Flutter - How to generate a private/public key pair to encrypt messages
There is a Dart2 and Flutter compatible pre-release of Pointycastle available.
The default README.md points to the first non-pre-release version and therefore the frontpage shows "DART 2 INCOMPATIBLE", but that only applies to version < 0.11.1
.
Just add to pubspec.yaml
dependencies:
pointycastle: ^1.0.0-rc4
For examples check the unit tests https://github.com/PointyCastle/pointycastle/blob/master/test/key_generators/rsa_key_generator_test.dart
I started using some sample code for generating public key / private key pair using pointy castles. After a long time of debugging and editing code, I ended up with the following code:
var keyParams = new RSAKeyGeneratorParameters(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();
print(new RsaKeyHelper().encodePublicKeyToPem(keyPair.publicKey) );
print(new RsaKeyHelper().encodePrivateKeyToPem(keyPair.privateKey) );
AsymmetricKeyParameter<RSAPublicKey> keyParametersPublic = new PublicKeyParameter(keyPair.publicKey);
var cipher = new RSAEngine()..init(true, keyParametersPublic);
var cipherText = cipher.process(new Uint8List.fromList("Hello World".codeUnits));
print("Encrypted: ${new String.fromCharCodes(cipherText)}");
AsymmetricKeyParameter<RSAPrivateKey> keyParametersPrivate = new PrivateKeyParameter(keyPair.privateKey);
cipher.init( false, keyParametersPrivate )
;
var decrypted = cipher.process(cipherText);
print("Decrypted: ${new String.fromCharCodes(decrypted)}");
I used this guy's edits from this git issue page (Look here for some more functions such as encoding to / decoding from PEM