簡體   English   中英

PHP 中的 AES 加密和 Javascript 中的解密

[英]AES Encryption in PHP and Decryption in Javascript

我有一個應用程序,我在其中使用 AES CBC 128 算法加密 json 編碼數組,然后在 javascript(React/Next Js Project)中解密它。 我在 php 中的加密如下面的代碼所示

加密 PHP


$plaintext = "message to be encrypted";
$ivlen = openssl_cipher_iv_length($cipher="AES-128-CBC");
$iv = openssl_random_pseudo_bytes($ivlen);
$ciphertext_raw = openssl_encrypt($plaintext, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv);
$hmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary=true);
$ciphertext = base64_encode( $iv.$hmac.$ciphertext_raw );

我在 Javascript 中遇到解密問題

到目前為止我的代碼如下所示

 const baseenc = CryptoJS.enc.Base64.parse(cipher).toString();
  var encrypted = CryptoJS.AES.decrypt(cipher, key, { iv: iv }).toString();
  var plaintext = CryptoJS.enc.Latin1.stringify(encrypted);

任何人都可以請顯示錯誤是什么或幫助我獲得正確的 output

必須在 CryptoJS 代碼中實現以下步驟:

  • 分離IV、HMAC和密文(Base64解碼后)
  • 計算密文的 HMAC
  • 檢查密文的真實性。 如果接收和計算的 HMAC 相同,則密文是真實的。
  • 執行解密,只有密文是真實的

下面的代碼是一個可能的實現。 應用密鑰0123456789012345並使用 PHP 代碼生成使用的密文:

 var ciphertext = 'WqfMfCxKg7U7h5S1mbx7mSHOkkkIrUUpg++mX4ZdWt0I26VfKn7bsi60Oo/SIsWQGyC4dF5z081NvjTXwZGjIpguA0k/QqIM/GDEpCojaro='; var key = '0123456789012345'; // Convert key and ciphertext into WordArrays var ciphertextWA = CryptoJS.enc.Base64.parse(ciphertext); var keyWA = CryptoJS.enc.Utf8.parse(key); // Separate IV, HMAC and ciphertext var ivWA = CryptoJS.lib.WordArray.create(ciphertextWA.words.slice(0, 4)); var hmacWA = CryptoJS.lib.WordArray.create(ciphertextWA.words.slice(4, 4 + 8)); var actualCiphertextWA = CryptoJS.lib.WordArray.create(ciphertextWA.words.slice(4 + 8)); // Authenticate var hmacCalculatedWA = CryptoJS.HmacSHA256(actualCiphertextWA, keyWA); if(CryptoJS.enc.Base64.stringify(hmacCalculatedWA) === CryptoJS.enc.Base64.stringify(hmacWA)) { // Decrypt if authentication is successfull var decryptedMessageWA = CryptoJS.AES.decrypt({ciphertext: actualCiphertextWA}, keyWA, {iv: ivWA}); var decryptedMessage = CryptoJS.enc.Utf8.stringify(decryptedMessageWA); console.log(decryptedMessage); } else { console.log('Authentication failed;'); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js"></script>

請注意,最好使用不同的密鑰進行加密和身份驗證,請參見此處

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM