public static byte[] DecodeOpenSSLPrivateKey([NotNull]string instr)
{
if (instr == null)
{
throw new ArgumentNullException("instr");
}
const string pemprivheader = "-----BEGIN RSA PRIVATE KEY-----";
const string pemprivfooter = "-----END RSA PRIVATE KEY-----";
string pemstr = instr.Trim();
if (!pemstr.StartsWith(pemprivheader) || !pemstr.EndsWith(pemprivfooter))
return null;
var sb = new StringBuilder(pemstr);
sb.Replace(pemprivheader, ""); //remove headers/footers, if present
sb.Replace(pemprivfooter, "");
string pvkstr = sb.ToString().Trim(); //get string after removing leading/trailing whitespace
try
{
// if there are no PEM encryption info lines, this is an UNencrypted PEM private key
return Convert.FromBase64String(pvkstr);
}
catch (FormatException e)
{ //if can't b64 decode, it must be an encrypted private key
throw new FormatException("Not an unencrypted OpenSSL PEM private key", e);
}
}
}