The rewritten title is: PHP version of CryptoJS aes encryption function
P粉329425839
P粉329425839 2023-08-31 23:20:42
0
2
579
<p>I'm trying to create a PHP equivalent of this JS code using CryptoJS: </p> <pre class="brush:php;toolbar:false;">function aesEncrypt (data) { const key = 'GSTEGSTEjdfheyhdHSHSHSHDHHDHmdjjdn12ndndn5r='; const iv = '\0'; const cipher = CryptoJS.AES.encrypt(data, CryptoJS.enc.Base64.parse(key), { iv: CryptoJS.enc.Utf8.parse(iv), // Parse IV padding: CryptoJS.pad.Pkcs7, mode: CryptoJS.mode.CBC }) return cipher.toString() }</pre> <p>The result of js code: pHjpwiyKq7Rf4dFcBMbm1w==</p> <p>This is PHP code I wrote by reading other stackoverflow questions. But it doesn't return the same result. </p> <pre class="brush:php;toolbar:false;">$plaintext = "plainText"; $method = 'aes-256-cbc'; $key = base64_encode("GSTEGSTEjdfheyhdHSHSHSHDHHDHmdjjdn12ndndn5r="); $iv = hex2bin('00000000000000000000000000000000'); $ciphertext = openssl_encrypt( $plaintext, $method, $key, OPENSSL_RAW_DATA, $iv ); $ciphertext = base64_encode($ciphertext); echo $ciphertext;</pre> <p>Result of PHP code: YJOMi2vISmEXIjUZls3MA==</p>
P粉329425839
P粉329425839

reply all(2)
P粉668019339

Try this:

function encryptData($data, $key, $iv) {
  $cipher = "aes-256-cbc";
  $options = OPENSSL_RAW_DATA;

  $encrypted = openssl_encrypt($data, $cipher, $key, $options, $iv);
  $encrypted = base64_encode($encrypted);

  return $encrypted;
}

$message = "消息";
$key = "我的秘密密钥";
$iv = "我的iv";

$encrypted = encryptData($message, $key, $iv);

echo $encrypted;
P粉639667504

In the PHP code, the key must be Base64 decoded , not Base64 encoded:

$key = base64_decode("GSTEGSTEjdfheyhdHSHSHSHDHHDHmdjjdn12ndndn5r=");

With this change, the required ciphertext is created.

Please note that if 0 is passed in the fourth parameter of the openssl_encrypt() call instead of OPENSSL_RAW_DATA, the encryption The file will be Base64 encoded by default. Therefore, explicitly Base64 encoding the ciphertext is unnecessary.


Please remember that static IVs are not safe. Typically during the encryption process, a random IV is generated and passed along with the ciphertext to the decryption party (usually spliced ​​together).

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template