使用 CryptoJS 加密并使用 PHP 解密
在客户端(移动设备),我使用 CryptoJS 加密用户密码:
On the client side (mobile device) I encrypt a users password with CryptoJS:
var lib_crypt = require('aes');
$.loginButton.addEventListener('click', function(e){
var key = lib_crypt.CryptoJS.enc.Hex.parse('bcb04b7e103a0cd8b54763051cef08bc55abe029fdebae5e1d417e2ffb2a00a3');
var iv = lib_crypt.CryptoJS.enc.Hex.parse('101112131415161718191a1b1c1d1e1f');
var encrypted = lib_crypt.CryptoJS.AES.encrypt($.passwordInput.value, key, { iv: iv });
var password_base64 = encrypted.ciphertext.toString(lib_crypt.CryptoJS.enc.Base64);
return password_base64;
});
在服务器端,我想用 mcrypt_decrypt 解密:
On the server side i want to decrypt it with mcrypt_decrypt:
function decryptPassword($password)
{
$key = pack('H*', "bcb04b7e103a0cd8b54763051cef08bc55abe029fdebae5e1d417e2ffb2a00a3");
$ciphertext_dec = base64_decode($password);
$iv_dec = "101112131415161718191a1b1c1d1e1f";
$ciphertext_dec = substr($ciphertext_dec, 16);
$decryptedPassword = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $ciphertext_dec, MCRYPT_MODE_CBC, $iv_dec);
return trim($decryptedPassword);
}
我使用相同的密钥和 IV,我做错了什么?
I use the same key and IV, what do I do wrong?
推荐答案
双方的做法不同.
您确实在 CryptoJS 中解析了 IV,但忘记在 PHP 中解析:
You did parse the IV in CryptoJS, but forgot to do it in PHP:
$iv_dec = pack('H*', "101112131415161718191a1b1c1d1e1f");
为了修复您的 IV 错误,您可能注意到前 16 个字节是乱码.当 IV 错误时就会发生这种情况.注意 CryptoJS 默认使用 CBC 模式,所以 IV 只影响解密时的第一个块.删除:
To fix that your IV is wrong, you probably noticed that the first 16 bytes are gibberish. That happens when the IV is wrong. Note that CryptoJS uses CBC mode by default, so the IV has only influence on the first block during decryption. Remove this:
$ciphertext_dec = substr($ciphertext_dec, 16);
填充
您可能注意到大多数明文都没有正确输出.它们以一些奇怪的重复字符结尾.这是 CryptoJS 中默认应用的 PKCS#7 填充.您必须自己在 PHP 中删除填充.好消息是 Maarten Bodewes 为这个这里提供了适当的复制粘贴解决方案.
Padding
You probably noticed that most plaintexts don't come out right. They end with some strange repeated characters at the end. This is the PKCS#7 padding that is applied by default in CryptoJS. You have to remove the padding yourself in PHP. Good thing is that Maarten Bodewes has provided a proper copy paste solution for this here.
trim()
可能适用于 ZeroPadding,但不适用于使用 PKCS#7 中定义的适当填充方案时.您可以完全删除 trim()
调用,因为它没有用,并且可能会导致意外的明文,因为零字节和空格从头到尾都被修剪了.
trim()
might be appropriate for ZeroPadding, but not when a proper padding scheme like the one defined in PKCS#7 is used. You may remove the trim()
call altogether, because it is not useful and may result in unexpected plaintext, becauses zero bytes and whitespace is trimmed from the beginning and end.
相关文章