0

I'm using self signed certificate ECDH_secP384r1 for signing token. Here is the PowerShell that I create the certificate:

$Cert = New-SelfSignedCertificate -certstorelocation cert:\localmachine\my -dnsname $Certname -NotAfter $ExpireDate -KeyAlgorithm ECDH_secP384r1

Now in my .net core application first I load the certificate:

private readonly string _certificateSubjectName;

public X509Certificate2 GetSigningCertificate()
{

    using (var store = new X509Store(StoreLocation.LocalMachine))
    {
        store.Open(OpenFlags.ReadOnly);
        var certificates = store.Certificates.Find(X509FindType.FindBySubjectName, _certificateSubjectName, false);
        return certificates[0];

    }
}

And also I can Get the ECDsa private key like

ECDsa privateKey = signingCertificate.GetECDsaPrivateKey();
ECDsa publicKey = signingCertificate.GetECDsaPublicKey()

But how could I have byte array of these keys?

For Rsa I could use:

public byte[] GetPrivateKey(X509Certificate2 certificate)
{
    RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)certificate.PrivateKey;

    MemoryStream memoryStream = new MemoryStream();
    TextWriter streamWriter = new StreamWriter(memoryStream);
    PemWriter pemWriter = new PemWriter(streamWriter);
    AsymmetricCipherKeyPair keyPair = DotNetUtilities.GetRsaKeyPair(rsa);
    pemWriter.WriteObject(keyPair.Private);
    streamWriter.Flush();
    byte[] byteArray = memoryStream.GetBuffer();
    return byteArray;
}

But how about ECDsa? any idea?

Saeid
  • 13,224
  • 32
  • 107
  • 173
  • I'm not sure if you ever need to export keys (in fact it is a bad practice) and load somewhere else. Especially, when you don't need the raw key material. You should pass an instance of `X509Certificate2` to signing credentials and never touch keys. – Crypt32 Apr 03 '20 at 17:03
  • BTW, example of getting RSA private key is bad, Since .NET 4.6 (or so), direct access to `X509Certificate2.PrivateKey` is strictly discouraged because you can (an most likely) get `InvalidCastException`, because after .NET 4.7 (and in .NET Core) the `RSACryptoServiceProvider ` is replaced with `RSACng` on Windows. Don't use such code anymore. – Crypt32 Apr 03 '20 at 17:09
  • @Crypt32 I need get Byte array of keys for Test purposes – Saeid Apr 03 '20 at 17:45
  • I believe, that this question is related to this thread: https://stackoverflow.com/questions/60994403/signing-token-with-ecc-encryption-certificate and for that particular purpose you don't need to access raw keys. Simply use `new SigningCredentials(new X509AsymmetricSecurityKey(cert), SecurityAlgorithms.EcdsaSha384)`. – Crypt32 Apr 03 '20 at 18:06

0 Answers0