php中java加密方法的转换
下面是用java编写的加密方法,我正试图用php进行转换
public static String encryptWithAesCtrNoPadding(final String key, final String value)
throws IOException {
try {
byte[] encKey = Arrays.copyOf(key.getBytes("UTF-8"), 16);
SecretKeySpec secretKey = new SecretKeySpec(encKey, "AES");
Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(new byte[16]));
return Hex.encodeHexString(cipher.doFinal(value.getBytes("UTF-8")));
} catch (Exception ex) {
throw new IOException(ex.getMessage());
}
}
我尝试了几种在线解释的方法,但两个函数的加密值不匹配
下面是到目前为止我得到的最接近的解决方案,但没有得到所需的输出
<?php
function do_encryption(String $key, String $value)
{
$iv = "0000000000000000"; //base64_encode(openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-128-cbc')));
$encodedEncryptedData = bin2hex(openssl_encrypt($value, "AES-128-CTR", $key, OPENSSL_RAW_DATA, substr(($iv) , 0, 16)));
}
do_encryption("secret", "1234567890");
?>
非常感谢您为解决此问题提供的任何帮助。谢谢
# 1 楼答案
Java的AES CTR实现和PHP OpenSSL的AES CTR实现在使用相同数据(加密密钥、初始化向量和明文)馈送时提供相同的密文
在下面,您会发现两个程序都使用了不安全的固定IV(出于演示目的)-永远不要在实际程序中使用固定IV
Java端的结果是:
PHP端的结果也是一样的:
安全警告:以下代码使用静态IV和静态(硬编码)钥匙,仅用于教育目的:
爪哇:
PHP: