HarmonyOS RSA指定公钥或私钥字符串加密和解密

RSA指定公钥或私钥字符串加密和解密,得到加密或解密后的字符串

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

可以参考下述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() }
  private privateKey: string =
    'MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAMMwqzr5he95mLKR' +
      'd4mstwtAivjS2+wLWFzNTtQKM2R6SPkpsBv19Yxzv6MXMGdAtBkXnp+8ix7SUDDe' +
      '92+nUYy5rr8wT82MAh9e40bBeaPegN4y+6EVZlAHhfWZX/8Lkw/7H3rMbs9oAz+R' +
      'bVuMvfaksyBY7Dn2zGvKbGE92gO1AgMBAAECgYBbTOWbRWIn3QnW5QI0LMzF/5/B' +
      'uefS5o+jgQlRV6AobKa7nYtZ2NfNpcrK/6rNcU+MuSaicy/j795ArdqxqGMVDELN' +
      '5Xyk4oZ/14VxHyjLCUrfyYAn++nwBQPFPXBwE9V23aXBTPoVmdndfTDANlmbq7Vw' +
      '0atPncJ92tXXOvC2FQJBAP8+Gae15TYQbEeKvy35hXFOM7sbqEfUZ9KmT46Ixy0j' +
      'K6WMZu7SWZ1V4eLNGcGBQAkdq2tmMAKAiyiwEqE/RF8CQQDDxPLciFnEFzWPCdMK' +
      'BucEVcofsFNLPIstQDvzD0p5AFM1qP/Zvc8oBVUjesY7StwXvt+RuE0aptK3XgHK' +
      '7ZBrAkEArw1VJQuAFxMuX+aNdaeC2JGssu+l+xV22ybKu1OdXpyXa6OeWL6VTW3A' +
      'TP8jYe4WD+p0TWU5Gg404oPXUxWD+wJBAKRBO++y63Yubv6bpJkWH4Cwpk0eOVS3' +
      '8KI/8czGuJp7nlU4fapoqkYO61dAbNBUyAOYX6a49uB0tfmqA2ELIA8CQQCNHV8I' +
      'AsrJu0BAU6Cgd4iN4XuBzEqeeDALF6RyX4+FA6glQsWPD0QtEYHRCmCnfNeKKeaK' +
      'asllOuY/s3LgbDfW'
  private pubKeyString: string =
    'MIGJAoGBAMMwqzr5he95mLKRd4mstwtAivjS2+wLWFzNTtQKM2R6SPkpsBv19Yxz' +
      'v6MXMGdAtBkXnp+8ix7SUDDe92+nUYy5rr8wT82MAh9e40bBeaPegN4y+6EVZlAH' +
      'hfWZX/8Lkw/7H3rMbs9oAz+RbVuMvfaksyBY7Dn2zGvKbGE92gO1AgMBAAE='

  // 加密
  async jm(text: string) {
    let rsaGenerator = cryptoFramework.createAsyKeyGenerator('RSA1024')
    // 指定公钥和密钥,生成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 = await rsaGenerator.generateKeyPair()
    // 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 = cryptoFramework.createCipher("RSA1024|PKCS1");
    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 }
    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 = 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() {
        TextInput({ text: this.message })
          .onChange((value: string) => {
            this.message = value
          })
        Text('加密前的数据:')
        Text(this.message)
        Button('加密').onClick(() => {
          this.jm(this.message).then(data => {
            this.jmMessage = data
          })
        })
        Button('解密').onClick(() => {
          this.jiem(this.jieStr).then(data => {
            this.jiemMessage = data
          })
        })
        Text('加密后的数据:')
        Text(this.jmMessage)
        Text('解密后的数据:')
        Text(this.jiemMessage)
      }
      .width('100%')
    }
    .height('100%')
  }
}
分享
微博
QQ
微信
回复
1天前
相关问题
HarmonyOS RSA私钥加密解密
44浏览 • 1回复 待解决
HarmonyOS 私钥加密解密问题
78浏览 • 1回复 待解决
HarmonyOS RSA解密
16浏览 • 1回复 待解决
HarmonyOS RSA如何用解密
666浏览 • 0回复 待解决
HarmonyOS 支持rsa使用解密
499浏览 • 1回复 待解决
HarmonyOS 关于RSA解密问题
34浏览 • 1回复 待解决
rsa 解密初始化报错
309浏览 • 1回复 待解决
如何使用RSA加密明文数据
496浏览 • 1回复 待解决
RSA加密,使用自有私钥解密报错
268浏览 • 1回复 待解决
如何实现RSAPK加密一段文字
638浏览 • 1回复 待解决
关于加密字符串相关问题
233浏览 • 1回复 待解决
HarmonyOS 加密字符串格式转换
66浏览 • 1回复 待解决
字符串重复指定次数
402浏览 • 1回复 待解决
HarmonyOS RAS加密,AES加密和解密
67浏览 • 1回复 待解决