前端Aes-128-ecb加密解密

管理员

安装: npm install crypto-js

注意密码需要16位

import utf8 from 'crypto-js/enc-utf8';
import aes from 'crypto-js/aes';
import ecb from 'crypto-js/mode-ecb';
import pkcs7 from 'crypto-js/pad-pkcs7';

/**
* Aes-128-ecb加密
*/
export const encryptAes128 = (key = "qweasd7890123456", value) => {
    if (key?.length !== 16) {
        key = "qweasd7890123456"
    }
    let sKey = utf8.parse(key);
    let sValue = utf8.parse(value);
    let result = aes.encrypt(sValue, sKey, { mode: ecb, padding: pkcs7 });
    return result.toString()
}


/**
* Aes-128-ecb解密
*/
export const decryptionAes128 = (key = "qweasd7890123456", value) => {
    if (!value) return JSON.stringify("")

    try {
        if (key?.length !== 16) {
            key = "qweasd7890123456"
        }
        let sKey = utf8.parse(key);
        let result = aes.decrypt(value, sKey, { mode: ecb, padding: pkcs7 })
        return utf8.stringify(result).toString();
    } catch {
        return JSON.stringify("")
    }

}