rsaPrivateKeyToString function

String rsaPrivateKeyToString(
  1. RSAPrivateKey privateKey
)

Implementation

String rsaPrivateKeyToString(RSAPrivateKey privateKey) {
  final version = ASN1Integer(BigInt.from(0));

  final algorithmSeq = ASN1Sequence();
  final algorithmAsn1Obj = ASN1Object.fromBytes(Uint8List.fromList(
      [0x6, 0x9, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0xd, 0x1, 0x1, 0x1]));
  final paramsAsn1Obj = ASN1Object.fromBytes(Uint8List.fromList([0x5, 0x0]));
  algorithmSeq.add(algorithmAsn1Obj);
  algorithmSeq.add(paramsAsn1Obj);

  final privateKeySeq = ASN1Sequence();
  final modulus = ASN1Integer(privateKey.n);
  final publicExponent = ASN1Integer(BigInt.parse('65537'));
  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);

  privateKeySeq.add(version);
  privateKeySeq.add(modulus);
  privateKeySeq.add(publicExponent);
  privateKeySeq.add(privateExponent);
  privateKeySeq.add(p);
  privateKeySeq.add(q);
  privateKeySeq.add(exp1);
  privateKeySeq.add(exp2);
  privateKeySeq.add(co);
  final publicKeySeqOctetString =
  ASN1OctetString(Uint8List.fromList(privateKeySeq.encodedBytes));

  final topLevelSeq = ASN1Sequence();
  topLevelSeq.add(version);
  topLevelSeq.add(algorithmSeq);
  topLevelSeq.add(publicKeySeqOctetString);
  return base64.encode(topLevelSeq.encodedBytes);
}