Sample code for 30+ languages & platforms
React Native Requires Chilkat v11.0.0+

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 React Native Downloads

React Native
import { PrivateKey, PublicKey, Rsa } from '@chilkat/react-native'

function chilkatExample() {
  const rsa = new Rsa();

  // Generate a 2048-bit key.
  const privKey = new PrivateKey();
  try {
    rsa.genKey(2048, privKey);
  } catch {
    console.log(rsa.lastErrorText);
    return;
  }

  const password = 'secret';
  // Saving to a relative path (from the current working directory of the process).
  let path = 'rsaKeys/myTestRsaPrivate.pem';
  // Encrypt the PEM using 256-bit AES encryption.
  privKey.pkcs8EncryptAlg = 'aes256';
  try {
    privKey.savePkcs8EncryptedPemFile(password, path);
  } catch {
    console.log(privKey.lastErrorText);
    return;
  }

  // image

  // We can also save the public key.
  // There is no need to encrypt public keys.
  const pubKey = new PublicKey();
  privKey.toPublicKey(pubKey);

  path = 'rsaKeys/myTestRsaPublic.pem';
  // Choose PKCS1 or PKCS8
  // We'll choose PKCS8.
  const preferPkcs1 = false;
  try {
    pubKey.savePemFile(preferPkcs1, path);
  } catch {
    console.log(pubKey.lastErrorText);
    return;
  }

  // image

  console.log('Success.');
}