@Entry
@Component
struct Index {
aboutToAppear(): void {
AesUtils.encryptCBC('测试hello', 'newaircloud_vjow9Dej#JDj4[oIDF', (str: string) => {
this.str = str
})
}
@State str?: string = ''
@State str2?: string = ''
build() {
Column() {
Text('AES加密:' + this.str)
.height(100)
.backgroundColor(Color.Pink)
.onClick(() => {
AesUtils.encryptCBC('测试hello', 'newaircloud_vjow9Dej#JDj4[oIDF', (str: string) => {
this.str = str
})
})
Text('AES解密:' + this.str2)
.height(100)
.backgroundColor(Color.Pink)
.onClick(() => {
AesUtils.decryptCBC(this.str!, 'newaircloud_vjow9Dej#JDj4[oIDF', (str: string) => {
this.str2 = str
})
})
}
}
}
以下是工具类代码:
export class AesUtils {
static async encryptCBC(message: string, pk: string, callBack: Function) {
try {
let base64 = new util.Base64Helper();
let dataUnit = AesUtils.doMdBySync(pk)
let symKey = await AesUtils.genSymKeyByData(dataUnit);
let newBuf = buffer.from(buffer.from(message, 'utf-8').buffer);
let plainText: cryptoFramework.DataBlob = { data: new Uint8Array(newBuf.buffer) };
let encryptText = await AesUtils.encryptMessagePromise(symKey, plainText);
let encrypt = base64.encodeToStringSync(encryptText.data)
if (callBack) {
callBack(encrypt)
}
} catch (error) {
console.error(JSON.stringify(error));
if (callBack) {
let str = JSON.stringify(error)
callBack(str)
}
}
}
public static async decryptCBC(message: string, pk: string, callBack: Function) {
try {
let dataUnit = AesUtils.doMdBySync(pk)
let symKey = await AesUtils.genSymKeyByData(dataUnit);
let newBuf = buffer.from(buffer.from(message, 'utf-8').buffer);
let encryptText: cryptoFramework.DataBlob = { data: new Uint8Array(newBuf.buffer) };
let decryptText = await AesUtils.decryptMessagePromise(symKey, encryptText);
if (decryptText.data.toString()) {
let decrypt = buffer.from(decryptText.data).toString('utf-8')
if (callBack) {
callBack(decrypt)
}
} else {
if (callBack) {
callBack('decrypt failed')
}
}
} catch (error) {
if (callBack) {
let str = JSON.stringify(error)
callBack('decrypt failed' + str)
}
}
}
// key生成
private static async genSymKeyByData(symKeyData: Uint8Array) {
let symKeyBlob: cryptoFramework.DataBlob = { data: symKeyData };
let aesGenerator = cryptoFramework.createSymKeyGenerator('AES256');
let symKey = await aesGenerator.convertKey(symKeyBlob);
console.info('convertKey success:');
return symKey;
}
// 加密消息
private static async encryptMessagePromise(symKey: cryptoFramework.SymKey, plainText: cryptoFramework.DataBlob) {
let cipher = cryptoFramework.createCipher('AES256|CBC|PKCS7');
let iv = AesUtils.genIvParamsSpec();
await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, iv);
let cipherData = await cipher.doFinal(plainText);
return cipherData;
}
// 解密消息
private static async decryptMessagePromise(symKey: cryptoFramework.SymKey, cipherText: cryptoFramework.DataBlob) {
let decoder = cryptoFramework.createCipher('AES256|CBC|PKCS7');
let iv = AesUtils.genIvParamsSpec();
await decoder.init(cryptoFramework.CryptoMode.DECRYPT_MODE, symKey, iv);
let decryptData = await decoder.doFinal(cipherText);
return decryptData;
}
private static doMdBySync(key: string): Uint8Array {
let mdAlgName = 'SHA256'; // 摘要算法名
let md = cryptoFramework.createMd(mdAlgName);
let firstArray = new Uint8Array(buffer.from(key, 'utf-8').buffer)
md.updateSync({ data: firstArray });
let mdResult = md.digestSync();
let data = new util.Base64Helper().encodeToStringSync(mdResult.data)
console.info('[Sync]:Md result base64:' + data);
let hex = buffer.from(mdResult.data).toString('hex')
console.info('Md result hex:' + hex);
let mdLen = md.getMdLength();
console.info("md len: " + mdLen);
return mdResult.data
}
// iv生成
private static genIvParamsSpec(): cryptoFramework.IvParamsSpec {
let arr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; // 16 bytes
let dataIv = new Uint8Array(arr);
let ivBlob: cryptoFramework.DataBlob = { data: dataIv };
let ivParamsSpec: cryptoFramework.IvParamsSpec = {
algName: "IvParamsSpec",
iv: ivBlob
};
return ivParamsSpec;
}
}
由于传入数据为base64加密,解码前要base64进行一次decodeSync。