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

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

入门大师小波哥
发布于 2024-8-16 14:17
浏览
0收藏

使用RSA非对称密钥(PKCS1模式)加密
⚫ 调用cryptoFramework.createAsyKeyGenerator、
AsyKeyGenerator.generateKeyPair,生成RSA密钥类型为RSA1024、素数个数为2
的非对称密钥对(KeyPair)。KeyPair对象中包括公钥PubKey、私钥PriKey。
⚫ 调用cryptoFramework.createCipher,指定字符串参数’RSA1024|PKCS1’,创建非
对称密钥类型为RSA1024、填充模式为PKCS1的Cipher实例,用于完成加解密操作。
⚫ 调用Cipher.init,设置模式为加密(CryptoMode.ENCRYPT_MODE),指定加密密
钥(KeyPair.PubKey),初始化加密Cipher实例。非对称密钥无加密参数,直接传入
null。

调用Cipher.doFinal,传入明文,获取加密后的数据。
⚫ doFinal输出结果可能为null,在访问具体数据前,需要先判断结果是否为
null,避免产生异常。
⚫ 当数据量较大时,可以多次调用doFinal,即分段加解密。

由于RSA算法的Cipher实例不支持重复init操作,需要调用
cryptoFramework.createCipher,重新生成Cipher实例。
⚫ 调用Cipher.init,设置模式为解密(CryptoMode.DECRYPT_MODE),指定
解密密钥(KeyPair.PriKey)初始化解密Cipher实例。PKCS1模式无加密参
数,直接传入null。
⚫ 调用Cipher.doFinal,传入密文,获取解密后的数据。

import cryptoFramework from '@ohos.security.cryptoFramework';
import buffer from '@ohos.buffer';
// 加密消息
async function encryptMessagePromise(publicKey:
cryptoFramework.PubKey, plainText: cryptoFramework.DataBlob) {
let cipher = cryptoFramework.createCipher('RSA1024|PKCS1');
await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE,
publicKey, null);
let encryptData = await cipher.doFinal(plainText);
return encryptData;
}

// 解密消息
async function decryptMessagePromise(privateKey:
cryptoFramework.PriKey, cipherText:
cryptoFramework.DataBlob) {
let decoder =
cryptoFramework.createCipher('RSA1024|PKCS1');
await
decoder.init(cryptoFramework.CryptoMode.DECRYPT_MODE,
privateKey, null);
let decryptData = await decoder.doFinal(cipherText);
return decryptData;
}

// 生成RSA密钥对
async function genKeyPairByData(pubKeyData: Uint8Array, priKeyData:
Uint8Array) {
let pubKeyBlob: cryptoFramework.DataBlob = { data: pubKeyData };
let priKeyBlob: cryptoFramework.DataBlob = { data: priKeyData };
let rsaGenerator =
cryptoFramework.createAsyKeyGenerator('RSA1024');
let keyPair = await rsaGenerator.convertKey(pubKeyBlob, priKeyBlob);
console.info('convertKey success');
return keyPair;
}

async function main() {
let pkData = new Uint8Array([…]);
let skData = new Uint8Array([…]);
let keyPair = await genKeyPairByData(pkData, skData);
let pubKey = keyPair.pubKey;
let priKey = keyPair.priKey;
let message = 'This is a test';
// 把字符串按utf-8解码为Uint8Array
let plainText: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from(message, 'utf-8').buffer) };
let encryptText = await encryptMessagePromise(pubKey, plainText);
let decryptText = await decryptMessagePromise(priKey, encryptText);
if (plainText.data.toString() === decryptText.data.toString()) {
console.info('decrypt ok');
// 把Uint8Array按utf-8编码为字符串
let messageDecrypted = buffer.from(decryptText.data).toString('utf-8');
console.info('decrypted result string:' + messageDecrypted);
} else {
console.error('decrypt failed');
}
}

使用RSA非对称密钥分段加密
⚫ 调用cryptoFramework.createAsyKeyGenerator、AsyKeyGenerator.generateKeyPair,生成RSA密钥类型为
RSA1024、素数个数为2(不填默认)的非对称密钥对(KeyPair)。KeyPair对象中包括公钥PubKey、私钥PriKey。
如何生成RSA非对称密钥对,开发者可参考下文示例,并结合非对称密钥生成和转换规格:RSA和随机生成非对称密
钥对理解,参考文档与当前示例可能存在入参差异,请在阅读时注意区分。
⚫ 调用cryptoFramework.createCipher,指定字符串参数’RSA1024|PKCS1’,创建非对称密钥类型为RSA1024、填充
模式为PKCS1的Cipher实例,用于完成加解密操作。
⚫ 调用Cipher.init,设置模式为加密(CryptoMode.ENCRYPT_MODE),指定加密密钥(KeyPair.PubKey),初始化
加密Cipher实例。
⚫ 多次调用Cipher.doFinal,传入明文,获取加密后的数据。doFinal输出结果可能为null,在访问具体数据前,需要先
判断结果是否为null,避免产生异常。此处将明文按64个字节一组拆分,多次加密。使用1024位密钥,每次将生成
128字节密文。

由于RSA算法的Cipher实例不支持重复init操作,需要调用
cryptoFramework.createCipher,重新生成Cipher实例。
⚫ 调用Cipher.init,设置模式为解密(CryptoMode.DECRYPT_MODE),指定
解密密钥(KeyPair.PriKey)初始化解密Cipher实例。PKCS1模式无加密参
数,直接传入null。
⚫ 多次调用Cipher.doFinal,传入密文,获取解密后的数据。

import cryptoFramework from '@ohos.security.cryptoFramework';
import buffer from '@ohos.buffer';
// 分段加密消息
async function rsaEncryptBySegment(pubKey: cryptoFramework.PubKey, plainText: cryptoFramework.DataBlob) {
let cipher = cryptoFramework.createCipher('RSA1024|PKCS1');
await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null);
let plainTextSplitLen = 64;
let cipherText = new Uint8Array();
for (let i = 0; i < plainText.data.length; i += plainTextSplitLen ) {
let updateMessage = plainText.data.subarray(i, i + plainTextSplitLen );
let updateMessageBlob: cryptoFramework.DataBlob = { data: updateMessage };
// 将原文按64字符进行拆分,循环调用doFinal进行加密,使用1024bit密钥时,每次加密生成128字节长度的密文
let updateOutput = await cipher.doFinal(updateMessageBlob);
let mergeText = new Uint8Array(cipherText.length + updateOutput.data.length);
mergeText.set(cipherText);
mergeText.set(updateOutput.data, cipherText.length);
cipherText = mergeText;
}
let cipherBlob: cryptoFramework.DataBlob = { data: cipherText };
return cipherBlob;
}
// 分段解密消息
async function rsaDecryptBySegment(priKey: cryptoFramework.PriKey, cipherText: cryptoFramework.DataBlob) {
let decoder = cryptoFramework.createCipher('RSA1024|PKCS1');
await decoder.init(cryptoFramework.CryptoMode.DECRYPT_MODE, priKey, null);
let cipherTextSplitLen = 128; // RSA密钥每次加密生成的密文字节长度计算方式:密钥位数/8
let decryptText = new Uint8Array();
for (let i = 0; i < cipherText.data.length; i += cipherTextSplitLen) {
let updateMessage = cipherText.data.subarray(i, i + cipherTextSplitLen);
let updateMessageBlob: cryptoFramework.DataBlob = { data: updateMessage };
// 将密文按128字节进行拆分解密,得到原文后进行拼接
let updateOutput = await decoder.doFinal(updateMessageBlob);
let mergeText = new Uint8Array(decryptText.length + updateOutput.data.length);
mergeText.set(decryptText);
mergeText.set(updateOutput.data, decryptText.length);
decryptText = mergeText;
}
let decryptBlob: cryptoFramework.DataBlob = { data: decryptText };
return decryptBlob;
}


async function rsaEncryptLongMessage() {
let message = "This is a long plainTest! This is a long plainTest! This is a long plainTest!" +
"This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!" +
"This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!" +
"This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!" +
"This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!" +
"This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!" +
"This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!" +
"This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!";
let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024"); // 创建非对称密钥生成器对象
let keyPair = await asyKeyGenerator.generateKeyPair(); // 随机生成RSA密钥
let plainText: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from(message, 'utf-8').buffer) };
let encryptText = await rsaEncryptBySegment(keyPair.pubKey, plainText);
let decryptText = await rsaDecryptBySegment(keyPair.priKey, 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');
}
}


使用RSA非对称密钥(PKCS1_OAEP模式)加密
⚫ 调用cryptoFramework.createAsyKeyGeneratorBySpec、AsyKeyGeneratorBySpec.generateKeyPair,指定密钥
参数,生成RSA非对称密钥对(KeyPair)
⚫ 调用cryptoFramework.createCipher,指定字符串参数’RSA2048|PKCS1_OAEP|SHA256|MGF1_SHA1’,创建非对
称密钥类型为RSA2048、填充模式为PKCS1_OAEP、摘要算法为SHA256、掩码摘要为MGF1_SHA1的RSA密钥的
Cipher实例,用于完成加解密操作。
⚫ 调用Cipher.init,设置模式为加密(CryptoMode.ENCRYPT_MODE),指定加密密钥(KeyPair.PubKey),初始化
加密Cipher实例。非对称密钥无加密参数,直接传入null。
⚫ 在调用Cipher.doFinal前,调用Cipher.setCipherSpec设置PKCS1_OAEP填充参数pSource。调用
Cipher.getCipherSpec可获得OAEP相关参数。
⚫ 调用Cipher.doFinal,传入明文,获取加密后的数据。

由于RSA算法的Cipher实例不支持重复init操作,需要调用cryptoFramework.createCipher,
重新生成Cipher实例。
⚫ 调用Cipher.init,设置模式为解密(CryptoMode.DECRYPT_MODE),指定解密密钥
(KeyPair.PriKey)初始化解密Cipher实例。PKCS1模式无加密参数,直接传入null。
⚫ 在调用Cipher.doFinal前,调用Cipher.setCipherSpec设置PKCS1_OAEP填充参数pSource,
此处需要和加密时设置的保持一致。调用Cipher.getCipherSpec可获得OAEP相关参数。
⚫ 调用Cipher.doFinal,传入密文,获取解密后的数据。

import cryptoFramework from '@ohos.security.cryptoFramework';
import buffer from '@ohos.buffer';
// 根据密钥参数属性构造RSA非对称密钥对密钥参数
function genRsaKeyPairSpec(nIn: bigint, eIn: bigint, dIn: bigint) {
let rsaCommSpec: cryptoFramework.RSACommonParamsSpec = {
n: nIn,
algName: "RSA",
specType: cryptoFramework.AsyKeySpecType.COMMON_PARAMS_SPEC
};
let rsaKeyPairSpec: cryptoFramework.RSAKeyPairSpec = {
params: rsaCommSpec,
sk: dIn,
pk: eIn,
algName: "RSA",
specType: cryptoFramework.AsyKeySpecType.KEY_PAIR_SPEC
};
return rsaKeyPairSpec;
}

// 生成RSA2048密钥对参数
function genRsa2048KeyPairSpec(): cryptoFramework.RSAKeyPairSpec {
let nIn =
BigInt("0x9260d0750ae117eee55c3f3deaba74917521a262ee76007cdf8a56755ad73a1598a14084
10a01434c3f5bc54a88b57fa19fc4328daea0750a4c44e88cff3b2382621b80f670464433e4336e6d00
3e8cd65bff211da144b88291c2259a00a72b711c116ef7686e8fee34e4d933c868187bdc26f7be0714
93c86f7a5941c3510806ad67b0f94d88f5cf5c02a092821d8626e8932b65c5bd8c92049c210932b7af
a7ac59c0e886ae5c1edb00d8ce2c57633db26bd6639bff73cee82be9275c402b4cf2a4388da8cf8c64
eefe1c5a0f5ab8057c39fa5c0589c3e253f0960332300f94bea44877b588e1edbde97cf2360727a09b7
75262d7ee552b3319b9266f05a25");
let eIn = BigInt("0x010001");
let dIn =
BigInt("0x6a7df2ca63ead4dda191d614b6b385e0d9056a3d6d5cfe07db1daabee022db08212d9761
3d3328e0267c9dd23d787abde2afcb306aeb7dfce69246cc73f5c87fdf06030179a2114b767db1f083ff
841c025d7dc00cd82435b9a90f695369e94df23d2ce458bc3b3283ad8bba2b8fa1ba62e2dce9accff3
799aae7c840016f3ba8e0048c0b6cc4339af7161003a5beb864a0164b2c1c9237b64bc87556994351
b27506c33d4bcdfce0f9c491a7d6b0628c7c852be4f0a9c3132b2ed3a2c8881e9aab07e20e17deb07
4691be677776a78b5c502e05d9bdde72126b3738695e2dd1a0a98a14247c65d8a7ee79432a092cb
0721a12df798e44f7cfce0c498147a9b1");
return genRsaKeyPairSpec(nIn, eIn, dIn);
}

async function rsaUseSpecDecryptOAEPPromise() {
let plan = "This is a test";
// 获得RSA密钥对密钥参数对象
let rsaKeyPairSpec = genRsa2048KeyPairSpec();
// 根据RSA密钥对参数生成RSA密钥对
let rsaGeneratorSpec = cryptoFramework.createAsyKeyGeneratorBySpec(rsaKeyPairSpec);
let cipher = cryptoFramework.createCipher("RSA2048|PKCS1_OAEP|SHA256|MGF1_SHA1");
let decoder = cryptoFramework.createCipher("RSA2048|PKCS1_OAEP|SHA256|MGF1_SHA1");
// RSA加解密PKCS1-OAEP模式填充字节流P
let pSource = new Uint8Array([1, 2, 3, 4]);
let input: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from(plan, 'utf-8').buffer) };
// 生成密钥对
let keyPair = await rsaGeneratorSpec.generateKeyPair();
// 进行加密操作初始化
await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, keyPair.pubKey, null);
// get和set操作可以放在Cipher对象init之后,此处对cipher进行set和get操作
cipher.setCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF1_PSRC_UINT8ARR, pSource);
let retP = cipher.getCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF1_PSRC_UINT8ARR);
// 比较get出来的P字节流与set进去的P字节流是否一致
if (retP.toString() != pSource.toString()) {
console.error("error init pSource" + retP);
} else {
console.info("pSource changed ==" + retP);
}

// 进行OAEP其他参数的get操作
let md = cipher.getCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MD_NAME_STR);
console.info("md == " + md);
let mgf = cipher.getCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF_NAME_STR);
console.info("mgf == " + mgf);
let mgf1Md = cipher.getCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF1_MD_STR);
console.info("mgf1Md == " + mgf1Md);
let cipherDataBlob = await cipher.doFinal(input);
// get和set操作可以放在Cipher对象init之前,且与init之后等价,此处对decoder进行set和get操作
decoder.setCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF1_PSRC_UINT8ARR, pSource);
retP = decoder.getCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF1_PSRC_UINT8ARR);
// 比较get出来的P字节流与set进去的P字节流是否一致
if (retP.toString() != pSource.toString()) {
console.error("error init pSource" + retP);
} else {
console.info("pSource changed ==" + retP);
}
// 进行OAEP其他参数的get操作
md = decoder.getCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MD_NAME_STR);
console.info("md == " + md);
mgf = decoder.getCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF_NAME_STR);
console.info("mgf == " + mgf);
mgf1Md = decoder.getCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF1_MD_STR);
console.info("mgf1Md == " + mgf1Md);
// 初始化解密操作
await decoder.init(cryptoFramework.CryptoMode.DECRYPT_MODE, keyPair.priKey, null);
let decodeData = await decoder.doFinal(cipherDataBlob);
// 解密成功
if (decodeData.data.toString() === input.data.toString()) {
console.info("oaep decrypt success");
} else {
console.error("oaep decrypt fail");
}
}


©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
分类
标签
已于2024-8-16 14:45:29修改
收藏
回复
举报
回复
    相关推荐