0

我正在使用自签名证书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.Length1250 并且预期大小是 48

我错过了什么?请有任何想法。

4

2 回答 2

1

好的,经过一番搜索,我找到了一个简单的解决方案,我把它作为答案放在这里:

using System.Security.Cryptography.X509Certificates;

public string GetSignedToken(IEnumerable<Claim> claims)
{
    var signingCertificate = GetSigningCertificate();
    var securityKey = new ECDsaSecurityKey(signingCertificate.GetECDsaPrivateKey());
    var signingCredentials = new SigningCredentials(securityKey, 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;
}

并进行验证:

using System.Security.Cryptography.X509Certificates;

public TokenValidationParameters GetTokenValidationParameters()
{
    var signingCertificate = GetSigningCertificate();
    var securityKey = new ECDsaSecurityKey(signingCertificate.GetECDsaPublicKey());

    var validationParameters = new TokenValidationParameters()
    {
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = securityKey,
        ValidateIssuer = true,
        ValidIssuer = _issuer,
        ValidateAudience = true,
        ValidAudience = _audience
    };

    return validationParameters;
}
于 2020-04-03T13:15:51.057 回答
0

以下代码将为您提供帮助,您可以使用充气城堡库生成算法:

private static ECDsa GetEllipticCurveAlgorithm(string privateKey)
{
    var keyParams = (ECPrivateKeyParameters)PrivateKeyFactory
        .CreateKey(Convert.FromBase64String(privateKey));

    var normalizedECPoint = keyParams.Parameters.G.Multiply(keyParams.D).Normalize();

    return ECDsa.Create(new ECParameters
    {
        Curve = ECCurve.CreateFromValue(keyParams.PublicKeyParamSet.Id),
        D = keyParams.D.ToByteArrayUnsigned(),
        Q =
    {
        X = normalizedECPoint.XCoord.GetEncoded(),
        Y = normalizedECPoint.YCoord.GetEncoded()
    }
    });
}

并通过以下方式生成令牌:

var signatureAlgorithm = GetEllipticCurveAlgorithm(privateKey);

            ECDsaSecurityKey eCDsaSecurityKey = new ECDsaSecurityKey(signatureAlgorithm)
            {
                KeyId = settings.Apple.KeyId
            };

            var handler = new JwtSecurityTokenHandler();   
            var token = handler.CreateJwtSecurityToken(
                issuer: iss,
                audience: AUD,
                subject: new ClaimsIdentity(new List<Claim> { new Claim("sub", sub) }),
                expires: DateTime.UtcNow.AddMinutes(5), 
                issuedAt: DateTime.UtcNow,
                notBefore: DateTime.UtcNow,
                signingCredentials: new SigningCredentials(eCDsaSecurityKey, SecurityAlgorithms.EcdsaSha256));
于 2020-08-31T08:03:35.730 回答