Skip to content

Instantly share code, notes, and snippets.

@ulve
Last active January 7, 2019 10:34
Show Gist options
  • Save ulve/7e6c365937363638f5bd6afb43152556 to your computer and use it in GitHub Desktop.
Save ulve/7e6c365937363638f5bd6afb43152556 to your computer and use it in GitHub Desktop.
X509Certificate2 private key to PEM
public static string ExportPrivateKey(X509Certificate2 certificateWithPrivateKey)
{
var parameterList = RsaParametersToList(certificateWithPrivateKey.GetRSAPrivateKey().ExportParameters(true));
var parameterBytes = SerializeList(parameterList);
var base64 = Convert.ToBase64String(parameterBytes);
var builder = new StringBuilder();
builder.Append("-----BEGIN RSA PRIVATE KEY-----\n");
for (int i = 0; i < base64.Length; i += 64)
builder.Append($"{ base64.Substring(i, Math.Min(64, base64.Length - i)) }\n");
builder.Append("-----END RSA PRIVATE KEY-----\n");
return builder.ToString();
}
private static List<byte[]> RsaParametersToList(System.Security.Cryptography.RSAParameters parameters)
{
return new List<byte[]> {
new byte[] {0x00},
parameters.Modulus,
parameters.Exponent,
parameters.D,
parameters.P,
parameters.Q,
parameters.DP,
parameters.DQ,
parameters.InverseQ
};
}
private static byte[] SerializeList(List<byte[]> list)
{
var keyBytes = list.Select(e => Encode(e)).SelectMany(e => e).ToArray();
using (var ms = new MemoryStream())
using (var binaryWriter = new BinaryWriter(ms))
{
binaryWriter.Write((byte)0x30); // SEQUENCE
binaryWriter.Write(Encode(keyBytes, false));
binaryWriter.Flush();
return ms.ToArray();
}
}
private static byte[] Encode(byte[] inBytes, bool useTypeOctet = true)
{
var length = inBytes.Length;
var bytes = new List<byte>();
if (useTypeOctet == true)
bytes.Add(0x02); // Integer, 2 bytes
bytes.Add(0x84); // Long, 4 bytes
bytes.AddRange(BitConverter.GetBytes(length).Reverse());
bytes.AddRange(inBytes);
return bytes.ToArray();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment