System.Security.Cryptography.CryptographicException:不支持请求的操作。 Windows Server 2012

时间:2017-12-31 12:31:28

标签: c# encryption cryptography public-key-encryption cng

我厌倦了为调用apns生成jwt令牌。这是我的代码:

    var header = new Dictionary<string, object>()
    {
        { "kid" , keyID }
    };
    var payload = new Dictionary<string, object>()
    {
        { "iss", teamID },
        { "iat", DateTimeOffset.Now.ToUnixTimeSeconds().ToString() }
    };

    var privateKey = GetApnsPrivateKey(authKeyPath);
    var token = JWT.Encode(payload, privateKey, JwsAlgorithm.ES256, header);
public static CngKey GetApnsPrivateKey(string authKeyPath)
{
    using (var reader = new StreamReader(new FileStream(authKeyPath, FileMode.Open, FileAccess.Read, FileShare.Read)))
    {
        var ecPrivateKeyParameters = (ECPrivateKeyParameters)new PemReader(reader).ReadObject();
        var x = ecPrivateKeyParameters.Parameters.G.AffineXCoord.GetEncoded();
        var y = ecPrivateKeyParameters.Parameters.G.AffineYCoord.GetEncoded();
        var d = ecPrivateKeyParameters.D.ToByteArrayUnsigned();
        return EccKey.New(x, y, d);

代码在我的机器上工作正常但在服务器中它会在GetApnsPrivateKey方法上抛出此异常:

System.Security.Cryptography.CryptographicException: The requested operation is not supported

在论坛上进行少量搜索之后,我发现它是因为CNG密钥存储提供商:https://msdn.microsoft.com/en-us/library/windows/desktop/aa376242.aspx?f=255&MSPPError=-2147217396 现在我想知道有什么方法可以解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

异常的来源是jose-jwt中的System.Security.Cryptography库,所以请避免使用它。 由于BouncyCastle库已在此处使用,因此请将其用于签名。 另外,我使用Newtonsoft.Json.JsonConvert(..)。

public string GetApnsToken(string authKeyPath,  
Dictionary<string, object> payload, 
Dictionary<string, object> header)
{
    ECPrivateKeyParameters ecPrivateKeyParameters;
    using (var reader = new StreamReader(new FileStream(authKeyPath, FileMode.Open, FileAccess.Read, FileShare.Read)))
    {
       ecPrivateKeyParameters = (ECPrivateKeyParameters)new PemReader(reader).ReadObject();
     }
     byte[] headerBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(header));
     byte[] payloadBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(payload));
     byte[] bytesToSign = Encoding.UTF8.GetBytes(ConcatTokenPartsWithEncoding(headerBytes, payloadBytes));

   var signer = new DsaDigestSigner(new ECDsaSigner(), new Sha256Digest());
   signer.Init(true, ecPrivateKeyParameters);
   signer.BlockUpdate(bytesToSign, 0, bytesToSign.Length);
   byte[] signBytes = signer.GenerateSignature();

   return ConcatTokenPartsWithEncoding(headerBytes, payloadBytes, signBytes);

}

public static string ConcatTokenPartsWithEncoding(params byte[][] parts)
{
var builder = new StringBuilder();
foreach (var part in parts)
{
 //encode base64 for Url
 var base64Str = Convert.ToBase64String(part);
 base64Str = base64Str.Split('=')[0]; // Remove any trailing '='s
 base64Str = base64Str.Replace('+', '-'); 
 base64Str = base64Str.Replace('/', '_');
 builder.Append(base64Str).Append(".");
}
builder.Remove(builder.Length - 1, 1); 
return builder.ToString();
}

答案 1 :(得分:0)

感谢Natalya的帖子。我可以解决这个问题:

        var dateTime = DateTimeOffset.Now;
        var privateKeyAsBytes = Convert.FromBase64String(authKey);
        var privateKey = CngKey.Import(privateKeyAsBytes, CngKeyBlobFormat.Pkcs8PrivateBlob);
        var header = new Dictionary<string, object>() { { "kid", keyID } };
        var payload = new Dictionary<string, object>() { { "iss", teamID }, { "iat", dateTime.ToUnixTimeSeconds().ToString() } };
        var token = JWT.Encode(payload, privateKey, JwsAlgorithm.ES256, header);