-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)}"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What if my public key is a dot cer file? How to encrypt?
java
public 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); } }