C# - 尝试使用导入方法从 .p8 文件创建 CngKey,抛出错误“编码或解码操作期间发生错误”。

Hel*_*len 3 c# jwt cng

我正在尝试使用Jose.JWT.encode(payload, secretKey, JwsAlgorithm.ES256, header)(请参阅https://github.com/dvsekhvalnov/jose-jwt)生成 JWT 令牌,以与 Apple 的新的基于令牌的 APNs 系统一起使用。

JWT 编码方法要求 SecretKey 格式正确CngKey。这是我将 .p8 文件从 Apple 转换为CngKey对象的代码:

        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);
Run Code Online (Sandbox Code Playgroud)

但是,在最后一行,抛出以下错误。

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: 
Run Code Online (Sandbox Code Playgroud)

输入的格式没有错误,因为有一个单独的错误(当我更改 blob 类型时出现)。

此代码在 .NET WebApi v4.6 中运行。

我进行了高低搜索,但无法破译这个错误所指的内容。任何帮助将不胜感激。谢谢。

小智 6

Apple 为 DeviceCheck 提供的安全密钥 (p8) 也包含换行符。我使用以下方法获取有效的 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);
Run Code Online (Sandbox Code Playgroud)