Sample code for 30+ languages & platforms
Dart

Get Public Key from CSR

See more CSR Examples

Demonstrates how to get the public key from a CSR.

Chilkat Dart Downloads

Dart
import 'package:chilkat/chilkat.dart';

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

  final pem = CkPem();

  // No password is required.  Pass an empty password string..
  final noPassword = '';
  try {
    pem.loadPemFile('qa_data/csr/csr2.pem', noPassword);
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

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

  final asn = CkAsn();
  try {
    asn.loadEncoded(strBase64, 'base64');
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  // Convert the ASN.1 to XML.
  final xml = CkXml();
  xml.loadXml(asn.asnToXml());
  print(xml.getXml());
  print('----');

  final strModulusHex = xml.getChildContent('bits');
  print('strModulusHex = $strModulusHex');
  print('----');

  // We need the modulus as base64.
  final bd = CkBinData();
  bd.appendEncoded(strModulusHex, 'hex');
  final modulus64 = bd.getEncoded('base64');
  print('modulus64 = $modulus64');
  print('----');

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

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

  // Load the XML into a Chilkat public key object.
  final pubkey = CkPublicKey();
  try {
    pubkey.loadFromString(xmlPubKey.getXml());
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  // Show the public key as PEM.
  final preferPkcs1 = true;
  print(pubkey.getPem(preferPkcs1));
}