我正在尝试使用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 中运行。
我已经搜索了高和低,但无法破译此错误所指的内容。任何帮助将不胜感激。谢谢你。