HarmonyOS RSA 公钥加密成功,但使用私钥加密,初始化方法报错

项目中使用 RSA 进行私钥加密时,cipher.init 方法报错。

日志堆栈:

Cannot get SourceMap info, dump raw stack:
=====================Backtrace========================
#01 pc 00000000006a40c7 /system/lib64/platformsdk/libark_jsruntime.so
#02 pc 00000000002f9d69 /system/lib64/platformsdk/libark_jsruntime.so
#03 pc 000000000019d868 /system/lib64/platformsdk/libark_jsruntime.so
#04 pc 000000000019d0e1 /system/lib64/platformsdk/libark_jsruntime.so
#05 pc 00000000002269e1 /system/lib64/platformsdk/libark_jsruntime.so
#06 pc 000000000059c4c5 /system/lib64/platformsdk/libark_jsruntime.so
#07 pc 000000000056548e /system/lib64/platformsdk/libark_jsruntime.so
#08 pc 0000000000055b11 /system/lib64/platformsdk/libace_napi.z.so
#09 pc 0000000000031443 /system/lib64/module/security/libcryptoframework_napi.z.so
#10 pc 00000000000156d6 /system/lib64/module/security/libcryptoframework_napi.z.so
#11 pc 0000000000060af4 /system/lib64/platformsdk/libace_napi.z.so
#12 pc 0000000000015be6 /system/lib64/platformsdk/libuv.so
#13 pc 000000000001a122 /system/lib64/platformsdk/libuv.so
#14 pc 0000000000019943 /system/lib64/platformsdk/libuv.so
#15 pc 000000000001a5b7 /system/lib64/platformsdk/libuv.so
HarmonyOS
1天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
fox280

参考以下demo:

import { cryptoFramework } from '@kit.CryptoArchitectureKit';
import { util } from '@kit.ArkTS';

@Entry
@Component
struct Index {
  @State message: string = 'Hello World';
  @State jmMessage: string = '暂无'
  @State jiemMessage: string = '暂无'
  @State jieStr: string = ''
  private keyPair: cryptoFramework.KeyPair | undefined = undefined
  private jmBlob: cryptoFramework.DataBlob = { data: new Uint8Array() }

  aboutToAppear(): void {
    let rsaGenerator = cryptoFramework.createAsyKeyGenerator('RSA1024|PRIMES_2')
    console.log('-1')
    // 指定公钥和密钥,生成keypair
    // let pkUnit8 = this.convertBase64ToUnit8Array(this.pubKeyString)
    // let prUnit8 = this.convertBase64ToUnit8Array(this.privateKey)
    // let pkBlob: cryptoFramework.DataBlob = { data: pkUnit8 }
    // let prBlob: cryptoFramework.DataBlob = { data: prUnit8 }
    // let keyPair:cryptoFramework.KeyPair = await rsaGenerator.convertKey(pkBlob, null)
    // 随机生成keypair的代码
    this.keyPair = rsaGenerator.generateKeyPairSync()
    console.log('-2')
  }
  //私钥加密
  async signMessagePromise(priKey: cryptoFramework.PriKey, data:string) {
    let signAlg = "RSA1024|PKCS1|NoHash|OnlySign";
    let signer = cryptoFramework.createSign(signAlg);
    await signer.init(priKey);
    let signData = await signer.sign({data: this.convertStringToUnit8Array(data)});
    return signData;
  }

  // 公钥解密
  async verifyMessagePromise(signMessageBlob: cryptoFramework.DataBlob, pubKey: cryptoFramework.PubKey) {
    let verifyAlg = "RSA1024|PKCS1|NoHash|Recover";
    let verifier = cryptoFramework.createVerify(verifyAlg);
    await verifier.init(pubKey);
    let rawSignData = await verifier.recover(signMessageBlob);
    console.log("rsa puk data " + this.convertUnit8ArrayToString(rawSignData?.data))
    return rawSignData;
  }


  // 加密
  async jm(text: string) {

    // this.keyPair = sjkeyPair
    let Base64Helper = new util.Base64Helper()
    // let sjpubKey = Base64Helper.encodeToStringSync(this.keyPair.pubKey.getEncoded().data)
    // let sjprKey = Base64Helper.encodeToStringSync(this.keyPair.priKey.getEncoded().data)

    // 获取相应的Cipher实例
    let cipher = await cryptoFramework.createCipher("RSA1024|PKCS1");
    await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, this.keyPair!.pubKey, null)
    // 将明文string转化成UnitArray
    let inputUnit8Array = this.convertStringToUnit8Array(this.message)
    // let inputUnit8Array = Base64Helper.decodeSync(this.message)
    let inputBlob: cryptoFramework.DataBlob = { data: inputUnit8Array }
    console.log('-3')
    let resultBlob = await cipher.doFinal(inputBlob)

    this.jmBlob = resultBlob
    // let resStr = this.convertUnit8ArrayToString(resultBlob.data)
    // 将blob转成str
    let resStr = Base64Helper.encodeToStringSync(resultBlob.data)
    console.log(resultBlob.data.toString())
    this.jieStr = resStr
    return resStr
  }

  // 解密

  async jiem(text: string) {
    try {
      let decoder = await cryptoFramework.createCipher('RSA1024|PKCS1');
      console.log('ji_priKey:' + this.keyPair!.priKey.getEncoded().data.toString())
      await decoder.init(cryptoFramework.CryptoMode.DECRYPT_MODE, this.keyPair!.priKey, null);
      let Base64Helper = new util.Base64Helper()
      let jiemessage = Base64Helper.decodeSync(text)
      console.log('jiem:' + jiemessage.toString())
      let decryptData = await decoder.doFinal({ data: jiemessage });
      // let decryptData = await decoder.doFinal(this.jmBlob);
      let decryptDataString = this.convertUnit8ArrayToString(decryptData.data)
      // let decryptDataString = Base64Helper.encodeToStringSync(decryptData.data)
      return decryptDataString
    } catch (e) {
      console.log('error123:' + JSON.stringify(e))
      return ''
    }
  }

  // 将base64转成unit8
  convertBase64ToUnit8Array(text: string) {
    let base64Helper = new util.Base64Helper();
    return base64Helper.decodeSync(text)
  }

  // 将unit8转成string ,字节码不能为0
  convertUnit8ArrayToString(uint8: Uint8Array) {
    return util.TextDecoder.create().decodeWithStream(uint8)
  }

  // 将密文string转成unit8
  // convertPriStringToUnit8Array(text: string) {
  // return new util.TextEncoder().encodeIntoUint8Array(text,)
  // }
  // 将明文string转成unit8,处理不了汉字和特殊字符
  convertStringToUnit8Array(text: string) {
    // return new util.TextEncoder().encodeInto(text)
    let arr: number[] = new Array(text.length)
    for (let i = 0, j = text.length; i < j; i++) {
      arr[i] = text.charCodeAt(i)
    }
    return new Uint8Array(arr)
  }

  build() {
    Row() {
      Column() {
        Text('带加密数据:')
        TextInput({ text: this.message })
          .onChange((value: string) => {
            this.message = value
          })
        Row()
        {
          Button('公钥加密').onClick(() => {
            console.log("加密 button");
            this.jm(this.message).then(data => {
              this.jmMessage = data
            })
          })
        }
        Row(){

        }.height(5)
        Row()
        {
          Button('私钥解密').onClick(() => {
            this.jiem(this.jieStr).then(data => {
              console.log("解密 button");
              this.jiemMessage = data
            })
          })
        }
        Row(){

        }.height(5)
        Row()
        {
          Button('清空').onClick(() => {
            this.jiemMessage = ''
            this.jmMessage = ''
          })

        }

        Row(){

        }.height(5)

        Row(){
          Button("私钥加密").onClick(()=>{
            this.signMessagePromise(this.keyPair!.priKey, this.message).then((result)=>{
              this.jmBlob = result
              let Base64Helper = new util.Base64Helper()
              this.jmMessage = Base64Helper.encodeToStringSync(result.data)
            })
          })
        }
        Row(){

        }.height(5)
        Row(){
          Button("公钥解密").onClick(()=>{
            this.verifyMessagePromise({data: this.jmBlob.data}, this.keyPair!.pubKey).then((result)=>{
              this.jiemMessage = this.convertUnit8ArrayToString(result!.data)
            })

          })
        }
        Text('加密后的数据:')
          .fontColor(Color.Red)
          .textAlign(TextAlign.Start)

        Text(this.jmMessage)
        Text('解密后的数据:')
        Text(this.jiemMessage)
      }
      .width('100%')
    }
    .height('100%')
  }
}
分享
微博
QQ
微信
回复
1天前
相关问题
HarmonyOS RSA私钥加密解密
49浏览 • 1回复 待解决
rsa 解密初始化报错
313浏览 • 1回复 待解决
HarmonyOS 私钥加密解密问题
80浏览 • 1回复 待解决
如何使用RSA加密明文数据
498浏览 • 1回复 待解决
RSA加密使用自有私钥解密报错
271浏览 • 1回复 待解决
如何实现RSAPK加密一段文字
641浏览 • 1回复 待解决
HarmonyOS RSA加密中,公私钥问题
24浏览 • 1回复 待解决
HarmonyOS rsa加密报错
45浏览 • 1回复 待解决
RSA 加密的具体使用方法
243浏览 • 1回复 待解决
HarmonyOS RSA解密
16浏览 • 1回复 待解决
HarmonyOS 支持rsa使用解密吗
499浏览 • 1回复 待解决
HarmonyOS 加密导入RSA1024秘对Demo
26浏览 • 1回复 待解决
HarmonyOS RSA加密的base64秘转换
26浏览 • 1回复 待解决
HarmonyOS struct初始化方法
70浏览 • 1回复 待解决
RSA加密方法HarmonyOS 的实现
29浏览 • 1回复 待解决
HarmonyOS RSA如何用解密
666浏览 • 0回复 待解决