HarmonyOS 关于RSA公钥加解密问题

目前我们的业务是服务端有私钥,客户端有公钥,客户端把接口参数用公钥加密后给服务端,服务端用私钥解密,请求成功了服务端会把数据用私钥加密给到客户端,客户端用公钥解密出来,麻烦帮忙出个完整的Demo

HarmonyOS
1天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
Heiang

参考示例如下:

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('jm:-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('jm:-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('jm:-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('jm:' + 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%')
  }
}

需要注意两个地方的修改

1、字符串转换

2、2. 去掉密文中的\n

分享
微博
QQ
微信
回复
1天前
相关问题
HarmonyOS RSA解密
16浏览 • 1回复 待解决
HarmonyOS RSA如何用解密
666浏览 • 0回复 待解决
HarmonyOS RSA私钥加密解密
44浏览 • 1回复 待解决
HarmonyOS 支持rsa使用解密
499浏览 • 1回复 待解决
rsa 解密初始化报错
313浏览 • 1回复 待解决
HarmonyOS 私钥加密解密问题
80浏览 • 1回复 待解决
RSA导入外部密钥实现加解密
816浏览 • 1回复 待解决
HarmonyOSRSA加解密相关吗
461浏览 • 0回复 待解决
如何使用RSA加密明文数据
496浏览 • 1回复 待解决
HarmonyOS 是否有rsa加解密的例子?
45浏览 • 1回复 待解决
HarmonyOS Native RSA 加解密实现咨询
33浏览 • 1回复 待解决
HarmonyOS RSA解密问题
490浏览 • 1回复 待解决
HarmonyOS 证书问题
33浏览 • 1回复 待解决
HarmonyOS 加解密问题
48浏览 • 1回复 待解决
如何实现RSAPK加密一段文字
641浏览 • 1回复 待解决
HarmonyOS 关于DES加解密的疑问
34浏览 • 1回复 待解决
HarmonyOS AES加解密问题
37浏览 • 1回复 待解决