91在线观看视频-91在线观看视频-91在线观看免费视频-91在线观看免费-欧美第二页-欧美第1页

0
  • 聊天消息
  • 系統消息
  • 評論與回復
登錄后你可以
  • 下載海量資料
  • 學習在線課程
  • 觀看技術視頻
  • 寫文章/發帖/加入社區
會員中心
創作中心

完善資料讓更多小伙伴認識你,還能領取20積分哦,立即完善>

3天內不再提示

鴻蒙OS開發問題:(ArkTS)【 RSA加解密,解決中文亂碼等現象】

jf_46214456 ? 來源:jf_46214456 ? 作者:jf_46214456 ? 2024-03-27 21:23 ? 次閱讀
加入交流群
微信小助手二維碼

掃碼添加小助手

加入工程師交流群

RSA加解密開始構建工具類就是舉步維艱,官方文檔雖然很全,但是還是有很多小瑕疵,在自己經過幾天的時間,徹底解決了中文亂碼的問題、分段加密的問題。

首先看官方示例代碼(以RSA非對稱加解密(多次調用doFinal實現分段)為例:):

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;
}

// 字節流轉成可理解的字符串
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每次加解密允許的原文長度大小與密鑰位數和填充模式等有關,詳細規格內容見overview文檔
  let cipherTextSplitLen = 128; // RSA密鑰每次加密生成的密文數據長度計算方式:密鑰位數/8
  let keyGenName = "RSA1024";
  let cipherAlgName = "RSA1024|PKCS1";
  let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator(keyGenName); // 創建非對稱密鑰生成器對象
  let cipher = cryptoFramework.createCipher(cipherAlgName); // 創建加密Cipher對象
  let decoder = cryptoFramework.createCipher(cipherAlgName); // 創建解密Decoder對象
  return new Promise((resolve, reject) = > {
    setTimeout(() = > {
      resolve("testRsaMultiDoFinal");
    }, 10);
  }).then(() = > {
    return asyKeyGenerator.generateKeyPair(); // 生成rsa密鑰
  }).then(keyPair = > {
    globalKeyPair = keyPair; // 保存到密鑰對全局變量
    return cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, globalKeyPair.pubKey, null);
  }).then(async () = > {
    globalCipherOutput = [];
    // 將原文按64字符進行拆分,循環調用doFinal進行加密,使用1024bit密鑰時,每次加密生成128B長度的密文
    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進行拆分解密,得到原文后進行拼接
    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每次加解密允許的原文長度大小與密鑰位數和填充模式等有關,詳細規格內容見overview文檔

注意點:在解密中,這句代碼就是產生中文亂碼的關鍵。

鴻蒙OS開發更多內容↓點擊HarmonyOSOpenHarmony技術
鴻蒙技術文檔開發知識更新庫gitee.com/li-shizhen-skin/harmony-os/blob/master/README.md在這。或+mau123789學習,是v喔

搜狗高速瀏覽器截圖20240326151450.png

globalDecodeOutput += uint8ArrayToString(tempDecodeOutput.data);

好,加上我的代碼

加密:

/**
 * 測試RSA加密
 */
export function textRsaEncryption(value: string) {
  let keyGenName = "RSA1024";
  let cipherAlgName = "RSA1024|PKCS1";
  //64 RSA每次加解密允許的原文長度大小與密鑰位數和填充模式等有關,詳細規格內容見overview文檔
  let plainTextSplitLen = 117;
  let globalKeyPair; //密鑰對
  let globalEncryptionOutput; //加密輸出
  let arrTest = StringUtils.string2Uint8Array1(value);
  //創建非對稱密鑰生成器對象
  let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator(keyGenName);
  // 創建加密Cipher對象
  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; // 保存到密鑰對全局變量
      return cipherEncryption.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, globalKeyPair.pubKey, null);
    }).then(async () = > {
      globalEncryptionOutput = [];

      // 將原文按64字符進行拆分,循環調用doFinal進行加密,使用1024bit密鑰時,每次加密生成128B長度的密文
      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("加密總長度:" + globalEncryptionOutput.length + "n生成加密串:n" + enStr)
      return enStr
    })
    .catch(error = > {
      LogUtils.i(`加密異常, ${error.code}, ${error.message}`);
    })
}復制

解密:

/**
 * 測試RSA解密
 */
export function textRsaDecryption(value: string) {
  let keyGenName = "RSA1024";
  let cipherAlgName = "RSA1024|PKCS1";
  // RSA密鑰每次加密生成的密文數據長度計算方式:密鑰位數/8
  let cipherTextSplitLen = 128;
  let globalKeyPair; //密鑰對
  //創建非對稱密鑰生成器對象
  let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator(keyGenName);
  // 創建解密Decoder對象
  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; // 保存到密鑰對全局變量
      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進行拆分解密,得到原文后進行拼接
      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);
        //存入數組 解決邊累加邊轉中文時 字節錯亂出現亂碼
        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}`);
    })
}復制

運行代碼:

Text("RSA加解密聯測")
          .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識別開發者項目中選擇的設備形態,找到該設備的支持能力集,篩選支持能力集包含的API并提供API聯想"
            //
            textRsaEncryption(globalPlainText)
              .then(enStr = > {
                if (enStr) textRsaDecryption(enStr)
              })
          })
      }
      .width('100%')
      .height(50)
      .margin({ top: 10 })
      .padding(5)復制

運行結果:

cke_155247.png

終于大功告成!!

審核編輯 黃宇

聲明:本文內容及配圖由入駐作者撰寫或者入駐合作網站授權轉載。文章觀點僅代表作者本人,不代表電子發燒友網立場。文章及其配圖僅供工程師學習之用,如有內容侵權或者其他違規問題,請聯系本站處理。 舉報投訴
  • API
    API
    +關注

    關注

    2

    文章

    1624

    瀏覽量

    64076
  • RSA
    RSA
    +關注

    關注

    0

    文章

    60

    瀏覽量

    19302
  • OpenHarmony
    +關注

    關注

    29

    文章

    3856

    瀏覽量

    18653
  • 鴻蒙OS
    +關注

    關注

    0

    文章

    191

    瀏覽量

    4999
收藏 人收藏
加入交流群
微信小助手二維碼

掃碼添加小助手

加入工程師交流群

    評論

    相關推薦
    熱點推薦

    labviewAES加解密小程序

    本帖最后由 eehome 于 2013-1-5 10:10 編輯 使用AES算法對128bit加密和解密版本:LabVIEW 8.6 8.6.1作者:zerld功能:使用AES算法對128bit加密和解密為便于閱讀,算法還留有優化空間。本
    發表于 02-22 14:12

    加解密

    stm32F4中如何看加解密的代碼
    發表于 04-08 11:23

    硬件加解密的分類

    文章目錄1、硬件加解密的分類2、ARM-CE / ARM-NEON3、Soc crypto engion4、cryptoisland5、cryptocell1、硬件加解密的分類在armv8的芯片
    發表于 07-22 07:55

    如何對AES加解密效率進行測試呢

    如何對AES加解密效率進行測試呢?怎樣去測試AES的加解密效率呢?
    發表于 11-11 06:22

    硬件加解密主要優點及引擎種類

    運算引擎,將一串明碼資料經過加密或編碼(Cryptography)后變成一堆不具意義的亂碼,大幅降低數據傳輸的風險,但資料加密或編碼化是復雜的運算過程,極耗CPU資源,大量加解密資料需求會造成CPU效能
    發表于 08-28 07:29

    STM32加解密技術

    沒有加解密技術是萬萬不能的? 通訊安全? 平臺安全? *例外:STM32 RDP保護知識產權? 加解密技術不是萬能的? 只是工具? 無法代替其它STM32安全技術
    發表于 09-08 08:18

    鴻蒙 OS 應用開發初體驗

    的 IDE、鴻蒙生態的開發語言 ArkTS,通過模擬器運行起來了鴻蒙 OS 版 HelloWorld。對于已經有移動
    發表于 11-02 19:38

    RSA加解密系統及其單芯片實現

    RSA加解密系統及其單芯片實現隨著計算機科技的進步,帶給人類極大的便利性,但伴隨而來的卻是安全性之問題。最簡單便利的安全措施是利用使用者賬號及密碼加以控管,但密
    發表于 11-20 16:25 ?27次下載

    源碼-加解密文本

    易語言是一門以中文作為程序代碼編程語言學習例程:易語言-源碼-加解密文本
    發表于 06-06 17:43 ?6次下載

    DES與RSA兩種加解密算法的詳細資料說明

    對稱加解密算法: 通信雙方(通信主體)同時掌握一個鑰匙,加解密都由這一個鑰匙完成。
    發表于 01-14 17:01 ?12次下載
    DES與<b class='flag-5'>RSA</b>兩種<b class='flag-5'>加解密</b>算法的詳細資料說明

    RSA加密與解密

    RSA加密與解密
    發表于 05-26 15:44 ?4次下載

    STM32的加解密硬件模塊

    電子發燒友網站提供《STM32的加解密硬件模塊.pdf》資料免費下載
    發表于 08-02 09:14 ?1次下載
    STM32的<b class='flag-5'>加解密</b>硬件模塊

    鴻蒙開發ArkTS基礎知識

    一、ArkTS簡介 ArkTS是HarmonyOS優選的主力應用開發語言。它在TypeScript(簡稱TS)的基礎上,匹配了鴻蒙的ArkUI框架,擴展了聲明式UI、狀態管理
    的頭像 發表于 01-24 16:44 ?3345次閱讀
    <b class='flag-5'>鴻蒙</b><b class='flag-5'>開發</b>之<b class='flag-5'>ArkTS</b>基礎知識

    鴻蒙OS開發問題:(ArkTS) 【解決中文亂碼 string2Uint8Array、uint8Array2String】

    在進行base64編碼中,遇到中文如果不進行處理一定會出現亂碼
    的頭像 發表于 03-27 21:38 ?3055次閱讀
    <b class='flag-5'>鴻蒙</b><b class='flag-5'>OS</b><b class='flag-5'>開發問</b>題:(<b class='flag-5'>ArkTS</b>) 【解決<b class='flag-5'>中文</b><b class='flag-5'>亂碼</b> string2Uint8Array、uint8Array2String】

    harmony-utils之RSARSA加解密

    harmony-utils之RSARSA加解密 harmony-utils 簡介與說明 [harmony-utils] 一款功能豐富且極易上手的HarmonyOS工具庫,借助眾多實用工具類,致力于
    的頭像 發表于 06-30 16:52 ?141次閱讀
    主站蜘蛛池模板: 男人天堂网在线播放 | 欧美三级在线观看黄 | 亚洲三级在线视频 | a级毛片免费网站 | 久久久免费视频观看 | 黄视频网站在线观看 | 男女交性视频免费播放视频 | 三级第一页| 日韩在线视频一区 | 亚洲欧美精品一区二区 | 色色色色网 | 在线a人片免费观看不卡 | 色女人久久 | 天天操操操操 | 天堂网2021天堂手机版丶 | 欧美在线视频看看 | 国产精品久久久久天天影视 | 真实的国产乱xxxx在线 | 精品美女在线 | 深爱五月激情网 | 91精品啪在线观看国产日本 | 午夜在线视频 | 日韩不卡毛片 | 在线精品国产成人综合第一页 | 日本黄色大片在线观看 | 午夜精品久视频在线观看 | 久久sese| 国产片一级aaa毛片视频 | 免费看欧美一级特黄α大片 | 看a网站| 日本亚洲在线 | 欧美高清在线观看视频 | 97se亚洲综合 | 综合7799亚洲伊人爱爱网 | h视频在线观看网站 | 免费观看一级一片 | 天堂网资源www | 一区二区三区高清视频在线观看 | 亚洲国产精品自在现线让你爽 | 日韩欧美在线中文字幕 | 男女无遮挡一进一出性视频 |