3

我正在尝试使用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);

但是,在最后一行,会引发以下错误。

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: 

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

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

我已经搜索了高和低,但无法破译此错误所指的内容。任何帮助将不胜感激。谢谢你。

4

3 回答 3

4

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);
于 2018-08-14T17:57:50.800 回答
2

原来我使用的 .p8 文件由于某种原因中间有换行符。记事本可能添加了它(并保存了它?)。我正在用换行符拆分以获取私钥,因此它正在截断密钥。一旦我删除了换行符,它就可以正常工作。

如果您收到error occurred during encode or decode operation错误,请检查您的 .p8(或其他)私钥是否格式错误且长度正确。

于 2017-10-31T19:55:23.070 回答
1

我遇到了同样的问题。我用这个:

var privateKey = privateKeyContent.Split('\n')[1];

然后我分析从 Apple 下载的令牌文件。我发现文件中有更多\n内容。我不确定这种格式在哪里不同或苹果改变了。然后我使用以下代码加载令牌,工作。实际上,我们可以直接使用这个令牌字符串。

var privateKeyContent = System.IO.File.ReadAllText(authKeyPath);
var privateKeyList = privateKeyContent.Split('\n');
int upperIndex = privateKeyList.Length;
StringBuilder sb = new StringBuilder();
for(int i= 1; i< upperIndex - 1; i++ )
{
    sb.Append(privateKeyList[i]);
    Debug.WriteLine(privateKeyList[i]);
}
于 2018-02-17T19:51:53.117 回答