Dart Requires Chilkat v11.0.0+
Dart
Generate an RSA Key and Save to Encrypted PEM
See more RSA Examples
Demonstrates how to generate an RSA key and save to an encrypted PEM file.Chilkat Dart Downloads
import 'package:chilkat/chilkat.dart';
void main() {
final rsa = CkRsa();
// Generate a 2048-bit key.
final privKey = CkPrivateKey();
try {
rsa.genKey(2048, privKey);
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
final password = 'secret';
// Saving to a relative path (from the current working directory of the process).
var path = 'rsaKeys/myTestRsaPrivate.pem';
// Encrypt the PEM using 256-bit AES encryption.
privKey.pkcs8EncryptAlg = 'aes256';
try {
privKey.savePkcs8EncryptedPemFile(password, path);
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
//
// We can also save the public key.
// There is no need to encrypt public keys.
final pubKey = CkPublicKey();
privKey.toPublicKey(pubKey);
path = 'rsaKeys/myTestRsaPublic.pem';
// Choose PKCS1 or PKCS8
// We'll choose PKCS8.
final preferPkcs1 = false;
try {
pubKey.savePemFile(preferPkcs1, path);
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
//
print('Success.');
}