2017-10-30 7 views
1

​​(https://github.com/dvsekhvalnov/jose-jwt参照)を使用してAppleの新しいトークンベースのAPNシステムで使用するJWTトークンを生成しようとしています。CryptKeyをインポートメソッドで.p8ファイルから作成しようとしました。「エンコードまたはデコード操作中にエラーが発生しました。」というエラーが発生しました。

JWTエンコード方式では、secretKeyが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); 

しかし、最後の行に、次のエラーがスローされます。 はここCngKeyオブジェクトにアップルから.p8ファイルを変換する私のコードです。

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: 

(私はブロブの種類を変更したときに表示される)そのため、別のエラーがありますように、入力が間違った形式ではありません。

このコードは.NET WebApi v4.6で実行されています。

私は高低を検索しましたが、このエラーの意味を解読できませんでした。どんな助けでも大歓迎です。ありがとうございました。

答えて

1

何らかの理由で、使用していた.p8ファイルの途中に改行があります。可能であれば、メモ帳はそれを追加しました(そして保存しましたか?)。私は秘密鍵を得るために改行で分割していたので、鍵を切り捨てていました。改行を削除すると、うまくいきました。

error occurred during encode or decode operationエラーが発生した場合は、.p8(または他の)秘密鍵が不正な形式で正しい長さであるかどうかを確認してください。

0

私は同じ問題を抱えました。私はこれを使用します:

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

次に、アップルからダウンロードしたトークンファイルを分析します。ファイルに\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]); 
} 
関連する問題