signing a key with ES256 (ECDSA with P-256 curve and SHA256) on .Net Framework

Hi folks I have a private key in the PKCS#8 format and I need to sign a JWT with it using ES256, which I feel like should be an easy thing to do, but I'm hitting all sorts of problems. This is the only solution I got working in .Net Framework:

byte[] keyBytes = Convert.FromBase64String(pkcs8);
using (var ecdsa = new ECDsaCng(CngKey.Import(keyBytes, CngKeyBlobFormat.Pkcs8PrivateBlob)))
{
     byte[] signedData = ecdsa.SignData(data, HashAlgorithmName.SHA256);
     return signedData;
}

But it fails with "The system cannot find the file specified" (stack trace below) when running on IIS because IIS has the "Load user profile" option set to "false" by default, which I heard is the right thing to do from a security perspective. Is it even possible to sign data with ES256 without loading the user profile on IIS?

I tried: CngKey.Import(keyBytes, CngKeyBlobFormat.Pkcs8PrivateBlob) but it doesn't work on IIS.

ecdsa.ImportPkcs8PrivateKey(keyBytes, out _); but it is not available on .net framework.

stack trace:

System.Security.Cryptography.CngKey.Import(keyBytes, System.Security.Cryptography.CngKeyBlobFormat.Pkcs8PrivateBlob)' threw an exception of type 'System.Security.Cryptography.CryptographicException'
    Data: {System.Collections.ListDictionaryInternal}
    HResult: -2147024894
    HelpLink: null
    InnerException: null
    Message: "The system cannot find the file specified.\r\n"
    Source: "System.Core"
    StackTrace: "   at System.Security.Cryptography.NCryptNative.ImportKey(SafeNCryptProviderHandle provider, Byte[] keyBlob, String format)\r\n   at System.Security.Cryptography.CngKey.Import(Byte[] keyBlob, String curveName, CngKeyBlobFormat format, CngProvider provider)\r\n   at System.Security.Cryptography.CngKey.Import(Byte[] keyBlob, CngKeyBlobFormat format)"
    TargetSite: {Microsoft.Win32.SafeHandles.SafeNCryptKeyHandle ImportKey(Microsoft.Win32.SafeHandles.SafeNCryptProviderHandle, Byte[], System.String)}

Upvotes: 0

Views: 89

Answers (0)

Related Questions