AES 加解密
npm install crypto-js
import cryptoJs from 'crypto-js';
加密CBC模式
export const encryptAes = (message: string, key: string, iv: string) => {
const keyHex = cryptoJs.enc.Utf8.parse(key);
const ivHex = cryptoJs.enc.Utf8.parse(iv);
const option = { iv: ivHex, mode: cryptoJs.mode.CBC, padding: cryptoJs.pad.Pkcs7 };
const encrypted = cryptoJs.AES.encrypt(message, keyHex, option);
const str = encrypted.toString();
return str;
};
加密ECB模式
export const encryptEcb = (word: string, key: string) =>{
const keyHex = cryptoJs.enc.Utf8.parse(key);
const text = cryptoJs.enc.Utf8.parse(word);
const option = { mode: cryptoJs.mode.ECB, padding: cryptoJs.pad.Pkcs7 };
const encrypted = cryptoJs.AES.encrypt(text, keyHex, option);
const str = encrypted.toString();
return str;
};
解密ECB模式
export const decryptEcb = (word: string, key: string) => {
const keyHex = cryptoJs.enc.Utf8.parse(key);
const option = { mode: cryptoJs.mode.ECB, padding: cryptoJs.pad.Pkcs7 };
const decrypt = cryptoJs.AES.decrypt(word, keyHex, option);
return cryptoJs.enc.Utf8.stringify(decrypt).toString();
}
base64 加密
export const base64Encode = (val: string) => {
const str = cryptoJs.enc.Utf8.parse(val);
const base64 = cryptoJs.enc.Base64.stringify(str);
return base64;
}
base64 解密
export const base64Decode = (val: string) => {
const words = cryptoJs.enc.Base64.parse(val);
const deBase64 = words.toString(cryptoJs.enc.Utf8);
return deBase64;
}
HmacSHA256加密 输出16进制
export const hmacSHA256 = (word: string, secretKey='6sDQ8JLsXoDkMWA') => {
const hash = cryptoJs.HmacSHA256(word, secretKey);
const hex16 = cryptoJs.enc.Hex.stringify(hash);
return hex16;
}
node:crypto Aes 加密ECB模式
let crypto = require('node:crypto')
let secret = 'w*s&=izikqujzaaq'
let key = secret
let iv = ''
let cipher = crypto.createCipheriv('aes-128-ecb', key, iv);
const ciphertext = cipher.update('12345', 'Utf8', 'base64') + cipher.final('base64');
node:crypto Aes 解密ECB模式
let crypto = require('node:crypto')
let secret = 'w*s&=izikqujzaaq'
let key = secret
let iv = ''
const decipher = crypto.createDecipheriv('aes-128-ecb', key, iv);
const receivedtext = decipher.update(ciphertext, 'base64', 'utf8') + decipher.final();