//鸿蒙aes加密模式分为(GCM模式)加解密, (CBC模式)加解密, (GCM模式)分段式加解密, 这里写的是(CBC模式加解密)
import { cryptoFramework } from '@kit.CryptoArchitectureKit';
import { buffer } from '@kit.ArkTS';
// 获取IvParamsSpec 参数 加解密参数ParamsSpec的子类,用于在对称加解密时作为init()方法的参数。
export function genIvParamsSpec(ivstr:string){
let dataIv: Uint8Array = new Uint8Array(buffer.from(ivstr, 'utf-8').buffer);
let ivBlob: cryptoFramework.DataBlob = { data: dataIv};
let ivParamsSpec: cryptoFramework.IvParamsSpec = {
algName: "IvParamsSpec",
iv: ivBlob
};
return ivParamsSpec;
}
//加密消息
/*
*参数1 与后台约定的加密key 长度128位的字符串
* 参数2 需加密的消息
* 参数3 加密所需的iv
*/
async function encryptMessagePromise(symKey: cryptoFramework.SymKey, plainText: cryptoFramework.DataBlob, ivstr:string){
//初始化cipher 约定CBC 加密格式
let cipher = cryptoFramework.createCipher('AES128|CBC|PKCS7');
let iv = genIvParamsSpec(ivstr)
await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, iv);
let cipherData = await cipher.doFinal(plainText);
return cipherData; //获取加密后的消息
}
//解密消息
/*
* 参数1 与后台约定的加密key 长度128位的字符串
* 参数2 加密获取的消息
* 参数3 加密时获取的iv
*/
async function decryptMessagePromise(symKey: cryptoFramework.SymKey, cipherText: cryptoFramework.DataBlob, ivstr:string){
let decoder = cryptoFramework.createCipher('AES128|CBC|PKCS7');
let iv = genIvParamsSpec(ivstr);
await decoder.init(cryptoFramework.CryptoMode.DECRYPT_MODE, symKey, iv);
let decryptData = await decoder.doFinal(cipherText);
return decryptData;
}
/*
* 生成指定加密秘钥
*/
async function genSymKeyByData(symKeyData: Uint8Array) {
let symKeyBlob: cryptoFramework.DataBlob = { data: symKeyData };
let aesGenerator = cryptoFramework.createSymKeyGenerator('AES128');
let symKey = await aesGenerator.convertKey(symKeyBlob);
console.info('convertKey success');
return symKey;
}
/*
* 参数1 需要进行加密的字符串 可以是MD5格式
* 参数2 CBC模式所需的指定 iv字符串, 与后台约定, 需16位字符串
*/
export async function aesCBC (message:string, ivstr:string){
try{
let key:string = 'a1b2c3d4e5f6g7f8' //与后台约定的加密秘钥 自行修改
let keyData = new Uint8Array(buffer.from(key, 'utf-8').buffer)
let symKey = await genSymKeyByData(keyData);
let plainText: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from(message, 'utf-8').buffer) };
let encryptText = await encryptMessagePromise(symKey, plainText, ivstr);
let decryptText = await decryptMessagePromise(symKey, encryptText, ivstr);
if (plainText.data.toString() === decryptText.data.toString()) {
console.info('decrypt ok');
console.info('decrypt plainText: ' + buffer.from(decryptText.data).toString('utf-8'));
console.info('encrypt plainText: ' + buffer.from(encryptText.data).toString('utf-8'));
//Uint8Array 转字符串
let entryText = buffer.from(encryptText.data).toString('utf-8')
return buffer.from(encryptText.data).toString('base64')
} else {
console.error('decrypt failed');
return 'decrypt failed'
}
} catch (error){
console.error(`AES CBC “${error}“, error code: ${error.code}`);
return `AES CBC “${error}“, error code: ${error.code}`
}
}