Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Trying to create a CngKey from a .p8 file with import method, throwing error "An error occurred during encode or decode operation."

Tags:

c#

jwt

cng

I'm trying to generate a JWT token using Jose.JWT.encode(payload, secretKey, JwsAlgorithm.ES256, header) (see https://github.com/dvsekhvalnov/jose-jwt) to use with Apple's new token-based APNs system.

The JWT encode method requires the secretKey to be in CngKey format. Here's my code converting the .p8 file from Apple to a CngKey object:

        var privateKeyContent = System.IO.File.ReadAllText(authKeyPath);
        var privateKey = privateKeyContent.Split('\n')[1];

        //convert the private key to CngKey object and generate JWT

        var secretKeyFile = Convert.FromBase64String(privateKey);
        var secretKey = CngKey.Import(secretKeyFile, CngKeyBlobFormat.Pkcs8PrivateBlob);

However, on the last line, the following error is thrown.

System.Security.Cryptography.CryptographicException was unhandled by user code
  HResult=-2146885630
  Message=An error occurred during encode or decode operation.

  Source=System.Core
  StackTrace:
       at System.Security.Cryptography.NCryptNative.ImportKey(SafeNCryptProviderHandle provider, Byte[] keyBlob, String format)
       at System.Security.Cryptography.CngKey.Import(Byte[] keyBlob, String curveName, CngKeyBlobFormat format, CngProvider provider)
       at System.Security.Cryptography.CngKey.Import(Byte[] keyBlob, CngKeyBlobFormat format)
       at tokenauthapi.App_Start.TokenInitSendMessage.<send>d__0.MoveNext() in C:\token-push-prototype\token-auth-api\token-auth-api\App_Start\TokenInitSendMessage.cs:line 31
  InnerException: 

The input isn't in the wrong format as there's a separate error for that (that appears when I change the blob type).

This code is running in a .NET WebApi v4.6.

I've searched high and low but haven't been able to decipher what this error is referring to. Any help would be greatly appreciated. Thank you.

like image 419
Helen Avatar asked Nov 14 '25 20:11

Helen


1 Answers

The security key (p8) provided by Apple for DeviceCheck also contained newlines. I used the following to get a valid CngKey:

var privateKeyContent = File.ReadAllText("pathToApplePrivateKey.p8");
var privateKeyList = privateKeyContent.Split('\n').ToList();
var privateKey = privateKeyList.Where((s, i) => i != 0 && i != privateKeyList.Count - 1)
                                   .Aggregate((agg, s) => agg + s);

CngKey key = CngKey.Import(Convert.FromBase64String(privateKey), CngKeyBlobFormat.Pkcs8PrivateBlob);
like image 53
Scott Wood Avatar answered Nov 17 '25 10:11

Scott Wood



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!