当前位置:   article > 正文

鸿蒙OS开发问题:(ArkTS)【 RSA加解密,解决中文乱码等现象】_鸿蒙应用开发rsa解密

鸿蒙应用开发rsa解密

RSA加解密开始构建工具类就是举步维艰,官方文档虽然很全,但是还是有很多小瑕疵,在自己经过几天的时间,彻底解决了中文乱码的问题、分段加密的问题。

首先看官方示例代码(以RSA非对称加解密(多次调用doFinal实现分段)为例:):

  1. import cryptoFramework from "@ohos.security.cryptoFramework"
  2. function stringToUint8Array(str) {
  3. var arr = [];
  4. for (var i = 0, j = str.length; i < j; ++i) {
  5. arr.push(str.charCodeAt(i));
  6. }
  7. var tmpArray = new Uint8Array(arr);
  8. return tmpArray;
  9. }
  10. // 字节流转成可理解的字符串
  11. function uint8ArrayToString(array) {
  12. let arrayString = '';
  13. for (let i = 0; i < array.length; i++) {
  14. arrayString += String.fromCharCode(array[i]);
  15. }
  16. return arrayString;
  17. }
  18. function encryptLongMessagePromise() {
  19. let globalPlainText = "This is a long plainTest! This is a long plainTest! This is a long plainTest!" +
  20. "This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!" +
  21. "This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!" +
  22. "This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!" +
  23. "This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!" +
  24. "This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!" +
  25. "This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!" +
  26. "This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!";
  27. let globalCipherOutput;
  28. let globalDecodeOutput;
  29. var globalKeyPair;
  30. let plainTextSplitLen = 64; // RSA每次加解密允许的原文长度大小与密钥位数和填充模式等有关,详细规格内容见overview文档
  31. let cipherTextSplitLen = 128; // RSA密钥每次加密生成的密文数据长度计算方式:密钥位数/8
  32. let keyGenName = "RSA1024";
  33. let cipherAlgName = "RSA1024|PKCS1";
  34. let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator(keyGenName); // 创建非对称密钥生成器对象
  35. let cipher = cryptoFramework.createCipher(cipherAlgName); // 创建加密Cipher对象
  36. let decoder = cryptoFramework.createCipher(cipherAlgName); // 创建解密Decoder对象
  37. return new Promise((resolve, reject) => {
  38. setTimeout(() => {
  39. resolve("testRsaMultiDoFinal");
  40. }, 10);
  41. }).then(() => {
  42. return asyKeyGenerator.generateKeyPair(); // 生成rsa密钥
  43. }).then(keyPair => {
  44. globalKeyPair = keyPair; // 保存到密钥对全局变量
  45. return cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, globalKeyPair.pubKey, null);
  46. }).then(async () => {
  47. globalCipherOutput = [];
  48. // 将原文按64字符进行拆分,循环调用doFinal进行加密,使用1024bit密钥时,每次加密生成128B长度的密文
  49. for (let i = 0; i < (globalPlainText.length / plainTextSplitLen); i++) {
  50. let tempStr = globalPlainText.substr(i * plainTextSplitLen, plainTextSplitLen);
  51. let tempBlob = { data : stringToUint8Array(tempStr) };
  52. let tempCipherOutput = await cipher.doFinal(tempBlob);
  53. globalCipherOutput = globalCipherOutput.concat(Array.from(tempCipherOutput.data));
  54. }
  55. console.info(`globalCipherOutput len is ${globalCipherOutput.length}, data is: ${globalCipherOutput.toString()}`);
  56. return;
  57. }).then(() =>{
  58. return decoder.init(cryptoFramework.CryptoMode.DECRYPT_MODE, globalKeyPair.priKey, null);
  59. }).then(async() => {
  60. globalDecodeOutput = [];
  61. // 将密文按128B进行拆分解密,得到原文后进行拼接
  62. for (let i = 0; i < (globalCipherOutput.length / cipherTextSplitLen); i++) {
  63. let tempBlobData = globalCipherOutput.slice(i * cipherTextSplitLen, (i + 1) * cipherTextSplitLen);
  64. let message = new Uint8Array(tempBlobData);
  65. let tempBlob = { data : message };
  66. let tempDecodeOutput = await decoder.doFinal(tempBlob);
  67. globalDecodeOutput += uint8ArrayToString(tempDecodeOutput.data);
  68. }
  69. if (globalDecodeOutput === globalPlainText) {
  70. console.info(`encode and decode success`);
  71. } else {
  72. console.info(`encode and decode error`);
  73. }
  74. return;
  75. }).catch(error => {
  76. console.error(`catch error, ${error.code}, ${error.message}`);
  77. })
  78. }
let plainTextSplitLen = 64; // RSA每次加解密允许的原文长度大小与密钥位数和填充模式等有关,详细规格内容见overview文档

注意点:在解密中,这句代码就是产生中文乱码的关键。

鸿蒙OS开发更多内容↓点击HarmonyOS与OpenHarmony技术
鸿蒙技术文档开发知识更新库gitee.com/li-shizhen-skin/harmony-os/blob/master/README.md在这。或+mau123789学习,是v喔

搜狗高速浏览器截图20240326151450.png

 
globalDecodeOutput += uint8ArrayToString(tempDecodeOutput.data);

好,加上我的代码

加密:

  1. /**
  2. * 测试RSA加密
  3. */
  4. export function textRsaEncryption(value: string) {
  5. let keyGenName = "RSA1024";
  6. let cipherAlgName = "RSA1024|PKCS1";
  7. //64 RSA每次加解密允许的原文长度大小与密钥位数和填充模式等有关,详细规格内容见overview文档
  8. let plainTextSplitLen = 117;
  9. let globalKeyPair; //密钥对
  10. let globalEncryptionOutput; //加密输出
  11. let arrTest = StringUtils.string2Uint8Array1(value);
  12. //创建非对称密钥生成器对象
  13. let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator(keyGenName);
  14. // 创建加密Cipher对象
  15. let cipherEncryption = cryptoFramework.createCipher(cipherAlgName);
  16. return new Promise((resolve, reject) => {
  17. setTimeout(() => {
  18. resolve("textRsaEncryption");
  19. }, 10);
  20. })
  21. .then(() => {
  22. let base64 = Base64.getInstance()
  23. let pubKeyBlob = { data: new Uint8Array(base64.decode(publicKey)) }
  24. let priKeyBlob = { data: new Uint8Array(base64.decode(privateKey)) }
  25. return asyKeyGenerator.convertKey(pubKeyBlob, priKeyBlob);
  26. })
  27. .then(keyPair => {
  28. globalKeyPair = keyPair; // 保存到密钥对全局变量
  29. return cipherEncryption.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, globalKeyPair.pubKey, null);
  30. }).then(async () => {
  31. globalEncryptionOutput = [];
  32. // 将原文按64字符进行拆分,循环调用doFinal进行加密,使用1024bit密钥时,每次加密生成128B长度的密文
  33. for (let i = 0; i < (arrTest.length / plainTextSplitLen); i++) {
  34. let tempArr = arrTest.slice(i * plainTextSplitLen, (i + 1) * plainTextSplitLen);
  35. let tempBlob = { data: tempArr };
  36. let tempCipherOutput = await cipherEncryption.doFinal(tempBlob);
  37. globalEncryptionOutput = globalEncryptionOutput.concat(Array.from(tempCipherOutput.data));
  38. }
  39. let base64 = Base64.getInstance()
  40. let enStr = base64.encode(globalEncryptionOutput)
  41. LogUtils.i("加密总长度:" + globalEncryptionOutput.length + "\n生成加密串:\n" + enStr)
  42. return enStr
  43. })
  44. .catch(error => {
  45. LogUtils.i(`加密异常, ${error.code}, ${error.message}`);
  46. })
  47. }

解密:

  1. /**
  2. * 测试RSA解密
  3. */
  4. export function textRsaDecryption(value: string) {
  5. let keyGenName = "RSA1024";
  6. let cipherAlgName = "RSA1024|PKCS1";
  7. // RSA密钥每次加密生成的密文数据长度计算方式:密钥位数/8
  8. let cipherTextSplitLen = 128;
  9. let globalKeyPair; //密钥对
  10. //创建非对称密钥生成器对象
  11. let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator(keyGenName);
  12. // 创建解密Decoder对象
  13. let cipherDecryption = cryptoFramework.createCipher(cipherAlgName);
  14. return new Promise((resolve, reject) => {
  15. setTimeout(() => {
  16. resolve("textRsaEncryption");
  17. }, 10);
  18. })
  19. .then(() => {
  20. let base64 = Base64.getInstance()
  21. let pubKeyBlob = { data: new Uint8Array(base64.decode(publicKey)) }
  22. let priKeyBlob = { data: new Uint8Array(base64.decode(privateKey)) }
  23. return asyKeyGenerator.convertKey(pubKeyBlob, priKeyBlob);
  24. })
  25. .then(keyPair => {
  26. globalKeyPair = keyPair; // 保存到密钥对全局变量
  27. return cipherDecryption.init(cryptoFramework.CryptoMode.DECRYPT_MODE, globalKeyPair.priKey, null);
  28. }).then(async () => {
  29. let base64 = Base64.getInstance()
  30. let globalCipherOutput1 = new Uint8Array(base64.decode(value))
  31. let len = globalCipherOutput1.length
  32. //解密输出
  33. let globalDecryptionOutput = new Uint8Array(len);
  34. let globalOffset = 0
  35. // 将密文按128B进行拆分解密,得到原文后进行拼接
  36. for (let i = 0; i < (len / cipherTextSplitLen); i++) {
  37. let tempBlobData = globalCipherOutput1.subarray(i * cipherTextSplitLen, (i + 1) * cipherTextSplitLen);
  38. let message = new Uint8Array(tempBlobData);
  39. let tempBlob = { data: message };
  40. let tempDecodeOutput = await cipherDecryption.doFinal(tempBlob);
  41. //存入数组 解决边累加边转中文时 字节错乱出现乱码
  42. globalDecryptionOutput.set(tempDecodeOutput.data, globalOffset)
  43. //偏移量
  44. globalOffset += tempDecodeOutput.data.byteLength
  45. }
  46. let result = StringUtils.uint8Array2String(globalDecryptionOutput)
  47. LogUtils.i("解密串:cipherAlgName[" + cipherAlgName + "]\n" + result);
  48. })
  49. .catch(error => {
  50. LogUtils.i(`解密异常,cipherAlgName[${cipherAlgName}] ${error.code}, ${error.message}`);
  51. })
  52. }

运行代码:

  1. Text("RSA加解密联测")
  2. .TextNormalStyle()
  3. .fontSize(16)
  4. .fontWeight(FontWeight.Normal)
  5. .fontColor(Color.White)
  6. .textAlign(TextAlign.Center)
  7. .margin({ left: 5 })
  8. .layoutWeight(1)
  9. .onClick(() => {
  10. let globalPlainText = ""
  11. globalPlainText += "123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/"
  12. globalPlainText += "123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/"
  13. globalPlainText += "123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/"
  14. globalPlainText += "123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/"
  15. globalPlainText += "123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/"
  16. globalPlainText += "123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/"
  17. globalPlainText += "123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/"
  18. globalPlainText += "123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/"
  19. globalPlainText += "123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/"
  20. globalPlainText += "123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/"
  21. globalPlainText += "123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/"
  22. globalPlainText += "123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/"
  23. globalPlainText += "123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/"
  24. globalPlainText += "123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/"
  25. globalPlainText += "123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/"
  26. globalPlainText += "123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/"
  27. globalPlainText += "123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/"
  28. globalPlainText += "123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/"
  29. globalPlainText += "一二三四五六七八九十"
  30. globalPlainText += "123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/123456789/"
  31. globalPlainText += "SDK向DevEco Studio提供全量API,DevEco Studio识别开发者项目中选择的设备形态,找到该设备的支持能力集,筛选支持能力集包含的API并提供API联想"
  32. //
  33. textRsaEncryption(globalPlainText)
  34. .then(enStr => {
  35. if (enStr) textRsaDecryption(enStr)
  36. })
  37. })
  38. }
  39. .width('100%')
  40. .height(50)
  41. .margin({ top: 10 })
  42. .padding(5)

运行结果:

cke_155247.png

终于大功告成!!

最后呢,很多开发朋友不知道需要学习那些鸿蒙技术?鸿蒙开发岗位需要掌握那些核心技术点?为此鸿蒙的开发学习必须要系统性的进行。

而网上有关鸿蒙的开发资料非常的少,假如你想学好鸿蒙的应用开发与系统底层开发。你可以参考这份资料,少走很多弯路,节省没必要的麻烦。由两位前阿里高级研发工程师联合打造《鸿蒙NEXT星河版OpenHarmony开发文档》里面内容包含了(ArkTS、ArkUI开发组件、Stage模型、多端部署、分布式应用开发、音频、视频、WebGL、OpenHarmony多媒体技术、Napi组件、OpenHarmony内核、Harmony南向开发、鸿蒙项目实战等等)鸿蒙(Harmony NEXT)技术知识点

如果你是一名Android、Java、前端等等开发人员,想要转入鸿蒙方向发展。可以直接领取这份资料辅助你的学习。下面是鸿蒙开发的学习路线图。

高清完整版请点击《鸿蒙NEXT星河版开发学习文档》

针对鸿蒙成长路线打造的鸿蒙学习文档。话不多说,我们直接看详细资料鸿蒙(OpenHarmony )学习手册(共计1236页)与鸿蒙(OpenHarmony )开发入门教学视频,帮助大家在技术的道路上更进一步。

《鸿蒙 (OpenHarmony)开发学习视频》

图片

《鸿蒙生态应用开发V2.0白皮书》

图片

《鸿蒙 (OpenHarmony)开发基础到实战手册》

获取这份鸿蒙星河版学习资料,请点击→《鸿蒙NEXT星河版开发学习文档》

OpenHarmony北向、南向开发环境搭建

图片

《鸿蒙开发基础》

  1. ArkTS语言

  2. 安装DevEco Studio

  3. 运用你的第一个ArkTS应用

  4. ArkUI声明式UI开发

  5. .……

图片

《鸿蒙开发进阶》

  1. Stage模型入门

  2. 网络管理

  3. 数据管理

  4. 电话服务

  5. 分布式应用开发

  6. 通知与窗口管理

  7. 多媒体技术

  8. 安全技能

  9. 任务管理

  10. WebGL

  11. 国际化开发

  12. 应用测试

  13. DFX面向未来设计

  14. 鸿蒙系统移植和裁剪定制

  15. ……

图片

《鸿蒙开发实战》

  1. ArkTS实践

  2. UIAbility应用

  3. 网络案例

  4. ……

图片

 获取这份鸿蒙星河版学习资料,请点击→《鸿蒙NEXT星河版开发学习文档》

总结

鸿蒙—作为国家主力推送的国产操作系统。部分的高校已经取消了安卓课程,从而开设鸿蒙课程;企业纷纷跟进启动了鸿蒙研发

并且鸿蒙是完全具备无与伦比的机遇和潜力的;预计到年底将有 5,000 款的应用完成原生鸿蒙开发,未来将会支持 50 万款的应用那么这么多的应用需要开发,也就意味着需要有更多的鸿蒙人才鸿蒙开发工程师也将会迎来爆发式的增长,学习鸿蒙势在必行!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/603147
推荐阅读
相关标签
  

闽ICP备14008679号