The rewritten title is: PHP version of CryptoJS aes encryption function
P粉329425839
P粉329425839 2023-08-31 23:20:42
0
2
357
<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(1)
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!