#HarmonyOS NEXT体验官# 数据加密 4.加解密之二-鸿蒙开发者社区-51CTO.COM

#HarmonyOS NEXT体验官# 数据加密 4.加解密之二 原创

入门大师小波哥
发布于 2024-8-16 14:14
浏览
0收藏
import cryptoFramework from '@ohos.security.cryptoFramework';
import buffer from '@ohos.buffer';
function genIvParamsSpec() {
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;
}

// 加密消息
async function encryptMessagePromise(symKey:
cryptoFramework.SymKey, plainText: cryptoFramework.DataBlob) {
let cipher = cryptoFramework.createCipher('AES128|CBC|PKCS7');
let iv = genIvParamsSpec();
await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE,
symKey, iv);
let cipherData = await cipher.doFinal(plainText);
return cipherData;
}

// 解密消息
async function decryptMessagePromise(symKey:
cryptoFramework.SymKey, cipherText: cryptoFramework.DataBlob)
{
let decoder =
cryptoFramework.createCipher('AES128|CBC|PKCS7');
let iv = genIvParamsSpec();
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;
}
async function aesCBC() {
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');
}
}


使用AES对称密钥(GCM模式)分段加密
⚫ 调用cryptoFramework.createSymKeyGenerator、SymKeyGenerator.generateSymKey,
生成密钥算法为AES、密钥长度为128位的对称密钥(SymKey)。
⚫ 如何生成AES对称密钥,开发者可参考下文示例,并结合对称密钥生成和转换规格:AES和随
机生成对称密钥理解,参考文档与当前示例可能存在入参差异,请在阅读时注意区分。
⚫ 调用cryptoFramework.createCipher,指定字符串参数’AES128|GCM|PKCS7’,创建对称密
钥类型为AES128、分组模式为GCM、填充模式为PKCS7的Cipher实例,用于完成加解密操
作。
⚫ 调用Cipher.init,设置模式为加密(CryptoMode.ENCRYPT_MODE),指定加密密钥
(SymKey)和GCM模式对应的加密参数(GcmParamsSpec),初始化加密Cipher实例。

将一次传入数据量设置为20字节,多次调用Cipher.update,更新数据(明文)。
⚫ 当前单次update长度没有限制,开发者可以根据数据量判断如何调用update。
⚫ 建议开发者对每次update的结果都判断是否为null,并在结果不为null时取出其中的数据进行
拼接,形成完整的密文。因为在不同的规格下,update的结果可能会受到不同影响。
⚫ 1)比如ECB和CBC模式,始终以分组作为基本单位来加密,并输出本次update产生的加密分
组结果。即当本次update操作凑满一个分组就输出密文,没有凑满则此次update输出null,
将未加密的数据与下次输入的数据拼接凑分组再输出。等到最后doFinal的时候,将未加密的
数据,根据指定的填充模式进行填充,在输出剩余加密结果。解密过程中的update同理。
⚫ 2)对于流加密模式(比如CTR和OFB模式),通常密文长度和明文长度相等。

调用Cipher.doFinal,获取加密后的数据。
⚫ 由于已使用update传入数据,此处data传入null。
⚫ doFinal输出结果可能为null,在访问具体数据前,需要先判断结果是否为null,避免
产生异常。
⚫ 读取GcmParamsSpec.authTag作为解密的认证信息。在GCM模式下,需要从加密后
的数据中取出末尾16字节,作为解密时初始化的认证信息。示例中authTag恰好为16
字节。

调用Cipher.init,设置模式为解密(CryptoMode.DECRYPT_MODE),指定
解密密钥(SymKey)和GCM模式对应的解密参数(GcmParamsSpec),初
始化解密Cipher实例。
⚫ 将一次传入数据量设置为20字节,多次调用Cipher.update,更新数据(密
文)。
⚫ 调用Cipher.doFinal,获取解密后的数据。

import cryptoFramework from '@ohos.security.cryptoFramework';
import buffer from '@ohos.buffer';
function genGcmParamsSpec() {
let arr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; // 12 bytes
let dataIv = new Uint8Array(arr);
let ivBlob: cryptoFramework.DataBlob = { data: dataIv };
arr = [0, 0, 0, 0, 0, 0, 0, 0]; // 8 bytes
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]; // 16 bytes
let dataTag = new Uint8Array(arr);
let tagBlob: cryptoFramework.DataBlob = {
data: dataTag
}; // The GCM authTag is obtained by doFinal() in encryption and passed in params of init() in decryption.
let gcmParamsSpec: cryptoFramework.GcmParamsSpec = {
iv: ivBlob,
aad: aadBlob,
authTag: tagBlob,
algName: "GcmParamsSpec"
};
return gcmParamsSpec;
}
let gcmParams = genGcmParamsSpec();

/ 分段加密消息
async function encryptMessageUpdateBySegment(symKey: cryptoFramework.SymKey, plainText: cryptoFramework.DataBlob) {
let cipher = cryptoFramework.createCipher('AES128|GCM|PKCS7');
await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, gcmParams);
let updateLength = 20; // 假设以20字节为单位进行分段update,实际并无要求
let cipherText = new Uint8Array();
for (let i = 0; i < plainText.data.length; i += updateLength) {
let updateMessage = plainText.data.subarray(i, i + updateLength);
let updateMessageBlob: cryptoFramework.DataBlob = { data: updateMessage };
// 分段update
let updateOutput = await cipher.update(updateMessageBlob);
// 把update的结果拼接起来,得到密文(有些情况下还需拼接doFinal的结果,这取决于分组模式
// 和填充模式,本例中GCM模式的doFinal结果只包含authTag而不含密文,所以不需要拼接)
let mergeText = new Uint8Array(cipherText.length + updateOutput.data.length);
mergeText.set(cipherText);
mergeText.set(updateOutput.data, cipherText.length);
cipherText = mergeText;
}
gcmParams.authTag = await cipher.doFinal(null);
let cipherBlob: cryptoFramework.DataBlob = { data: cipherText };
return cipherBlob;
}

// 分段解密消息
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 updateLength = 20; // 假设以20字节为单位进行分段update,实际并无要求
let decryptText = new Uint8Array();
for (let i = 0; i < cipherText.data.length; i += updateLength) {
let updateMessage = cipherText.data.subarray(i, i + updateLength);
let updateMessageBlob: cryptoFramework.DataBlob = { data: updateMessage };
// 分段update
let updateOutput = await decoder.update(updateMessageBlob);
// 把update的结果拼接起来,得到明文
let mergeText = new Uint8Array(decryptText.length + updateOutput.data.length);
mergeText.set(decryptText);
mergeText.set(updateOutput.data, decryptText.length);
decryptText = mergeText;
}
let decryptData = await decoder.doFinal(null);
if (decryptData == null) {
console.info('GCM decrypt success, decryptData is null');
}
let decryptBlob: cryptoFramework.DataBlob = { data: decryptText };
return decryptBlob;
}

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 aes() {
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 = "aaaaa.....bbbbb.....ccccc.....ddddd.....eee"; // 假设信息总共43字节,根据utf-8解码后,也是43字节
let plainText: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from(message, 'utf-8').buffer) };
let encryptText = await encryptMessageUpdateBySegment(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-8-16 17:59:46修改
收藏
回复
举报
回复
    相关推荐