Skip to main content

Use CryptoJS for MD5 and AES Encryption and Decryption of Request Parameters

tip

EchoAPI has built-in CryptoJS (https://github.com/brix/crypto-js), which makes it convenient to perform various encryption and decryption on request parameters.

MD5 Encryption

CryptoJS.MD5('string to be encrypted').toString()

image.png

SHA256 Encryption

CryptoJS.SHA256('string to be encrypted').toString()

image.png

Base64 Encryption

CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse('string to be encrypted'))

image.png

Base64 Decryption

CryptoJS.enc.Base64.parse("string to be decrypted").toString(CryptoJS.enc.Utf8)

image.png

Simple AES Encryption

CryptoJS.AES.encrypt('string to be encrypted', 'secret key').toString()

image.png

Simple AES Decryption

CryptoJS.AES.decrypt('string to be decrypted', 'secret key').toString(CryptoJS.enc.Utf8)

image.png

Custom AES Encryption and Decryption Functions

The above examples are two simple AES encryption and decryption schemes. In most cases, we need to customize more parameters for AES encryption and decryption, such as encryption mode, padding, etc.

const key = CryptoJS.enc.Utf8.parse("secret key");  // Sixteen hexadecimal digits as the key
const iv = CryptoJS.enc.Utf8.parse('initialization vector'); // Sixteen hexadecimal digits as the key offset

// Decryption method
function Decrypt(word) {
let encryptedHexStr = CryptoJS.enc.Hex.parse(word);
let srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
let decrypt = CryptoJS.AES.decrypt(srcs, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
return decryptedStr.toString();
}

// Encryption method
function Encrypt(word) {
let srcs = CryptoJS.enc.Utf8.parse(word);
let encrypted = CryptoJS.AES.encrypt(srcs, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
return encrypted.ciphertext.toString().toUpperCase();
}

// In the above methods, mode is the encryption mode, and padding is the padding.

Request Example

image.png