encodePrivateKeyToPemPKCS1 method

String encodePrivateKeyToPemPKCS1()

Implementation

String encodePrivateKeyToPemPKCS1() {
  final topLevel = ASN1Sequence();

  final version = ASN1Integer.fromInt(0);
  final modulus = ASN1Integer(privateKey.n!);
  final publicExponent = ASN1Integer(privateKey.exponent!);
  final privateExponent = ASN1Integer(privateKey.privateExponent!);
  final p = ASN1Integer(privateKey.p!);
  final q = ASN1Integer(privateKey.q!);
  final dP = privateKey.privateExponent! % (privateKey.p! - BigInt.from(1));
  final exp1 = ASN1Integer(dP);
  final dQ = privateKey.privateExponent! % (privateKey.q! - BigInt.from(1));
  final exp2 = ASN1Integer(dQ);
  final iQ = privateKey.q!.modInverse(privateKey.p!);
  final co = ASN1Integer(iQ);

  topLevel.add(version);
  topLevel.add(modulus);
  topLevel.add(publicExponent);
  topLevel.add(privateExponent);
  topLevel.add(p);
  topLevel.add(q);
  topLevel.add(exp1);
  topLevel.add(exp2);
  topLevel.add(co);

  final dataBase64 = base64Encode(topLevel.encodedBytes);

  return '-----BEGIN RSA PRIVATE KEY-----\n$dataBase64\n-----END RSA PRIVATE KEY-----';
}