我正在使用自签名证书ECDH_secP384r1
来签署令牌。这是我创建证书的 PowerShell:
$Cert = New-SelfSignedCertificate -certstorelocation cert:\localmachine\my -dnsname $Certname -NotAfter $ExpireDate -KeyAlgorithm ECDH_secP384r1
现在在我的 .net 核心应用程序中,我首先加载证书:
private readonly string _certificateSubjectName;
public X509Certificate2 GetSigningCertificate()
{
using (var store = new X509Store(StoreLocation.LocalMachine))
{
store.Open(OpenFlags.ReadOnly);
var certificates = store.Certificates.Find(X509FindType.FindBySubjectName, _certificateSubjectName, false);
return certificates[0];
}
}
现在通过获得证书,我在创建 SigningCredentials 时出错:我试图按照这种方式
public string GetSignedToken(IEnumerable<Claim> claims)
{
var signingCertificate = GetSigningCertificate();
byte[] certBytes = signingCertificate.Export(X509ContentType.Pkcs12);
var privateECDsa = LoadPrivateKey(certBytes);
var signingCredentials = new SigningCredentials(new ECDsaSecurityKey(privateECDsa), SecurityAlgorithms.EcdsaSha384);
var token = new JwtSecurityToken(
issuer: _issuer,
audience: _audience,
claims: claims,
expires: DateTime.Now.AddMinutes(_expiryMinutes),
signingCredentials: signingCredentials);
var securityTokenHandler = new JwtSecurityTokenHandler();
var rawJwtToken = securityTokenHandler.WriteToken(token);
return rawJwtToken ;
}
private static ECDsa LoadPrivateKey(byte[] key)
{
var privKeyInt = new Org.BouncyCastle.Math.BigInteger(+1, key);
var parameters = SecNamedCurves.GetByName("secP384r1");
var ecPoint = parameters.G.Multiply(privKeyInt);
var privKeyX = ecPoint.Normalize().XCoord.ToBigInteger().ToByteArrayUnsigned();
var privKeyY = ecPoint.Normalize().YCoord.ToBigInteger().ToByteArrayUnsigned();
var curve = ECCurve.NamedCurves.nistP384;
var d = privKeyInt.ToByteArrayUnsigned();
var q = new ECPoint
{
X = privKeyX,
Y = privKeyY
};
var eCParameters = new ECParameters
{
Curve = curve,
D = d,
Q = q
};
var eCDsa = ECDsa.Create(eCParameters); //In this line I got an exception
return eCDsa;
}
但是我在 ECDsa.Create 中遇到了一个异常:
The specified key parameters are not valid. Q.X and Q.Y are required fields. Q.X, Q.Y must be the same length. If D is specified it must be the same length as Q.X and Q.Y for named curves or the same length as Order for explicit curves.
更新:
我也尝试过这种方式来修复尺寸:
var d = FixSize(privKeyInt.ToByteArrayUnsigned(), privKeyX.Length);
但在这种情况下 input[0] != 0
我有一个例外,我input[0]
不是 0 也是input.Length
1250 并且预期大小是 48
我错过了什么?请有任何想法。