HarmonyOS 鸿蒙Next AES256解密
HarmonyOS 鸿蒙Next AES256解密
let key: string = “A”
let encryptText: string = “B”
假设后端给了一个 key 字符串, 一个使用这个key加密后的 encryptText 字符串
我们这边怎么对 encryptText 进行解密,还原成本来的字符串
使用 ‘AES256|ECB|PKCS7’ 模式
2 回复
import { cryptoFramework } from '@kit.CryptoArchitectureKit';
import { buffer, util } from '@kit.ArkTS';
// 解密消息
function decryptMessage(symKey: cryptoFramework.SymKey, cipherText: cryptoFramework.DataBlob) {
let decoder = cryptoFramework.createCipher('AES256|ECB|PKCS7');
decoder.initSync(cryptoFramework.CryptoMode.DECRYPT_MODE, symKey, null);
let decryptData = decoder.doFinalSync(cipherText);
return decryptData;
}
async function 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;
}
async function main() {
try {
let encryptText = 'ORar1vPTO9kStZ5A7Vxe5w==' //后端加密字符串
let keystr = 'nu08bq17tu6xqu8psdhywquiokm12hqw' //后端32位key字符串
let base64Helper = new util.Base64Helper();
let keyData = stringToUint8Array(keystr)
let symKey = await genSymKeyByData(keyData);
let plainText: cryptoFramework.DataBlob = { data: base64Helper.decodeSync(encryptText) };
let decryptText = decryptMessage(symKey, plainText);
console.info('decrypt plainText: ' + buffer.from(decryptText.data).toString('utf-8')); //输出解密结果
} catch (error) {
console.error(`AES ECB “${error}“, error code: ${error.code}`);
}
}
@Entry
@Component
struct AESDemo2 {
@State message: string = '点击进行解密';
build() {
RelativeContainer() {
Text(this.message)
.id('AESDemo2HelloWorld')
.fontSize(50)
.fontWeight(FontWeight.Bold)
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Center },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
.onClick(() => {
main()
})
}
.height('100%')
.width('100%')
}
}
function stringToUint8Array(str: string) {
return new Uint8Array(buffer.from(str, 'utf-8').buffer);
}
更多关于HarmonyOS 鸿蒙Next AES256解密的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html