在使用php调用java接口时,遇到了两边加密结果不一致的问题。经过沟通发现接口方使用了SHA1PRNG算法,对原密码计算后做为Des的加密Key。
因此在php中也需要先对原密码做相应计算才能保持结果一致。
java加密
public static final String ALGORITHM = "DES"; public static final String TRANSFORMATION = "DES/ECB/PKCS5Padding"; public static String encrypt(String contents, String password) throws Exception { try { Cipher cipher = Cipher.getInstance(TRANSFORMATION); cipher.init(Cipher.ENCRYPT_MODE, generateKey(password)); byte[] output = cipher.doFinal(contents.getBytes("utf-8")); return new String(Base64.encodeBase64(output), "utf-8"); } catch (Exception e) { logger.error("加密失败:{}",e); } return null; } public static Key generateKey(String password) throws Exception { return generateKey(password.getBytes()); } public static Key generateKey(byte[] seed) throws Exception { KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM); SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG"); secureRandom.setSeed(seed); keyGenerator.init(56,secureRandom); Key key = keyGenerator.generateKey(); return key; }
php加密
$key = "012345"; $data = "1866666345"; $key = substr(openssl_digest(openssl_digest($key, \'sha1\', true), \'sha1\', true), 0, 16); $out = openssl_encrypt($data, \'DES-ECB\', $key, OPENSSL_RAW_DATA); echo base64_encode($out);
参考资料
https://www.cnblogs.com/qdpurple/p/10270593.html
https://blog.csdn.net/ranlv91/article/details/81916654
请发表评论