我有一个Java程序,可以使用256位密钥使用AES/ECB/PKCS5Padding
密码加密,我想写一个产生相同结果的PHP脚本。
但是,我的脚本没有这样做。我有点觉得他们在加密问题之前如何处理密钥,但我无法分辨。
有人能指出PHP脚本中的错误吗?
感谢。
以下是示例代码,您可以在copy& amp;粘贴:
Java
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.MessageDigest;
public class JavaCipher {
private SecretKeySpec secretKey;
private JavaCipher(String secret) throws Exception {
MessageDigest sha = MessageDigest.getInstance("SHA-256");
byte[] digest = sha.digest(secret.getBytes("UTF-8"));
secretKey = new SecretKeySpec(digest, "AES");
}
private String encrypt(String sSrc) throws Exception {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encrypted = cipher.doFinal(sSrc.getBytes());
return DatatypeConverter.printHexBinary(encrypted).toLowerCase();
}
public static void main(String[] args) throws Exception {
JavaCipher cipher = new JavaCipher("some random key");
// print d013acccb5d191a00898ac87057383ff
System.out.println(cipher.encrypt("abcdefg"));
}
}
PHP
<?php
class PHPCipher {
private $key;
public function __construct($key)
{
$this->key = substr(hash('sha256', $key), 0, 32);
}
public function encrypt($data)
{
$size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
$td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
mcrypt_generic_init($td, $this->key, $iv);
$result = mcrypt_generic($td, $this->pad($data, $size));
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return bin2hex($result);
}
private function pad($text, $blocksize)
{
$pad = $blocksize - (strlen($text) % $blocksize);
return $text . str_repeat(chr($pad), $pad);
}
}
$cipher = new PHPCipher('some random key');
// print 9a4df66d67a3e8d4a1dda7cda6e94d07
echo $cipher->encrypt('abcdefg');
答案 0 :(得分:0)
由于密钥大小为256位的AES是我所需要的,所以我需要做的就是提供一个32字节的密钥。
而不是将字符串剪切成32个字符(这会改变键):
$this->key = substr(hash('sha256', $key), 0, 32);
我应该把它打包成二进制字符串
$this->key = pack('H*', hash('sha256', $key));