鸿蒙 Crypto 库 AES 加密

鸿蒙 Crypto 库 AES 加密
最新回答
山间雾安

2021-06-28 12:40:11

在鸿蒙系统中使用CryptoJS库进行AES加密时,需通过解析密钥和IV、选择加密模式及补齐方式等步骤完成,具体操作如下:

1. 安装CryptoJS库
  • 从指定仓库安装三方库:npm install @ohos/crypto-js
  • 或通过Gitee地址安装:
    https://gitee.com/openharmony-sig/crypto-jsohpm
2. AES加密(CBC模式示例)
  • 参数准备:将密钥(key)和初始化向量(iv)从字符串解析为WordArray对象。

    const key = "0ada0f8609947992";const iv = "0ada0f8609947992";const info = "heihei"; // 待加密字符串const keyParse = CryptoJS.enc.Utf8.parse(key);const ivParse = CryptoJS.enc.Utf8.parse(iv);
  • 执行加密:生成Base64或Hex格式的密文。

    Base64格式

    const aesBase64 = CryptoJS.AES.encrypt(info, keyParse, { iv: ivParse,}).toString();// 输出示例:GFFC7wEfHgO0UzaDKVnZaw==

    Hex格式:通过ciphertext.toString()获取:

    const aesHex = CryptoJS.AES.encrypt(info, keyParse, { iv: ivParse,}).ciphertext.toString();// 输出示例:185142EF011F1E03B45336832959D96B
3. AES解密(Hex转Base64后解密)
  • Hex转Base64:若密文为Hex格式,需先转换为Base64。

    let encryptedHex = "185142EF011F1E03B45336832959D96B";encryptedHex = encryptedHex.replace(/n*$/g, '').replace(/n/g, ''); // 清理换行符const hexParsed = CryptoJS.enc.Hex.parse(encryptedHex);const base64 = CryptoJS.enc.Base64.stringify(hexParsed);
  • 执行解密:使用相同的密钥和IV解密Base64密文。

    const keyParse = CryptoJS.enc.Utf8.parse(key);const ivParse = CryptoJS.enc.Utf8.parse(iv);const decrypted = CryptoJS.AES.decrypt(base64, keyParse, { iv: ivParse,});const result = CryptoJS.enc.Utf8.stringify(decrypted); // 输出:heihei
4. 高级配置:加密模式与补齐方式
  • 支持模式

    CBC(默认):需提供iv。

    CFB/CTR/OFB:流加密模式,无需补齐。

    ECB:无需iv,但安全性较低。

    示例(CFB模式 + AnsiX923补齐):

    const encrypted = CryptoJS.AES.encrypt("Message", "Secret Passphrase", { mode: CryptoJS.mode.CFB, padding: CryptoJS.pad.AnsiX923});
  • 支持补齐方式

    Pkcs7(默认):标准PKCS#7补齐。

    Iso97971/AnsiX923/Iso10126:特定标准补齐。

    ZeroPadding/NoPadding:零补齐或无补齐。

5. 关键注意事项
  • 密钥与IV长度:AES-128需16字节,AES-256需32字节。若输入不足,需补齐或截断。
  • 编码一致性:密钥、IV和明文需统一使用Utf8.parse解析,避免编码错误。
  • 模式选择:CBC模式需确保iv随机且唯一;ECB模式不适用于加密重复数据。
  • 补齐影响:解密时需与加密时的补齐方式一致,否则可能失败。
6. 完整代码示例// 加密(CBC + Pkcs7)const key = "0ada0f8609947992"; // 16字节const iv = "0ada0f8609947992"; // 16字节const plaintext = "heihei";const keyParse = CryptoJS.enc.Utf8.parse(key);const ivParse = CryptoJS.enc.Utf8.parse(iv);// Base64密文const ciphertextBase64 = CryptoJS.AES.encrypt(plaintext, keyParse, { iv: ivParse }).toString();console.log("Base64:", ciphertextBase64);// 解密(Hex转Base64)const ciphertextHex = "185142EF011F1E03B45336832959D96B";const hexParsed = CryptoJS.enc.Hex.parse(ciphertextHex);const base64 = CryptoJS.enc.Base64.stringify(hexParsed);const decrypted = CryptoJS.AES.decrypt(base64, keyParse, { iv: ivParse });const result = CryptoJS.enc.Utf8.stringify(decrypted);console.log("解密结果:", result); // 输出:heihei

通过以上步骤,可高效完成鸿蒙系统中AES加密的配置与操作,同时支持灵活的模式和补齐方式调整。