Sample code for 30+ languages & platforms
React Native

Get Public Key from CSR

See more CSR Examples

Demonstrates how to get the public key from a CSR.

Chilkat React Native Downloads

React Native
import { Asn, BinData, Pem, PublicKey, Xml } from '@chilkat/react-native'

function chilkatExample() {
  // This requires the Chilkat API to have been previously unlocked.
  // See Global Unlock Sample for sample code.

  const pem = new Pem();

  // No password is required.  Pass an empty password string..
  const noPassword = '';
  try {
    pem.loadPemFile('qa_data/csr/csr2.pem', noPassword);
  } catch {
    console.log(pem.lastErrorText);
    return;
  }

  const strBase64 = pem.getEncodedItem('csr', '', 'base64', 0);

  const asn = new Asn();
  try {
    asn.loadEncoded(strBase64, 'base64');
  } catch {
    console.log(asn.lastErrorText);
    return;
  }

  // Convert the ASN.1 to XML.
  const xml = new Xml();
  xml.loadXml(asn.asnToXml());
  console.log(xml.getXml());
  console.log('----');

  const strModulusHex = xml.getChildContent('bits');
  console.log(`strModulusHex = ${strModulusHex}`);
  console.log('----');

  // We need the modulus as base64.
  const bd = new BinData();
  bd.appendEncoded(strModulusHex, 'hex');
  const modulus64 = bd.getEncoded('base64');
  console.log(`modulus64 = ${modulus64}`);
  console.log('----');

  // Build the XML for the public key.
  const xmlPubKey = new Xml();
  xmlPubKey.tag = 'RSAPublicKey';
  xmlPubKey.updateChildContent('Modulus', modulus64);
  // The RSA exponent will always be decimal 65537 (base64 = AQAB)
  xmlPubKey.updateChildContent('Exponent', 'AQAB');

  console.log('RSA public key as XML:');
  console.log(xmlPubKey.getXml());
  console.log('----');

  // Load the XML into a Chilkat public key object.
  const pubkey = new PublicKey();
  try {
    pubkey.loadFromString(xmlPubKey.getXml());
  } catch {
    console.log(pubkey.lastErrorText);
    return;
  }

  // Show the public key as PEM.
  const preferPkcs1 = true;
  console.log(pubkey.getPem(preferPkcs1));
}