HarmonyOS RSA加密算法实现

实现一套跟其他系统相同的RSA加密算法功能。

目前在复刻APP,其中有一个本地RAS加密功能无法实现,该加密功能在APP中比不可少,很多跟后台的接口交互都要用到,否则APP就无法使用。

希望可以再HarmonyOS 系统上实现该工具类的功能,完成public String encryptPwd(String publicKey, String pwd)方法。

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

demo实例如下

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

@Entry
@Component
struct RSAOAEPCrypto {
  @State message: string = '点击开始';

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {
            RSAOAEP()
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}

// 生成RSA密钥对
async function genKeyPairByData(pubKeyData: Uint8Array, priKeyData: Uint8Array) {
  let pubKeyBlob: cryptoFramework.DataBlob = { data: pubKeyData };
  let priKeyBlob: cryptoFramework.DataBlob = { data: priKeyData };
  let rsaGenerator = cryptoFramework.createAsyKeyGenerator('RSA2048');
  let keyPair = await rsaGenerator.convertKey(pubKeyBlob, priKeyBlob);
  console.error('convertKey success');
  return keyPair;
}

async function RSAOAEP() {
  // 获得RSA密钥对密钥参数对象
let pkData = "-----BEGIN PUBLIC KEY-----\n" +
  "MIIBIjANBgkqhkiG9w0BAQEFxxxxxxxCgKCAQEAr+q/H5DxV1etGxTNWtns\n" +
  "xmVkiAKVPEcejoNT2xObwsQ/xxxxxxxkIY3Yd63S3RFcdmlIy4NFEg+ccrqpu\n" +
  "4z/Zi0AHELDk28WxMxLj1tr7xxxxxxxjpzyRW/6Cm9RMfGtASiJFmARlQiVaZ+f\n" +
  "/QemObAJfnJLEbqOJeIh6byJxxxxxxxVqaK/2n+1hBsfcFq8OAAXG3fMOVipOSNc\n" +
  "raL6FxPrZ2iVS6OvbTV2PmiFxxxxxxxPVNj1Nfe3Gc2W7q/NRkMFWfhOg5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kF3RLwzAu\n" +
  "VExg4seeZhQLsiw9Nmwdxxxxxxxxxxxxxxzw+a/Uo2lOpML9sFqw9ywxegDS9Xxq\n" +
  "Iq0x3pfoiq4YaIbPXZYQxxxxxxxxxxxxxxxxxdT+6kVcyh0tKgsxu2GTcL0XYaiU5uI\n" +
  "YkkWoTdOI+x/nBIusypxxxxxxxxxxxxxxxxxxg+SvbLtYP/QpserXxjOrCoXN5thNX\n" +
  "hYjGzYqp2siE0Rz4rawuxxxxxxxxxxxxxxxxxw70Lp7Pd1zhLCpYxN1w041qDu9D\n" +
  "s38osNIbbwKBgB6XpxxxxxxxxxxxxxxxxxmKDfEHXXAaWXK8DePCl8BuP13kcSLev6\n" +
  "rbGd6CxYbuA7QKMMXsF/xxxxxxxxxxxxxfmRVJ5bbyqq/PaczqCF2grZjWdUD7cKD\n" +
  "UNV8mUG3DVei3r70QbYwYxxxxxxxxxxxxxxxDhQpquskvEx5sUOham4yjFVBxAoGAPems\n" +
  "dIquKX7VgPU3bXo34rjlxxxxxxxxxxxxxxxxxxpkoyoLS12l1VI+KggQe3YFk8MGYonRy\n" +
  "AgXK6W18KjFNEIKqfukR/nVxxxxxxxxxxxxxxATip+y/8KbYO9kCcGOu9ZliX3W7nL\n" +
  "OL7uCyp/c7FyAWN2JwtkFJOxxxxxxxxxxxxxxxxxxxxxx9ETVUCgYBqH8eXUsGuu6HmzFgkgKZ/\n" +
  "w+nnFQNoNUgWQyD7ahxSgIxxxxxxxxxxxxxxx1GiYh2xYn7MjKBpKaikLBuSA/8V2+tp\n" +
  "+t20QNGzTEBtz1+u4QoHNMlxxxxxxxxxnsraypYCurgL0twMZxmLq1d5pR2yL74CQ\n" +
  "nuLkoZ5CforupRMjEaxPDw==\n" +
  "-----END PRIVATE KEY-----";

  try {
    let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator('RSA1024');
    let keyPairData = asyKeyGenerator.convertPemKeySync(pkData, skData);
    if (keyPairData != null) {
      console.error('[Sync]: convert pem key pair success');
    } else {
      console.error("[Sync]: convert pem key pair result fail!");
    }

    let priPemKey = keyPairData.priKey;
    let pubPemKey = keyPairData.pubKey;
    // pem生成公私密钥字符串
    let priString = priPemKey.getEncodedPem('PKCS8');
    let pubString = pubPemKey.getEncodedPem('X509');
    // 去除字符串 -----BEGIN PRIVATE KEY-----
    let priB = priString.replace("-----BEGIN PRIVATE KEY-----", "")
    let pubB = pubString.replace("-----BEGIN PUBLIC KEY-----", "")
    // 去除字符串 -----END PRIVATE KEY-----
    let priE = priB.replace("-----END PRIVATE KEY-----", "")
    let pubE = pubB.replace("-----END PUBLIC KEY-----", "")
    // 去除换行符
    let pri = priE.replaceAll("\n", "")
    let pub = pubE.replaceAll("\n", "")

    console.info("[Sync]TestPkcs1ToPkcs8BySync pripripri output is " + pri);
    console.info("[Sync]TestPkcs1ToPkcs8BySync pubpubpub output is " + pub);

    if (keyPairData != null) {
      console.info('[Sync]: convert pem key pair success');
      // base64 转换器
      let base64 = new util.Base64Helper();
      // base64 转码
      let base64pkData = base64.decodeSync(pub);
      let base64skData = base64.decodeSync(pri);

      let keyPair = await genKeyPairByData(base64pkData, base64skData);

      //明文
      let plan = "This is a test";

      // 根据RSA密钥对参数生成RSA密钥对
      let cipher = cryptoFramework.createCipher("RSA1024|PKCS1_OAEP|SHA256|MGF1_SHA1");
      let decoder = cryptoFramework.createCipher("RSA1024|PKCS1_OAEP|SHA256|MGF1_SHA1");
      // RSA加解密PKCS1-OAEP模式填充字节流P
      let pSource = new Uint8Array([1, 2, 3, 4]);
      let input: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from(plan, 'utf-8').buffer) };

      // 进行加密操作初始化
      cipher.initSync(cryptoFramework.CryptoMode.ENCRYPT_MODE, keyPair.pubKey, null);
      // get和set操作可以放在Cipher对象init之后,此处对cipher进行set和get操作
      cipher.setCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF1_PSRC_UINT8ARR, pSource);
      let retP = cipher.getCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF1_PSRC_UINT8ARR);
      // 比较get出来的P字节流与set进去的P字节流是否一致
      if (retP.toString() != pSource.toString()) {
        console.error("error init pSource" + retP);
      } else {
        console.error("pSource changed ==" + retP);
      }
      // 进行OAEP其他参数的get操作
      let md = cipher.getCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MD_NAME_STR);
      console.error("md == " + md);
      let mgf = cipher.getCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF_NAME_STR);
      console.error("mgf == " + mgf);
      let mgf1Md = cipher.getCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF1_MD_STR);
      console.error("mgf1Md == " + mgf1Md);
      let cipherDataBlob = cipher.doFinalSync(input);
      console.error('encrypt plainText: ' + base64.encodeToStringSync(cipherDataBlob.data));

      // get和set操作可以放在Cipher对象init之前,且与init之后等价,此处对decoder进行set和get操作
      decoder.setCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF1_PSRC_UINT8ARR, pSource);
      retP = decoder.getCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF1_PSRC_UINT8ARR);
      // 比较get出来的P字节流与set进去的P字节流是否一致
      if (retP.toString() != pSource.toString()) {
        console.error("error init pSource" + retP);
      } else {
        console.error("pSource changed ==" + retP);
      }

      // 进行OAEP其他参数的get操作
      md = decoder.getCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MD_NAME_STR);
      console.error("md == " + md);
      mgf = decoder.getCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF_NAME_STR);
      console.error("mgf == " + mgf);
      mgf1Md = decoder.getCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF1_MD_STR);
      console.error("mgf1Md == " + mgf1Md);
      // 初始化解密操作
      decoder.initSync(cryptoFramework.CryptoMode.DECRYPT_MODE, keyPair.priKey, null);
      let decodeData = decoder.doFinalSync(cipherDataBlob);

      // Uint8Array 转 Base64 String
      let base64String = base64.encodeToStringSync(decodeData.data);
      console.error("base64 string:   "  + base64String);

      // 解密成功
      if (decodeData.data.toString() === input.data.toString()) {
        // Uint8Array 转 String字符串
        let textDecoder = util.TextDecoder.create('utf-8')
        let string = textDecoder.decodeWithStream(decodeData.data)
        console.error("oaep decrypt success:   "  + string);
      } else {
        console.error("oaep decrypt fail");
      }
    } else {
      console.error("[Sync]: convert pem key pair result fail!");
    }
  } catch (e) {
    console.error(`Sync error, ${e.code}, ${e.message}`);
  }
}
分享
微博
QQ
微信
回复
1天前
相关问题
HarmonyOS AES加密算法demo
41浏览 • 1回复 待解决
安全加密算法代码参考
1807浏览 • 1回复 待解决
HarmonyOS SM2加密算法
23浏览 • 1回复 待解决
HarmonyOS MD5加密算法demo
37浏览 • 1回复 待解决
HarmonyOS 需要MD5加密算法
49浏览 • 1回复 待解决
HarmonyOS HmacSHA1 加密算法 参数问题
38浏览 • 1回复 待解决
HarmonyOS 是否有带iv的DES加密算法
526浏览 • 1回复 待解决
加密算法(crypto-js)Arkts转化代码
1144浏览 • 1回复 待解决
是否有AES的ECB模式的加密算法
579浏览 • 1回复 待解决
HarmonyOS 实现RSA加密功能
622浏览 • 1回复 待解决
HarmonyOS 请问ArkTS如何实现RSA加密
522浏览 • 1回复 待解决
HarmonyOS RSA算法如何使用
349浏览 • 1回复 待解决
RSA加密方法在HarmonyOS实现
29浏览 • 1回复 待解决
HarmonyOS RSA加密方式
672浏览 • 1回复 待解决
HarmonyOS rsa加密报错
45浏览 • 1回复 待解决
HarmonyOS RSA分段加密乱码
633浏览 • 1回复 待解决
HarmonyOS RSA加密失败问题
35浏览 • 1回复 待解决
RSA NoPadding模式加密失败
1271浏览 • 1回复 待解决
HarmonyOS 密钥库RSA算法的使用demo
41浏览 • 1回复 待解决