我尝试将加密和解密函数转换为在 Java 中用于以下 PHP。但收到非法密钥大小错误。建议我在 java 中进行 256 位 AES 解密。
PHP 代码
<?php
function encrypt ($data,$salt) {
$hash = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($salt), $data, MCRYPT_MODE_CBC, md5(md5($salt))));
return $hash;
}
function decrypt ($encdata,$salt) {
$string = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($salt), base64_decode($encdata), MCRYPT_MODE_CBC, md5(md5($salt)));
return $string;
}
?>
转换后的 Java 代码:
//The below code found in http://www.logikdev.com/2010/11/01/encrypt-with-php-decrypt-with-java/
public static String md5(String input) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] messageDigest = md.digest(input.getBytes());
BigInteger number = new BigInteger(1, messageDigest);
return number.toString(16);
}
public String decrypt(String encryptedData) {
String decryptedData = null;
try {
SecretKeySpec skeySpec = new SecretKeySpec(md5("5A17K3Y").getBytes(), "AES");
String initialVectorString=md5(md5("5A17K3Y"));
IvParameterSpec initialVector = new IvParameterSpec(initialVectorString.getBytes());
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding","SunJCE");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, initialVector);
encryptedData=encryptedData.replace('-','+').replace('_','/').replace(',','=');
byte[] encryptedByteArray = (new org.apache.commons.codec.binary.Base64()).decode((encryptedData.getBytes()));
byte[] decryptedByteArray = cipher.doFinal(encryptedByteArray);
decryptedData = new String(decryptedByteArray, "UTF8");
} catch (Exception e) {
System.out.println("Error. Problem decrypting the data: " + e);
}
}
解密数据时出现问题:java.security.InvalidKeyException:非法密钥大小