如何在 RSA_encrypt 密钥对生成算法中以 STRING 格式获取 publicKey

How to get publicKey in RSA_encrypt key-pair generation algorithm in STRING format in flutter

我目前正在我的 flutter 应用程序中进行加密,其中我使用 RSA 密钥对生成器来获取 public 和使用以下代码的私钥-

import 'package:rsa_encrypt/rsa_encrypt.dart';
import 'package:pointycastle/api.dart' as crypto;

//Future to hold our KeyPair
Future<crypto.AsymmetricKeyPair> futureKeyPair;

//to store the KeyPair once we get data from our future
crypto.AsymmetricKeyPair keyPair;

Future<crypto.AsymmetricKeyPair<crypto.PublicKey, crypto.PrivateKey>> getKeyPair()
{
var helper = RsaKeyHelper();
return helper.computeRSAKeyPair(helper.getSecureRandom());
}

现在我想获取字符串格式的 keyPair.publicKey,但如果我打印 keyPair.publicKey,它会显示“Instance of RSA publicKey”。我怎样才能得到它的字符串格式??

保存 public 密钥时最好使用标准化格式。对于 RSA public 密钥,您可以将它们分层存储,就像 Matroesjka 娃娃一样。

  1. 将public密钥编码为PKCS#1 RSA标准规定的ASN.1/DER格式;
  2. 以一种称为 SubjectPublicKeyInfo 的格式对 public 密钥进行编码,该格式是 X.509 规范的一部分 - 它表明这确实是一个 RSA 密钥;
  3. 应用所谓的 PEM“ASCII 盔甲”,它由指示通用 SubjectPublicKeyFormat(只是 PUBLIC KEY)的页眉和页脚行组成,以及 public 的多行 base 64 编码中间步骤 2 的密钥。

听起来工作量很大,但如果您查看 here,您会发现称为 encodePublicKeyToPemparsePublicKeyFromPem 的方便方法可以为您完成这 3 个步骤(它实际上确实1 和 2 在同一个函数中,有点遗憾但并不重要。

这些密钥非常便于携带,也可以被其他人使用。 OpenSSL 或 PGP。