HarmonyOS鸿蒙Next加解密-RSA-使用已有公私钥
HarmonyOS鸿蒙Next加解密-RSA-使用已有公私钥
介绍
提供通用的RSA加解密Demo
demo详情链接
https://gitee.com/scenario-samples/encrypt-message
2 回复
在HarmonyOS鸿蒙Next中,使用已有的RSA公私钥进行加解密可以通过cryptoFramework模块实现。首先,使用createAsyKeyGenerator创建RSA密钥生成器,然后通过convertKey方法将已有的公私钥转换为系统可识别的密钥对象。对于公钥加密,使用createCipher创建加密器,并调用init方法初始化加密模式,使用doFinal进行加密操作。对于私钥解密,同样创建解密器并初始化解密模式,使用doFinal进行解密操作。示例代码如下:
import cryptoFramework from '@ohos.security.cryptoFramework';
// 已有公钥和私钥的字符串
const publicKeyStr = '...'; // 已有公钥字符串
const privateKeyStr = '...'; // 已有私钥字符串
// 创建RSA密钥生成器
let rsaKeyGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024");
// 将字符串转换为公钥对象
let pubKeyBlob = { data: stringToUint8Array(publicKeyStr) };
rsaKeyGenerator.convertKey(pubKeyBlob, null, (err, publicKey) => {
if (err) {
console.error('Convert public key failed');
return;
}
// 使用公钥加密
let cipher = cryptoFramework.createCipher("RSA1024|PKCS1");
cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, publicKey, null, (err, data) => {
if (err) {
console.error('Init cipher failed');
return;
}
let plainText = 'Hello, HarmonyOS';
cipher.doFinal({ data: stringToUint8Array(plainText) }, (err, data) => {
if (err) {
console.error('Encrypt failed');
return;
}
console.info('Encrypted data: ' + uint8ArrayToString(data.data));
});
});
});
// 将字符串转换为私钥对象
let priKeyBlob = { data: stringToUint8Array(privateKeyStr) };
rsaKeyGenerator.convertKey(null, priKeyBlob, (err, privateKey) => {
if (err) {
console.error('Convert private key failed');
return;
}
// 使用私钥解密
let cipher = cryptoFramework.createCipher("RSA1024|PKCS1");
cipher.init(cryptoFramework.CryptoMode.DECRYPT_MODE, privateKey, null, (err, data) => {
if (err) {
console.error('Init cipher failed');
return;
}
let encryptedData = '...'; // 加密后的数据
cipher.doFinal({ data: stringToUint8Array(encryptedData) }, (err, data) => {
if (err) {
console.error('Decrypt failed');
return;
}
console.info('Decrypted data: ' + uint8ArrayToString(data.data));
});
});
});
// 字符串转Uint8Array
function stringToUint8Array(str) {
let arr = [];
for (let i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
}
return new Uint8Array(arr);
}
// Uint8Array转字符串
function uint8ArrayToString(array) {
return String.fromCharCode.apply(null, array);
}
更多关于HarmonyOS鸿蒙Next加解密-RSA-使用已有公私钥的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS鸿蒙Next中,使用已有的RSA公私钥进行加解密可以通过HiCrypto框架实现。首先,导入java.security相关类,然后加载已有的公私钥(如从文件或字符串中读取)。使用KeyFactory将密钥转换为PrivateKey或PublicKey对象。接着,创建Cipher实例,设置模式为Cipher.ENCRYPT_MODE或Cipher.DECRYPT_MODE,并调用doFinal方法进行加解密操作。确保密钥格式和长度正确,遵循RSA标准。

