RSA加解密開始構(gòu)建工具類就是舉步維艱,官方文檔雖然很全,但是還是有很多小瑕疵,在自己經(jīng)過幾天的時(shí)間,徹底解決了中文亂碼的問題、分段加密的問題。
首先看官方示例代碼(以RSA非對(duì)稱加解密(多次調(diào)用doFinal實(shí)現(xiàn)分段)為例:):
import cryptoFramework from "@ohos.security.cryptoFramework"
function stringToUint8Array(str) {
var arr = [];
for (var i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
}
var tmpArray = new Uint8Array(arr);
return tmpArray;
}
// 字節(jié)流轉(zhuǎn)成可理解的字符串
function uint8ArrayToString(array) {
let arrayString = '';
for (let i = 0; i < array.length; i++) {
arrayString += String.fromCharCode(array[i]);
}
return arrayString;
}
function encryptLongMessagePromise() {
let globalPlainText = "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 globalCipherOutput;
let globalDecodeOutput;
var globalKeyPair;
let plainTextSplitLen = 64; // RSA每次加解密允許的原文長(zhǎng)度大小與密鑰位數(shù)和填充模式等有關(guān),詳細(xì)規(guī)格內(nèi)容見overview文檔
let cipherTextSplitLen = 128; // RSA密鑰每次加密生成的密文數(shù)據(jù)長(zhǎng)度計(jì)算方式:密鑰位數(shù)/8
let keyGenName = "RSA1024";
let cipherAlgName = "RSA1024|PKCS1";
let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator(keyGenName); // 創(chuàng)建非對(duì)稱密鑰生成器對(duì)象
let cipher = cryptoFramework.createCipher(cipherAlgName); // 創(chuàng)建加密Cipher對(duì)象
let decoder = cryptoFramework.createCipher(cipherAlgName); // 創(chuàng)建解密Decoder對(duì)象
return new Promise((resolve, reject) = > {
setTimeout(() = > {
resolve("testRsaMultiDoFinal");
}, 10);
}).then(() = > {
return asyKeyGenerator.generateKeyPair(); // 生成rsa密鑰
}).then(keyPair = > {
globalKeyPair = keyPair; // 保存到密鑰對(duì)全局變量
return cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, globalKeyPair.pubKey, null);
}).then(async () = > {
globalCipherOutput = [];
// 將原文按64字符進(jìn)行拆分,循環(huán)調(diào)用doFinal進(jìn)行加密,使用1024bit密鑰時(shí),每次加密生成128B長(zhǎng)度的密文
for (let i = 0; i < (globalPlainText.length / plainTextSplitLen); i++) {
let tempStr = globalPlainText.substr(i * plainTextSplitLen, plainTextSplitLen);
let tempBlob = { data : stringToUint8Array(tempStr) };
let tempCipherOutput = await cipher.doFinal(tempBlob);
globalCipherOutput = globalCipherOutput.concat(Array.from(tempCipherOutput.data));
}
console.info(`globalCipherOutput len is ${globalCipherOutput.length}, data is: ${globalCipherOutput.toString()}`);
return;
}).then(() = >{
return decoder.init(cryptoFramework.CryptoMode.DECRYPT_MODE, globalKeyPair.priKey, null);
}).then(async() = > {
globalDecodeOutput = [];
// 將密文按128B進(jìn)行拆分解密,得到原文后進(jìn)行拼接
for (let i = 0; i < (globalCipherOutput.length / cipherTextSplitLen); i++) {
let tempBlobData = globalCipherOutput.slice(i * cipherTextSplitLen, (i + 1) * cipherTextSplitLen);
let message = new Uint8Array(tempBlobData);
let tempBlob = { data : message };
let tempDecodeOutput = await decoder.doFinal(tempBlob);
globalDecodeOutput += uint8ArrayToString(tempDecodeOutput.data);
}
if (globalDecodeOutput === globalPlainText) {
console.info(`encode and decode success`);
} else {
console.info(`encode and decode error`);
}
return;
}).catch(error = > {
console.error(`catch error, ${error.code}, ${error.message}`);
})
}
let plainTextSplitLen = 64; // RSA每次加解密允許的原文長(zhǎng)度大小與密鑰位數(shù)和填充模式等有關(guān),詳細(xì)規(guī)格內(nèi)容見overview文檔
注意點(diǎn):在解密中,這句代碼就是產(chǎn)生中文亂碼的關(guān)鍵。
鴻蒙OS開發(fā) | 更多內(nèi)容↓點(diǎn)擊 | HarmonyOS與OpenHarmony技術(shù) |
---|---|---|
鴻蒙技術(shù)文檔 | 開發(fā)知識(shí)更新庫gitee.com/li-shizhen-skin/harmony-os/blob/master/README.md 在這。 | 或+mau123789學(xué)習(xí),是v喔 |
globalDecodeOutput += uint8ArrayToString(tempDecodeOutput.data);
好,加上我的代碼
加密:
/**
* 測(cè)試RSA加密
*/
export function textRsaEncryption(value: string) {
let keyGenName = "RSA1024";
let cipherAlgName = "RSA1024|PKCS1";
//64 RSA每次加解密允許的原文長(zhǎng)度大小與密鑰位數(shù)和填充模式等有關(guān),詳細(xì)規(guī)格內(nèi)容見overview文檔
let plainTextSplitLen = 117;
let globalKeyPair; //密鑰對(duì)
let globalEncryptionOutput; //加密輸出
let arrTest = StringUtils.string2Uint8Array1(value);
//創(chuàng)建非對(duì)稱密鑰生成器對(duì)象
let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator(keyGenName);
// 創(chuàng)建加密Cipher對(duì)象
let cipherEncryption = cryptoFramework.createCipher(cipherAlgName);
return new Promise((resolve, reject) = > {
setTimeout(() = > {
resolve("textRsaEncryption");
}, 10);
})
.then(() = > {
let base64 = Base64.getInstance()
let pubKeyBlob = { data: new Uint8Array(base64.decode(publicKey)) }
let priKeyBlob = { data: new Uint8Array(base64.decode(privateKey)) }
return asyKeyGenerator.convertKey(pubKeyBlob, priKeyBlob);
})
.then(keyPair = > {
globalKeyPair = keyPair; // 保存到密鑰對(duì)全局變量
return cipherEncryption.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, globalKeyPair.pubKey, null);
}).then(async () = > {
globalEncryptionOutput = [];
// 將原文按64字符進(jìn)行拆分,循環(huán)調(diào)用doFinal進(jìn)行加密,使用1024bit密鑰時(shí),每次加密生成128B長(zhǎng)度的密文
for (let i = 0; i < (arrTest.length / plainTextSplitLen); i++) {
let tempArr = arrTest.slice(i * plainTextSplitLen, (i + 1) * plainTextSplitLen);
let tempBlob = { data: tempArr };
let tempCipherOutput = await cipherEncryption.doFinal(tempBlob);
globalEncryptionOutput = globalEncryptionOutput.concat(Array.from(tempCipherOutput.data));
}
let base64 = Base64.getInstance()
let enStr = base64.encode(globalEncryptionOutput)
LogUtils.i("加密總長(zhǎng)度:" + globalEncryptionOutput.length + "n生成加密串:n" + enStr)
return enStr
})
.catch(error = > {
LogUtils.i(`加密異常, ${error.code}, ${error.message}`);
})
}復(fù)制
解密:
/**
* 測(cè)試RSA解密
*/
export function textRsaDecryption(value: string) {
let keyGenName = "RSA1024";
let cipherAlgName = "RSA1024|PKCS1";
// RSA密鑰每次加密生成的密文數(shù)據(jù)長(zhǎng)度計(jì)算方式:密鑰位數(shù)/8
let cipherTextSplitLen = 128;
let globalKeyPair; //密鑰對(duì)
//創(chuàng)建非對(duì)稱密鑰生成器對(duì)象
let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator(keyGenName);
// 創(chuàng)建解密Decoder對(duì)象
let cipherDecryption = cryptoFramework.createCipher(cipherAlgName);
return new Promise((resolve, reject) = > {
setTimeout(() = > {
resolve("textRsaEncryption");
}, 10);
})
.then(() = > {
let base64 = Base64.getInstance()
let pubKeyBlob = { data: new Uint8Array(base64.decode(publicKey)) }
let priKeyBlob = { data: new Uint8Array(base64.decode(privateKey)) }
return asyKeyGenerator.convertKey(pubKeyBlob, priKeyBlob);
})
.then(keyPair = > {
globalKeyPair = keyPair; // 保存到密鑰對(duì)全局變量
return cipherDecryption.init(cryptoFramework.CryptoMode.DECRYPT_MODE, globalKeyPair.priKey, null);
}).then(async () = > {
let base64 = Base64.getInstance()
let globalCipherOutput1 = new Uint8Array(base64.decode(value))
let len = globalCipherOutput1.length
//解密輸出
let globalDecryptionOutput = new Uint8Array(len);
let globalOffset = 0
// 將密文按128B進(jìn)行拆分解密,得到原文后進(jìn)行拼接
for (let i = 0; i < (len / cipherTextSplitLen); i++) {
let tempBlobData = globalCipherOutput1.subarray(i * cipherTextSplitLen, (i + 1) * cipherTextSplitLen);
let message = new Uint8Array(tempBlobData);
let tempBlob = { data: message };
let tempDecodeOutput = await cipherDecryption.doFinal(tempBlob);
//存入數(shù)組 解決邊累加邊轉(zhuǎn)中文時(shí) 字節(jié)錯(cuò)亂出現(xiàn)亂碼
globalDecryptionOutput.set(tempDecodeOutput.data, globalOffset)
//偏移量
globalOffset += tempDecodeOutput.data.byteLength
}
let result = StringUtils.uint8Array2String(globalDecryptionOutput)
LogUtils.i("解密串:cipherAlgName[" + cipherAlgName + "]n" + result);
})
.catch(error = > {
LogUtils.i(`解密異常,cipherAlgName[${cipherAlgName}] ${error.code}, ${error.message}`);
})
}復(fù)制
運(yùn)行代碼:
Text("RSA加解密聯(lián)測(cè)")
.TextNormalStyle()
.fontSize(16)
.fontWeight(FontWeight.Normal)
.fontColor(Color.White)
.textAlign(TextAlign.Center)
.margin({ left: 5 })
.layoutWeight(1)
.onClick(() = > {
let globalPlainText = ""
globalPlainText += "123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/"
globalPlainText += "123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/"
globalPlainText += "123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/"
globalPlainText += "123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/"
globalPlainText += "123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/"
globalPlainText += "123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/"
globalPlainText += "123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/"
globalPlainText += "123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/"
globalPlainText += "123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/"
globalPlainText += "123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/"
globalPlainText += "123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/"
globalPlainText += "123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/"
globalPlainText += "123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/"
globalPlainText += "123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/"
globalPlainText += "123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/"
globalPlainText += "123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/"
globalPlainText += "123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/"
globalPlainText += "123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/"
globalPlainText += "一二三四五六七八九十"
globalPlainText += "123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/"
globalPlainText += "SDK向DevEco Studio提供全量API,DevEco Studio識(shí)別開發(fā)者項(xiàng)目中選擇的設(shè)備形態(tài),找到該設(shè)備的支持能力集,篩選支持能力集包含的API并提供API聯(lián)想"
//
textRsaEncryption(globalPlainText)
.then(enStr = > {
if (enStr) textRsaDecryption(enStr)
})
})
}
.width('100%')
.height(50)
.margin({ top: 10 })
.padding(5)復(fù)制
運(yùn)行結(jié)果:
終于大功告成!!
審核編輯 黃宇
-
API
+關(guān)注
關(guān)注
2文章
1501瀏覽量
62033 -
RSA
+關(guān)注
關(guān)注
0文章
59瀏覽量
18895 -
OpenHarmony
+關(guān)注
關(guān)注
25文章
3722瀏覽量
16323 -
鴻蒙OS
+關(guān)注
關(guān)注
0文章
188瀏覽量
4400
發(fā)布評(píng)論請(qǐng)先 登錄
相關(guān)推薦
評(píng)論