导入 ECC 密钥 - CngKey.Import() - 参数不正确

Import ECC key - CngKey.Import() - Parameter is incorrect

目的:使用jose-jwt[=生成一个ES256签名的JWT 14=]

步骤:

1.Generate 私钥证书 使用 openssl:

openssl ecparam -name prime256v1 -genkey > privateKey.pem
openssl req -new -key privateKey.pem -x509 -nodes -days 365 -out public.cer

2.Token世代:

var payload = new Dictionary<string, object>()
{
   { "sub", "mr.x@contoso.com" },
   { "exp", 1300819380   }
};
var certificate = X509Certificate.CreateFromCertFile("public.cer");
byte[] publicKey = certificate.GetPublicKey(); //public key has 65 bytes

//Below step is throwing an error:
var cng = CngKey.Import(publicKey, CngKeyBlobFormat.EccPublicBlob);
var token = JWT.Encode(claims, cng, JwsAlgorithm.ES256);

CngKey.Import() 在尝试生成 [=24= 时抛出“参数不正确”错误Jose.JWT.Encode 函数需要 ]CngKey。不确定我缺少哪一步。谢谢

"ECCPUBLICBLOB" 格式与证书中的 "public key" 字段不同。

ECCPUBLICBLOB 的格式在 中有解释,但这里有一个简短的总结:

UINT32 Magic
UINT32 cbKey
<cbKey bytes of public key>

Magic 的值将取决于您尝试导入的曲线和算法(https://referencesource.microsoft.com/#system.core/System/Security/Cryptography/BCryptNative.cs,fde0749a0a5f70d8,references 中的一些提示)。

cbKey 是 public 键中的字节数。

public 密钥字节与您从 GetPublicKey() 获得的略有不同。它只是曲线 X 坐标,它将是(对于 NIST P-256)字节 1..33(GetPublicKey() 的第一个字节将是 0x04,表示有效负载未压缩,然后是 32 字节X 坐标,然后是 Y 坐标的 32 个字节)。

IEnumerable<byte> blobBytes = BitConverter.GetBytes(0x31534345);
blobBytes = blobBytes.Append(BitConverter.GetBytes(32));
blobBytes = blobBytes.Append(cert.GetPublicKey().Skip(1).Take(32));

byte[] eccblob = blobBytes.ToArray();

System.Linq 用于简洁的扩展方法。

不过,如果您只需要一个对象实例,cert.GetECDsaPublicKey() 应该为您做正确的事情(每次调用 returns 一个新实例,因此适当地管理生命周期)

following post.

的帮助下,我能够导入 CngKey

现在 Jose.JWT.Encode() 在以下行抛出 "Unable to sign" 错误:

return JWT.Encode(claims, cng, JwsAlgorithm.ES256)

我最终使用 .NET 4.6 GetECDsaPrivateKey() 编写了自己的私钥签名实现。

你可以在following post

上看到我的最终解决方案

Public 密钥需要通过 丢弃第一个字节 ,留下 64 个字节,然后为曲线 4 个字节作为前缀 [=35] =] 和 4 个字节的密钥长度 。这是完整的解决方案:

var payload = new Dictionary<string, object>()
{
   { "sub", "mr.x@contoso.com" },
   { "exp", 1300819380     }
};
var certificate = X509Certificate.CreateFromCertFile("public.cer");
byte[] publicKey = certificate.GetPublicKey(); //public key has 65 bytes

//Discard the first byte (it is always 0X04 for ECDSA public key)
publicKey = publicKey.Skip(1).ToArray();:

//Generate 4 bytes for curve and 4 bytes for key length [ 69(E), 67(C), 83(S), 49(1), 32(Key length), 0, 0, 0 ]
byte[] x = { 69, 67, 83, 49, 32, 0, 0, 0 };    

//Prefix above generated array to existing public key array
publicKey = x.Concat(publicKey).ToArray();

var cng = CngKey.Import(publicKey, CngKeyBlobFormat.EccPublicBlob); //This works
return JWT.Encode(claims, cng, JwsAlgorithm.ES256); //Fixed, see my final solution link above