#鸿蒙通关秘籍#对称加密有没有实现过的?我自己搞了一个老验证失败呢?

HarmonyOS
2024-12-09 10:59:54
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
SSD孤星泪

这里边对称加密跟大多数平台差不多,主要是你看好对应的类型就好了

import { cryptoFramework } from '@kit.CryptoArchitectureKit';
import { buffer } from '@kit.ArkTS';

function generateRandom(len: number) {
let rand = cryptoFramework.createRandom();
let generateRandSync = rand.generateRandomSync(len);
return generateRandSync;
}

function genGcmParamsSpec() {
let ivBlob = generateRandom(12);
let arr = [1, 2, 3, 4, 5, 6, 7, 8]; let dataAad = new Uint8Array(arr);
let aadBlob: cryptoFramework.DataBlob = { data: dataAad };
arr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; 
let dataTag = new Uint8Array(arr);
let tagBlob: cryptoFramework.DataBlob = {
data: dataTag
};
let gcmParamsSpec: cryptoFramework.GcmParamsSpec = {
iv: ivBlob,
aad: aadBlob,
authTag: tagBlob,
algName: "GcmParamsSpec"
};
return gcmParamsSpec;
}
let gcmParams = genGcmParamsSpec();
async function encryptMessagePromise(symKey: cryptoFramework.SymKey, plainText: cryptoFramework.DataBlob) {
let cipher = cryptoFramework.createCipher('AES128|GCM|PKCS7');
await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, gcmParams);
let encryptUpdate = await cipher.update(plainText);
gcmParams.authTag = await cipher.doFinal(null);
return encryptUpdate;
}
async function decryptMessagePromise(symKey: cryptoFramework.SymKey, cipherText: cryptoFramework.DataBlob) {
let decoder = cryptoFramework.createCipher('AES128|GCM|PKCS7');
await decoder.init(cryptoFramework.CryptoMode.DECRYPT_MODE, symKey, gcmParams);
let decryptUpdate = await decoder.update(cipherText);
let decryptData = await decoder.doFinal(null);
if (decryptData == null) {
console.info('GCM decrypt success, decryptData is null');
}
return decryptUpdate;
}
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;
}
async function main() {
let keyData = new Uint8Array([83, 217, 231, 76, 28, 113, 23, 219, 250, 71, 209, 210, 205, 97, 32, 159]);
let symKey = await genSymKeyByData(keyData);
let message = "This is a test";
let plainText: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from(message, 'utf-8').buffer) };
let encryptText = await encryptMessagePromise(symKey, plainText);
let decryptText = await decryptMessagePromise(symKey, encryptText);
if (plainText.data.toString() === decryptText.data.toString()) {
console.info('decrypt ok');
console.info('decrypt plainText: ' + buffer.from(decryptText.data).toString('utf-8'));
} else {
console.error('decrypt failed');
}
}
已于2024-12-10 10:02:54修改
分享
微博
QQ
微信
回复
2024-12-09 12:49:44
相关问题
如何实现一个验证码弹窗子窗口
560浏览 • 1回复 待解决
HarmonyOS 有没有api实现DES加密
107浏览 • 1回复 待解决
有没有一个ARK UI组件库工程模版?
1036浏览 • 1回复 待解决