从KeyPair Generation Flutter获取RSA公钥或私钥

问题描述 投票:0回答:1

我添加了pointycastle并生成了一个密钥对,加密了试用版“Hello World”字符串。从这里,我想获得私钥和公钥的值。它是否存储在任何地方,因为每当我尝试打印keyPair.privateKey的值时,它都会返回Instance of 'RSAPrivateKey

这是我使用的代码

        var keyParams = new RSAKeyGeneratorParameters(new BigInt.from(65537), 2048, 5);
        var secureRandom = new FortunaRandom();
        var random = new Random.secure();
        List<int> seeds = [];
        for (int i = 0; i < 32; i++) {
          seeds.add(random.nextInt(255));
        }
        secureRandom.seed(new KeyParameter(new Uint8List.fromList(seeds)));

        var rngParams = new ParametersWithRandom(keyParams, secureRandom);
        var k = new RSAKeyGenerator();
        k.init(rngParams);
        var keyPair = k.generateKeyPair();
        var cipher = new RSAEngine()..init( true, new PublicKeyParameter<RSAPublicKey>(keyPair.publicKey));
        print("pubkey: ${keyPair.publicKey.toString()}");
        var cipherText = cipher.process(new Uint8List.fromList("Hello World".codeUnits));
        print("Encrypted: ${new String.fromCharCodes(cipherText)}");
        cipher.init( false, new PrivateKeyParameter<RSAPrivateKey>(keyPair.privateKey));
        //cipher.init( false, new PrivateKeyParameter(keyPair.privateKey) )
        var decrypted = cipher.process(cipherText);
        print("Decrypted: ${new String.fromCharCodes(decrypted)}");
dart flutter public-key-encryption pointycastle
1个回答
0
投票

确保导入package:pointycastle/asymmetric/api.dart,然后使用:

  var k = RSAKeyGenerator()..init(rngParams);
  AsymmetricKeyPair<PublicKey, PrivateKey> keyPair = k.generateKeyPair();
  RSAPrivateKey privateKey = keyPair.privateKey;
  RSAPublicKey publicKey = keyPair.publicKey;
  print(privateKey.d); // prints private exponent
  print(publicKey.n); // prints modulus

从各个部分重新创建:

  RSAPrivateKey foo = RSAPrivateKey(
    privateKey.n,
    privateKey.d,
    privateKey.p,
    privateKey.q,
  );
  RSAPublicKey bar = RSAPublicKey(publicKey.n, publicKey.e);
© www.soinside.com 2019 - 2024. All rights reserved.