AES128|CBC|PKCS7的加解密 在鸿蒙是可以实现的 请参考以下代码 使用您的IV : AAAAAAAAAAAAAAAA 和 key: BBBBBBBBBBBBBBBB 进行的加解密
import { cryptoFramework } from '@kit.CryptoArchitectureKit';
import { buffer, util } from '@kit.ArkTS';
@Entry
@Component
struct AESCBCCrypto {
@State message: string = '点击开始';
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(() => {
aesCBC()
})
}
.width('100%')
}
.height('100%')
}
}
// 生成IV
function genIvParamsSpec() {
let iv = new Uint8Array(buffer.from('AAAAAAAAAAAAAAAA', 'utf-8').buffer);
let ivBlob: cryptoFramework.DataBlob = { data: iv };
let ivParamsSpec: cryptoFramework.IvParamsSpec = {
algName: "IvParamsSpec",
iv: ivBlob
};
return ivParamsSpec;
}
// 加密消息
function encryptMessage(symKey: cryptoFramework.SymKey, plainText: cryptoFramework.DataBlob) {
let cipher = cryptoFramework.createCipher('AES128|CBC|PKCS7');
let iv = genIvParamsSpec();
cipher.initSync(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, iv);
let cipherData = cipher.doFinalSync(plainText);
return cipherData;
}
// 解密消息
function decryptMessage(symKey: cryptoFramework.SymKey, cipherText: cryptoFramework.DataBlob) {
let decoder = cryptoFramework.createCipher('AES128|CBC|PKCS7');
let iv = genIvParamsSpec();
decoder.initSync(cryptoFramework.CryptoMode.DECRYPT_MODE, symKey, iv);
// let decryptData = decoder.updateSync(cipherText);
let decryptData = decoder.doFinalSync(cipherText);
return decryptData;
}
// 转换密钥
function genSymKeyByData(symKeyData: Uint8Array) {
let symKeyBlob: cryptoFramework.DataBlob = { data: symKeyData };
let aesGenerator = cryptoFramework.createSymKeyGenerator('AES128');
let symKey = aesGenerator.convertKeySync(symKeyBlob);
console.info('convertKey success');
return symKey;
}
function aesCBC() {
try {
let base64 = new util.Base64Helper();
let pk = "BBBBBBBBBBBBBBBB";
let key = new Uint8Array (buffer.from(pk, 'utf-8').buffer)
console.error("key "+ key)
let symKey = genSymKeyByData(key);
let text = "hello,world!";
let newBuf = buffer.from(buffer.from(text, 'utf-8').buffer);
let plainText: cryptoFramework.DataBlob = { data: new Uint8Array(newBuf.buffer) };
let encryptText = encryptMessage(symKey, plainText);
console.error('encrypt 16进制 plainText: ' + buffer.from(encryptText.data).toString('hex'));
console.error('encrypt base64 plainText: ' + base64.encodeToStringSync(encryptText.data));
let decryptText = decryptMessage(symKey, encryptText);
console.error('decrypt plainText: ' + buffer.from(decryptText.data).toString('utf-8'));
console.error('decrypt ok' + decryptText.data.toString());
}catch (error){
console.error(JSON.stringify(error));
}
}
输出 :
key : 66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66
encrypt 16进制 plainText: 0da102514cf5bb853131bc21bc8a187b
encrypt base64 plainText: DaECUUz1u4UxMbwhvIoYew==
decrypt plainText: hello,world!
decrypt ok 104,101,108,108,111,44,119,111,114,108,100,33