Skip to content

Instantly share code, notes, and snippets.

@xmesaj2
Forked from TimHess/CertHelpers.cs
Created December 26, 2019 11:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xmesaj2/78d9306e6460e2e2e7cf397c57b8bcfd to your computer and use it in GitHub Desktop.
Save xmesaj2/78d9306e6460e2e2e7cf397c57b8bcfd to your computer and use it in GitHub Desktop.
Postgres Client Certs
using Microsoft.Extensions.Configuration;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Security;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Text;
namespace PostgreEFCore
{
public class PostgresCertHelpers
{
private IConfiguration Configuration { get; }
public PostgresCertHelpers(IConfiguration config)
{
Configuration = config;
}
public void ProvideClientCertificate(X509CertificateCollection clientCerts)
{
var certBytes = Encoding.ASCII.GetBytes(Configuration.GetValue<string>("vcap:services:google-cloudsql-postgres:0:credentials:ClientCert"));
var keyBytes = Encoding.ASCII.GetBytes(Configuration.GetValue<string>("vcap:services:google-cloudsql-postgres:0:credentials:ClientKey"));
var cert = GetX509FromBytes(certBytes, keyBytes);
clientCerts.Add(cert);
}
public static X509Certificate2 GetX509FromBytes(byte[] clientCertificate, byte[] clientKey)
{
var cert = new X509Certificate2(clientCertificate);
object obj;
using (var reader = new StreamReader(new MemoryStream(clientKey)))
{
obj = new PemReader(reader).ReadObject();
if (obj is AsymmetricCipherKeyPair cipherKey)
{
obj = cipherKey.Private;
}
}
var rsaKeyParams = (RsaPrivateCrtKeyParameters)obj;
var rsa = DotNetUtilities.ToRSA(rsaKeyParams);
cert = RSACertificateExtensions.CopyWithPrivateKey(cert, rsa);
// Following is work around for https://github.com/dotnet/corefx/issues/24454
var buffer = cert.Export(X509ContentType.Pfx, (string)null);
return new X509Certificate2(buffer, (string)null);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment