Skip to content

Instantly share code, notes, and snippets.

@proteye
Forked from ziizii/rsa.dart
Created July 15, 2018 14:46
Show Gist options
  • Save proteye/df73f6c555a3c9c01f685761da5b8da6 to your computer and use it in GitHub Desktop.
Save proteye/df73f6c555a3c9c01f685761da5b8da6 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)}");
}
@guoyuanzhuang
Copy link

What if my public key is a dot cer file? How to encrypt?
javapublic PublicKey getPublicKey(InputStream in) { try { try { CertificateFactory certificateFactory = CertificateFactory .getInstance("X.509"); Certificate certificate = certificateFactory.generateCertificate(in); return certificate.getPublicKey(); } finally { if (in != null) in.close(); } } catch (Exception e) { throw new RuntimeException("init exception", e); } }

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