-
-
Save xmesaj2/78d9306e6460e2e2e7cf397c57b8bcfd to your computer and use it in GitHub Desktop.
Postgres Client Certs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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