問題描述
在客戶端(移動(dòng)設(shè)備),我使用 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;
});
在服務(wù)器端,我想用 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,我做錯(cuò)了什么?
I use the same key and IV, what do I do wrong?
推薦答案
雙方的做法不同.
您確實(shí)在 CryptoJS 中解析了 IV,但忘記在 PHP 中解析:
You did parse the IV in CryptoJS, but forgot to do it in PHP:
$iv_dec = pack('H*', "101112131415161718191a1b1c1d1e1f");
為了修復(fù)您的 IV 錯(cuò)誤,您可能注意到前 16 個(gè)字節(jié)是亂碼.當(dāng) IV 錯(cuò)誤時(shí)就會(huì)發(fā)生這種情況.注意 CryptoJS 默認(rèn)使用 CBC 模式,所以 IV 只影響解密時(shí)的第一個(gè)塊.刪除:
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);
填充
您可能注意到大多數(shù)明文都沒有正確輸出.它們以一些奇怪的重復(fù)字符結(jié)尾.這是 CryptoJS 中默認(rèn)應(yīng)用的 PKCS#7 填充.您必須自己在 PHP 中刪除填充.好消息是 Maarten Bodewes 為這個(gè)這里提供了適當(dāng)?shù)膹?fù)制粘貼解決方案.
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 中定義的適當(dāng)填充方案時(shí).您可以完全刪除 trim()
調(diào)用,因?yàn)樗鼪]有用,并且可能會(huì)導(dǎo)致意外的明文,因?yàn)榱阕止?jié)和空格從頭到尾都被修剪了.
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.
這篇關(guān)于使用 CryptoJS 加密并使用 PHP 解密的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!