[英]C# - Trying to create a CngKey from a .p8 file with import method, throwing error “An error occurred during encode or decode operation.”
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. 我正在尝试使用
Jose.JWT.encode(payload, secretKey, JwsAlgorithm.ES256, header)
(请参阅https://github.com/dvsekhvalnov/jose-jwt )生成一个JWT令牌Jose.JWT.encode(payload, secretKey, JwsAlgorithm.ES256, header)
以与Apple的基于令牌的新令牌一起使用APNs系统。
The JWT encode method requires the secretKey to be in CngKey
format. JWT编码方法要求
CngKey
格式。 Here's my code converting the .p8 file from Apple to a CngKey
object: 这是我的代码将.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);
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). 输入的格式不正确,因为有一个单独的错误(当我更改blob类型时出现)。
This code is running in a .NET WebApi v4.6. 此代码在.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.
谢谢。
Turns out the .p8 file I was using had newlines in the middle of it for some reason. 事实证明我正在使用的.p8文件因为某些原因而在其中间有换行符。 Possible that notepad added it (and saved it?).
记事本可能添加了它(并保存了吗?)。 I was splitting by newlines to get the private key and therefore it was truncating the key.
我按分界线拆分获取私钥,因此它截断了密钥。 Once I removed the newlines it worked fine.
一旦我删除了换行符,它就可以了。
If you get the error occurred during encode or decode operation
error, check whether your .p8 (or other) private key is malformed and is the right length. 如果
error occurred during encode or decode operation
错误error occurred during encode or decode operation
出现错误,请检查.p8(或其他)私钥是否格式错误且长度是否合适。
The security key (p8) provided by Apple for DeviceCheck also contained newlines. Apple for DeviceCheck提供的安全密钥(p8)也包含换行符。 I used the following to get a valid CngKey:
我使用以下内容来获得有效的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);
I met the same issue. 我遇到了同样的问题。 I use this:
我用这个:
var privateKey = privateKeyContent.Split('\n')[1];
Then I analyze token file downloaded from Apple. 然后我分析从Apple下载的令牌文件。 I found there are more
\\n
in the file. 我发现文件中有更多的
\\n
。 I am not sure where this format is different or apple changed. 我不确定这种格式在哪里不同或苹果改变了。 Then I use the following codes to load the token, works.
然后我使用以下代码加载令牌,工作。 Actually, we can directly use this token string.
实际上,我们可以直接使用这个令牌字符串。
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]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.