我在尝试将一些代码从 JAVA“翻译”成 PHP 时遇到问题。
我已经尝试了很多功能,但我无法在两侧获得相同的结果。
Java代码
public static String encrypt(String text, String key, String charset) throws Exception {
byte[] keyBytes = Base64.decodeBase64(key);
SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] textBytes = text.getBytes(charset);
byte[] bytes = cipher.doFinal(textBytes);
return new String(Base64.encodeBase64(bytes), charset);
}
关键参数 -> "NWelNxflgZ+rjP0bo2gi2Q=="
文本参数 -> “我是一个测试”
字符集参数 -> "UTF-8"
算法常数 -> AES
结果 -> “13vh3qeuc+kN7NvcKwM6pw==”
PHP 代码
function encryptAES($text, $key)
{
$key = strtohex($key);
$encrypt = openssl_encrypt($text, 'aes128', $key, OPENSSL_RAW_DATA);
if (!$encrypt) {
throw new Exception('AES encryption error');
}
return base64_encode($encrypt);
}
function strtohex($x)
{
$s='';
foreach (str_split($x) as $c) $s.=sprintf("%02X",ord($c));
return($s);
}
关键参数 -> "NWelNxflgZ+rjP0bo2gi2Q=="
文本参数 -> “我是一个测试”
结果 -> “Vs5pwAC7PK0fQUQQ+PMhKw==”
谁能帮我解释一下为什么我的代码不起作用?
非常感谢你们。
最佳答案
已解决,问题是 strtohex 为您提供了输入控制台的密码。
public static function encryptAES($data, $AES_key)
{
$AES_key = base64_decode($AES_key);
$encrypt = openssl_encrypt($data, 'aes128', $AES_key);
if (!$encrypt) {
throw new Exception('AES encryption error');
}
return base64_encode($encrypt);
}
这是结果代码,它只是用base64_decode转换 key 。谢谢大家!
关于java - 在 JAVA 和 PHP 中加密返回不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55494874/