Skip to content

Instantly share code, notes, and snippets.

@ChrisTowles
Last active November 28, 2023 21:05
Show Gist options
  • Save ChrisTowles/f8a5358a29aebcc23316605dd869e839 to your computer and use it in GitHub Desktop.
Save ChrisTowles/f8a5358a29aebcc23316605dd869e839 to your computer and use it in GitHub Desktop.
C# Import or Export Cert to Base64 String
public void ExportCertToBase64()
{
var certificate = new System.Security.Cryptography.X509Certificates.X509Certificate2("c:\\temp\\Signing Cert.pfx", "XXXXXXXXXXXXXX", X509KeyStorageFlags.Exportable);
StringBuilder builder = new StringBuilder();
builder.AppendLine("-----BEGIN CERTIFICATE-----");
builder.AppendLine(Convert.ToBase64String(certificate.Export(X509ContentType.Pkcs12, "XXXXXXXXXXXXXX"), Base64FormattingOptions.InsertLineBreaks));
builder.AppendLine("-----END CERTIFICATE-----");
Console.WriteLine( builder.ToString());
}
public void ImportCertFromBase64()
{
var rawSIgningCert = @"
-----BEGIN CERTIFICATE-----
MIIDLzCCAhegAwIBAgIQJAw.......
-----END CERTIFICATE-----
";
var certBytes = Encoding.UTF8.GetBytes(rawSIgningCert);
var signingcert = new System.Security.Cryptography.X509Certificates.X509Certificate2(
certBytes, "XXXXXXXXXXXXXX",
System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable);
}
@Hobray
Copy link

Hobray commented Aug 9, 2018

The only way I could get this to work was by using "Convert.FromBase64String" instead of "Encoding.UTF8.GetBytes". I also had to parse out the "-----BEGIN CERTIFICATE-----" and "-----END CERTIFICATE-----" text from the "rawSIgningCert" field because Convert.FromBase64String chokes on non-base64 characters like the hyphen otherwise. After making those changes, this solution worked great.

@ryanwilliams83
Copy link

const string certificatePem = @"
-----BEGIN CERTIFICATE-----
MIIF8DCCBVmgAwIBAgIKYFOB9QABAACIvTANBgkqhkiG9w0BAQUFADBGMQswCQYD
...
OpueYUG3NBcHP/5IzhUYIQJbGzlQaUaZBMaQeC8ZslMNLWI2
-----END CERTIFICATE-----";

var pemData = Regex.Replace(Regex.Replace(certificatePem, @"\s+", string.Empty), @"-+[^-]+-+", string.Empty);
var pemBytes = Convert.FromBase64String(pemData);
return new X509Certificate2(pemBytes);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment