HarmonyOS 鸿蒙Next SHA1WithRSA 指定秘钥 签名验签的demo

发布于 1周前 作者 songsunli 来自 鸿蒙OS

HarmonyOS 鸿蒙Next SHA1WithRSA 指定秘钥 签名验签的demo SHA1WithRSA 指定秘钥 签名验签的 demo 有吗,能提供一份吗,谢谢

2 回复

可以参考如下demo:

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

@Entry
@Component
struct RSAExample {

  async signMessagePromise(content: cryptoFramework.DataBlob, priKey: cryptoFramework.PriKey) {
    let signAlg = "RSA1024|PKCS1|SHA1"; // 签名算法规格
    let signer = cryptoFramework.createSign(signAlg);
    await signer.init(priKey);
    let signData = await signer.sign(content);
    return signData;
  }

  async verifyMessagePromise(content: cryptoFramework.DataBlob, signMessageBlob: cryptoFramework.DataBlob, pubKey: cryptoFramework.PubKey) {
    let verifyAlg = "RSA1024|PKCS1|SHA1"; // 签名算法规格
    let verifier = cryptoFramework.createVerify(verifyAlg);
    await verifier.init(pubKey);
    let res = await verifier.verify(content, signMessageBlob);
    console.info("verify result is " + res);
    return res;
  }

  async convertAsyKey() {
    let rsaGenerator = cryptoFramework.createAsyKeyGenerator('RSA1024');
    // 随机生成的公私钥对,Base64格式
    let pubKeyVal = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDAn7UujTR0CX1ujnNn70MtLlSESk/Y6fBsSw3s9/XqkuiXbGPUzkNbP0rldmTfzLEw/bhu43/v4mbeq18OAoIdpW/I4OhNSMhAO+c0Urjmqp0/p/0xEPO8r42g1OExaGdioLj9CUw18ODEG8nNhW/Py0NN002G87wJm/bYwG0OhwIDAQAB";
    let priKeyVal = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMCftS6NNHQJfW6Oc2fvQy0uVIRKT9jp8GxLDez39eqS6JdsY9TOQ1s/P...";

    let pkBlob: cryptoFramework.DataBlob = { data: this.stringToUnit8Array(pubKeyVal) };
    let prBlob: cryptoFramework.DataBlob = { data: this.stringToUnit8Array(priKeyVal) };

    rsaGenerator.convertKey(pkBlob, prBlob, async (err, keyPair) => {
      if (err) {
        console.error(`convertKey failed, ${err.code}, ${err.message}`);
        return;
      }
      console.info('convertKey success!');
      let plainText: string = "test";
      let res = await this.signMessagePromise({
        data: new Uint8Array(buffer.from(plainText, 'utf-8').buffer)
      }, keyPair.priKey)

      console.log("convertKey sign result:" + new util.Base64Helper().encodeToStringSync(res.data))
      let verifyResult = await this.verifyMessagePromise({
        data: new Uint8Array(buffer.from(plainText, 'utf-8').buffer)
      }, res, keyPair.pubKey);

      if (verifyResult == true) {
        console.info('convertKey verify success');
      } else {
        console.error('convertKey verify failed');
      }
    });
  }

  stringToUnit8Array(str: string): Uint8Array {
    return new util.Base64Helper().decodeSync(str)
  }

  build() {
    Button("获取信息").width(100).height(100)
      .onClick(() => {
        this.convertAsyKey()
      })
  }
}

更多关于HarmonyOS 鸿蒙Next SHA1WithRSA 指定秘钥 签名验签的demo的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS(鸿蒙)系统中进行SHA1WithRSA指定密钥的签名与验签操作,你可以参考以下代码示例。该示例直接展示了如何在鸿蒙环境中实现该功能,不涉及Java或C语言相关内容。

#include <Security/Security.h>

// 假设你已经有了一个RSA密钥对
SecKeyRef privateKey = ...; // 你的私钥
SecKeyRef publicKey = ...;  // 你的公钥

// 要签名的数据
CFDataRef dataToSign = ...;

// 签名
CFErrorRef error = nullptr;
CFDataRef signature = SecKeyCreateSignature(privateKey,
                                            kSecKeyAlgorithmRSASignatureDigestSHA1,
                                            dataToSign,
                                            &error);
if (error) {
    // 处理错误
}

// 验签
Boolean isValid = SecKeyVerifySignature(publicKey,
                                        kSecKeyAlgorithmRSASignatureDigestSHA1,
                                        dataToSign,
                                        signature,
                                        &error);
if (error) {
    // 处理错误
}
if (isValid) {
    // 签名验证成功
} else {
    // 签名验证失败
}

// 注意:上述代码为简化示例,实际使用中需要处理内存管理、错误处理等细节。

如果问题依旧没法解决请联系官网客服,官网地址是 https://www.itying.com/category-93-b0.html,
回到顶部