PHP and CryptoJS AES encryption and decryption communication
use
The name of the | value |
---|---|
model | CBC |
fill | Pkcs7 |
The length of the | 128 .key 和 iv The length of is16 |
The output | Base64 |
import * as CryptoJS from 'crypto-js'
/** * AES encryption *@param Plaintext expressly *@param Key Encryption key *@param Iv offset *@returns Cipher * /
export const AESencrypt = (plaintext, key, iv) = > {
key = CryptoJS.enc.Utf8.parse(key)
iv = CryptoJS.enc.Utf8.parse(iv)
const encryptedData = CryptoJS.AES.encrypt(plaintext, key, {
iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
})
return encryptedData.toString()
}
/** * AES decryption *@param Ciphertext ciphertext *@param Key Encryption key *@param Iv offset *@returns Clear * /
export const AESdecrypt = (ciphertext, key, iv) = > {
key = CryptoJS.enc.Utf8.parse(key)
iv = CryptoJS.enc.Utf8.parse(iv)
const decryptedData = CryptoJS.AES.decrypt(ciphertext, key, {
iv,
padding: CryptoJS.pad.Pkcs7
})
return decryptedData.toString(CryptoJS.enc.Utf8)
}
Copy the code
class AESHelper
{
public static function encrypt($data.$key.$iv)
{
return base64_encode(openssl_encrypt($data.'AES-128-CBC'.$key.1.$iv));
}
public static function decrypt($data.$key.$iv)
{
return openssl_decrypt(base64_decode($data), 'AES-128-CBC'.$key.1.$iv); }}Copy the code
Q&A
CryptoJS
You do not need to set the mode for decryption- Decryption failed,
Error: Malformed UTF-8 data
- Decryption failed, the result is empty string or garbled characters
Check the method
- The mode is not set correctly
- Padding Settings are incorrect
key
和iv
Is not correctkey
和iv
Untreated,const key = CryptoJS.enc.Utf8.parse(key)
// 'key' and 'iv' are correctly processed. Plaintext and ciphertext are not required
const key = CryptoJS.enc.Utf8.parse(key)
const iv = CryptoJS.enc.Utf8.parse(iv)
Copy the code
CryptoJS supports AES-128, AES-192, and AES-256. It will pick the variant by the size of the key you pass in. If you use a passphrase, then it will generate a 256-bit key
Cryptojs-standard library for JavaScript encryption and decryption
brix/crypto-js
Welcome to my wechat official account: Coder