HarmonyOS 鸿蒙Next中RSA加密方法的实现

发布于 1周前 作者 zlyuanteng 来自 鸿蒙OS

HarmonyOS 鸿蒙Next中RSA加密方法的实现

请求时需要对明文数据进行rsa加密

4 回复

参考如下SA加密算法demo:

import huks from '[@ohos](/user/ohos).security.huks';
import { BusinessError } from '[@ohos](/user/ohos).base';

let aesKeyAlias = 'test_rsaKeyAlias';
let handle: number;
let plainText = '123456';
let IV = '001122334455';
let cipherData: Uint8Array;

function StringToUint8Array(str: String) {
 let arr: number[] = new Array();
 for (let i = 0, j = str.length; i < j; ++i) {
   arr.push(str.charCodeAt(i));
 }
 return new Uint8Array(arr);
}

function Uint8ArrayToString(fileData: Uint8Array) {
 let dataString = '';
 for (let i = 0; i < fileData.length; i++) {
   dataString += String.fromCharCode(fileData[i]);
 }
 return dataString;
}

function GetRsaGenerateProperties() {
 let properties: Array<huks.HuksParam> = new Array();
 let index = 0;
 properties[index++] = {
   tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
   value: huks.HuksKeyAlg.HUKS_ALG_RSA
 };
 properties[index++] = {
   tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
   value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048
 };
 properties[index++] = {
   tag: huks.HuksTag.HUKS_TAG_DIGEST,
   value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
 };
 properties[index++] = {
   tag: huks.HuksTag.HUKS_TAG_PURPOSE,
   value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT |
   huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
 };
 properties[index++] = {
   tag: huks.HuksTag.HUKS_TAG_PADDING,
   value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5
 };
 properties[index++] = {
   tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
   value: huks.HuksCipherMode.HUKS_MODE_ECB
 };
 return properties;
}

function GetRsaEncryptProperties() {
 let properties: Array<huks.HuksParam> = new Array();
 let index = 0;
 properties[index++] = {
   tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
   value: huks.HuksKeyAlg.HUKS_ALG_RSA
 };
 properties[index++] = {
   tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
   value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048
 };
 properties[index++] = {
   tag: huks.HuksTag.HUKS_TAG_DIGEST,
   value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
 };
 properties[index++] = {
   tag: huks.HuksTag.HUKS_TAG_PURPOSE,
   value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT
 };
 properties[index++] = {
   tag: huks.HuksTag.HUKS_TAG_PADDING,
   value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5
 };
 properties[index++] = {
   tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
   value: huks.HuksCipherMode.HUKS_MODE_ECB
 };
 // properties[index++] = {
 // tag: huks.HuksTag.HUKS_TAG_IV,
 // value: StringToUint8Array(IV)
 // }
 return properties;
}

function GetRsaDecryptProperties() {
 let properties: Array<huks.HuksParam> = new Array();
 let index = 0;
 properties[index++] = {
   tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
   value: huks.HuksKeyAlg.HUKS_ALG_RSA
 };
 properties[index++] = {
   tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
   value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048
 };
 properties[index++] = {
   tag: huks.HuksTag.HUKS_TAG_DIGEST,
   value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
 };
 properties[index++] = {
   tag: huks.HuksTag.HUKS_TAG_PURPOSE,
   value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
 }
 properties[index++] = {
   tag: huks.HuksTag.HUKS_TAG_PADDING,
   value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5
 }
 properties[index++] = {
   tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
   value: huks.HuksCipherMode.HUKS_MODE_ECB
 }
 // properties[index++] = {
 // tag: huks.HuksTag.HUKS_TAG_IV,
 // value: StringToUint8Array(IV)
 // }
 return properties;
}

export async function GenerateRsaKey() {
 /*
 * 模拟生成密钥场景
 * 1. 确定密钥别名
 */
 /*
 * 2. 获取生成密钥算法参数配置
 */
 let genProperties = GetRsaGenerateProperties();
 let options: huks.HuksOptions = {
   properties: genProperties
 }
 /*
 * 3. 调用generateKeyItem
 */
 await huks.generateKeyItem(aesKeyAlias, options)
   .then((data) => {
     console.info(`promise: generate RSA Key success, data = ${JSON.stringify(data)}`);
   }).catch((error: BusinessError) => {
     console.error(`promise: generate RSA Key failed` + error);
   })
}

export async function EncryptData() {
 /*
 * 模拟加密场景
 * 1. 获取密钥别名
 */
 /*
 * 2. 获取待加密的数据
 */
 /*
 * 3. 获取加密算法参数配置
 */
 let encryptProperties = GetRsaEncryptProperties();
 let options: huks.HuksOptions = {
   properties: encryptProperties,
   inData: StringToUint8Array(plainText)
 }
 /*
 * 4. 调用initSession获取handle
 */
 await huks.initSession(aesKeyAlias, options)
   .then((data) => {
     handle = data.handle;
   }).catch((error: BusinessError) => {
     console.error(`promise: init EncryptData failed` + error);
   })
 /*
 * 5. 调用finishSession获取加密后的密文
 */
 await huks.finishSession(handle, options)
   .then((data) => {
     console.info(`promise: encrypt data success, data is ` + Uint8ArrayToString(data.outData as Uint8Array));
     cipherData = data.outData as Uint8Array;
   }).catch((error: BusinessError) => {
     console.error(`promise: encrypt data failed` + error);
   })
}

export async function DecryptData() {
 /*
 * 模拟解密场景
 * 1. 获取密钥别名
 */
 /*
 * 2. 获取待解密的密文
 */
 /*
 * 3. 获取解密算法参数配置
 */
 let decryptOptions = GetRsaDecryptProperties()
 let options: huks.HuksOptions = {
   properties: decryptOptions,
   inData: cipherData
 }
 /*
 * 4. 调用initSession获取handle
 */
 await huks.initSession(aesKeyAlias, options)
   .then((data) => {
     handle = data.handle;
   }).catch((error: BusinessError) => {
     console.error(`promise: init DecryptData failed` + error);
   })
 /*
 * 5. 调用finishSession获取解密后的数据
 */
 await huks.finishSession(handle, options)
   .then((data) => {
     console.info(`promise: decrypt data success, data is ` + Uint8ArrayToString(data.outData as Uint8Array));
   }).catch((error: BusinessError) => {
     console.error(`promise: decrypt data failed` + error);
   })
}

async function DeleteKey() {
 /*
 * 模拟删除密钥场景
 * 1. 获取密钥别名
 */
 let emptyOptions: huks.HuksOptions = {
   properties: []
 }
 /*
 * 2. 调用deleteKeyItem删除密钥
 */
 await huks.deleteKeyItem(aesKeyAlias, emptyOptions)
   .then((data) => {
     console.info(`promise: delete data success`);
   }).catch((error: BusinessError) => {
     console.error(`promise: delete data failed` + error);
   })
}

export async function rsa_test() {
 await GenerateRsaKey()
 await EncryptData()
 await DecryptData()
}
API文档中有提供加密算法,我如果赶工期你可以看看OpenHarmony三方库,不敢还是写一遍

大致思路:

 1. 实现一个公共的加密和解密的算法, 
 2. 拦截系统的请求. 如果有参数调用(1) 中的方法进行加密.

 
基于原生的cryptoFramework, 实现的RSA加密方法的demo:


https://gitee.com/harmonyos_samples/crypto-collection

ps:  加密和结果可能都是Uint8Array, 需要利用buffer进行一次数据转换才可以.
2. 如果嫌原生数据类型转换麻烦, 可以使用前端加密算法封装的一个三方库连接

在HarmonyOS鸿蒙Next中实现RSA加密,可以通过以下步骤进行:

首先,需要生成RSA非对称密钥对。调用cryptoFramework.createAsyKeyGeneratorAsyKeyGenerator.generateKeyPair,生成RSA密钥类型为RSA1024、素数个数为2(默认)的非对称密钥对(KeyPair),KeyPair对象中包括公钥(PubKey)和私钥(PriKey)。

其次,创建Cipher实例并初始化。调用cryptoFramework.createCipher,指定字符串参数’RSA1024|PKCS1’,创建非对称密钥类型为RSA1024、填充模式为PKCS1的Cipher实例。调用Cipher.init,设置模式为加密(CryptoMode.ENCRYPT_MODE),指定加密密钥(KeyPair.PubKey),初始化加密Cipher实例。

最后,进行加密操作。由于RSA算法限制,明文需要按固定长度(如64字节)分组,多次调用Cipher.doFinal传入明文,获取加密后的数据。每次加密将生成固定长度(对于1024位密钥为128字节)的密文。

示例代码可参考HarmonyOS官方文档或相关开发社区。如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html

回到顶部