实现一次非对称RSA非对称加解密

实现一次非对称RSA非对称加解密

HarmonyOS
2024-05-21 20:40:59
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
mafast

核心代码

包含使用随机密钥对和指定密钥对(注释部分)。

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('jm:' + 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
微信
回复
2024-05-22 16:29:27
相关问题
RSA非对称加密-@hms-security/agoh-crypto
423浏览 • 1回复 待解决
是否有支持非对称加密的三方库?
931浏览 • 1回复 待解决
RSA导入外部密钥实现加解密
704浏览 • 1回复 待解决
HarmonyOS 有RSA加解密相关吗
336浏览 • 0回复 待解决
多种加密方式实现加解密
925浏览 • 1回复 待解决
HarmonyOS RSA解密问题
343浏览 • 1回复 待解决
HarmonyOS里面不能一次创建多级目录
286浏览 • 1回复 待解决
有没有一次编译,多端部署的资料
266浏览 • 1回复 待解决
动画如何做渲染一次不消失
7588浏览 • 1回复 待解决
HarmonyOS 加解密 demo
390浏览 • 1回复 待解决
根据一次开发多端部署开发短信页面
1121浏览 • 1回复 待解决