rsaPrivateKeyToPem static method

String rsaPrivateKeyToPem(
  1. RSAPrivateKey privateKey, {
  2. BigInt? publicExponent,
})

Encodes an RSA private key (PKCS#1) to PEM.

If publicExponent is not provided, 65537 is used.

Implementation

static String rsaPrivateKeyToPem(
  RSAPrivateKey privateKey, {
  BigInt? publicExponent,
}) {
  final BigInt? n = privateKey.n;
  final BigInt? d = privateKey.privateExponent;
  final BigInt? p = privateKey.p;
  final BigInt? q = privateKey.q;

  if (n == null || d == null || p == null || q == null) {
    throw ArgumentError(
      'RSAPrivateKey missing CRT parameters (n, d, p, q).',
    );
  }

  final BigInt e = publicExponent ?? BigInt.from(65537);
  final BigInt dp = d % (p - BigInt.one);
  final BigInt dq = d % (q - BigInt.one);
  final BigInt qInv = q.modInverse(p);

  final ASN1Sequence seq = ASN1Sequence();
  seq.add(ASN1Integer(BigInt.zero)); // version
  seq.add(ASN1Integer(n));
  seq.add(ASN1Integer(e));
  seq.add(ASN1Integer(d));
  seq.add(ASN1Integer(p));
  seq.add(ASN1Integer(q));
  seq.add(ASN1Integer(dp));
  seq.add(ASN1Integer(dq));
  seq.add(ASN1Integer(qInv));

  return _wrapPem('RSA PRIVATE KEY', seq.encodedBytes);
}