Skip to content

Instantly share code, notes, and snippets.

@TimHess
Created December 24, 2019 18:50
Show Gist options
  • Save TimHess/2ce0856d507a3528d66fce1c402b16b4 to your computer and use it in GitHub Desktop.
Save TimHess/2ce0856d507a3528d66fce1c402b16b4 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