dartflutterpublic-key-encryptionpointycastle

Get RSA Public or Private Key from KeyPair Generation Flutter


I have added pointycastle and generated a keypair, encrypting the trial "Hello World" string. From this, I want to get the values of the Private and Public Key. Is there anywhere they are stored, because whenever I try to print the values of keyPair.privateKey, it returns Instance of 'RSAPrivateKey.

Here is the code I used

        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)}");

Solution

  • Make sure to import package:pointycastle/asymmetric/api.dart, then use:

      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
    

    Recreate from the individual parts:

      RSAPrivateKey foo = RSAPrivateKey(
        privateKey.n,
        privateKey.d,
        privateKey.p,
        privateKey.q,
      );
      RSAPublicKey bar = RSAPublicKey(publicKey.n, publicKey.e);