HarmonyOS 使用 cryptoFramework.createCipher 创建RSA非对称加密问题

想让 pubKey 设置为自定义加密key,不想随机生成,因为这个加密key是前端和后端约定的,怎样才能设置自定义Key值呢?

let message = 'This is a test'
let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("RSA"); // 创建非对称密钥生成器对象
let keyPair = await asyKeyGenerator.generateKeyPair(); // 随机生成RSA密钥
let pubKey = keyPair.pubKey
let plainText: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from(message, 'utf-8').buffer) };
let cipher = cryptoFramework.createCipher('RSA|PKCS1');
cipher.initSync(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null);
HarmonyOS
1天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
fox280

可以参考如下代码进行自定义Key的加解密:

import { cryptoFramework } from '@kit.CryptoArchitectureKit';
import { buffer, util } from '@kit.ArkTS';
import { BusinessError } from '@kit.BasicServicesKit';

@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='

  build() {
    Row() {
      Column() {
        TextInput({ text: this.message })
          .onChange((value: string) => {
            this.message = value
          })
        Text('加密前的数据:')
        Text(this.message)
        Button('加密').onClick(() => {
          let signData = signMessagePromise(priKey)
          signData.then((result: cryptoFramework.DataBlob) => {
            signMsBlob = result
          }).catch((error: BusinessError) => {
            console.error("error:" + error)
          });
        })
        Button('解密').onClick(() => {
          verifyMessagePromise(signMsBlob, pubkey)
        })
        Text('加密后的数据:')
        Text(this.jmMessage)
        Text('解密后的数据:')
        Text(this.jiemMessage)
      }
      .width('100%')
    }
    .height('100%')
  }


}


let signMsBlob: cryptoFramework.DataBlob

//私钥加密
async function signMessagePromise(priKey: cryptoFramework.PriKey) {
  console.log('signMessagePromise start')
  let signAlg = "RSA1024|PKCS1|NoHash|OnlySign";
  let signer = cryptoFramework.createSign(signAlg);
  await signer.init(priKey);
  let signData = await signer.sign({data:stringToUint8Array("私钥加密")});
  console.log('signMessagePromise end')
  return signData;
}
// 公钥解密
async function 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 " + uint8ArrayToString(rawSignData?.data))
  return rawSignData;
}
// 字节流转成可理解的字符串
export function uint8ArrayToString(array:Uint8Array) {
  // 将UTF-8编码转换成Unicode编码
  let out: string = "";
  let index: number = 0;
  let len: number = array.length;
  while (index < len) {
    let character = array[index++];
    switch(character >> 4) {
      case 0:
      case 1:
      case 2:
      case 3:
      case 4:
      case 5:
      case 6:
      case 7:
        out += String.fromCharCode(character);
        break;
      case 12:
      case 13:
        out += String.fromCharCode(((character & 0x1F) << 6) | (array[index++] & 0x3F));
        break;
      case 14:
        out += String.fromCharCode(((character & 0x0F) << 12) | ((array[index++] & 0x3F) << 6) | ((array[index++] & 0x3F) << 0));
        break;
      default:
        break;
    }
  }
  return out;
}
// 字符串转成字节流
export function stringToUint8Array(str: string) {
  return new Uint8Array(buffer.from(str,'utf-8').buffer);
}

async function convertPubkey(pub: string, pri: string) {
  // rsa2048
  let base = new util.Base64Helper()

  try {
    let rsaGenerator = cryptoFramework.createAsyKeyGenerator('RSA2048');
    let pukData = base.decodeSync(pub)
    let priData = base.decodeSync(pri)
    let keyPair = await rsaGenerator.convertKey({ data: pukData }, { data: priData })
    console.log("RSA key success =>")
    let pubkey = keyPair.pubKey;
    let priKey = keyPair.priKey;
    let pkBlob = pubkey.getEncoded();
    let skBlob = priKey.getEncoded();
    AlertDialog.show({ message: 'pk bin data ' + pkBlob.data });
    AlertDialog.show({ message: 'sk bin data ' + skBlob.data });
    return pubkey;
  } catch (err) {
    console.error("error===》" + err)
  }
  return null;
}

let pubkey: cryptoFramework.PubKey;
let priKey: cryptoFramework.PriKey;
async function convertPrikey(pub: string, pri: string) {

  try {
    let base = new util.Base64Helper()
    let rsaGenerator = cryptoFramework.createAsyKeyGenerator('RSA2048');
    let pukData = base.decodeSync(pub)
    let priData = base.decodeSync(pri)
    let keyPair = await rsaGenerator.convertKey({ data: pukData }, { data: priData })
    console.log("RSA key success =>")
    pubkey = keyPair.pubKey;
    priKey = keyPair.priKey;
    return priKey;
  } catch (err) {
    console.error("error===》" + err)
  }
  return null;
}
分享
微博
QQ
微信
回复
1天前
相关问题
RSA非对称加密-@hms-security/agoh-crypto
565浏览 • 1回复 待解决
实现一次非对称RSA非对称加解密
1102浏览 • 1回复 待解决
是否有支持非对称加密的三方库?
1065浏览 • 1回复 待解决
HarmonyOS RSA加密失败问题
35浏览 • 1回复 待解决
HarmonyOS RSA加密中,公私钥问题
27浏览 • 1回复 待解决
HarmonyOS RSA加密方式
677浏览 • 1回复 待解决
RSA 加密的具体使用方法
243浏览 • 1回复 待解决
RSA加密使用自有私钥解密报错
271浏览 • 1回复 待解决
如何使用RSA公钥加密明文数据
498浏览 • 1回复 待解决
HarmonyOS rsa加密报错
45浏览 • 1回复 待解决
HarmonyOS RSA分段加密乱码
633浏览 • 1回复 待解决
HarmonyOS 实现RSA加密功能
626浏览 • 1回复 待解决
HarmonyOS RSA加密算法实现
37浏览 • 1回复 待解决
RSA NoPadding模式加密失败
1274浏览 • 1回复 待解决