Skip to content

Instantly share code, notes, and snippets.

@ziizii
Last active August 13, 2018 08:33
Show Gist options
  • Save ziizii/aa2ce6ba63ac043b62f199892a516719 to your computer and use it in GitHub Desktop.
Save ziizii/aa2ce6ba63ac043b62f199892a516719 to your computer and use it in GitHub Desktop.
How to generate RSA private/public key pair in Dart with Pointy Castle
import 'dart:html';
import 'dart:math';
import 'dart:typed_data';
import "package:bignum/bignum.dart";
import "package:pointycastle/export.dart";
void main() {
var keyParams = new RSAKeyGeneratorParameters(new BigInteger("65537"), 2048, 5);
var secureRandom = new FortunaRandom();
var random = new Random.secure();
var 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(keyPair.publicKey) )
;
var cipherText = cipher.process(new Uint8List.fromList("Hello World".codeUnits));
print("Encrypted: ${new String.fromCharCodes(cipherText)}");
cipher.init( false, new PrivateKeyParameter(keyPair.privateKey) )
;
var decrypted = cipher.process(cipherText);
print("Decrypted: ${new String.fromCharCodes(decrypted)}");
}
@JuliusNM
Copy link

JuliusNM commented Jul 19, 2018

Hi! thanks for providing this. Have you tested it? It seems to break between line 23 and 28.

@caocongcong
Copy link

NoSuchMethodError: No static getter 'keyPair' declared in class

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment