C# - 是否可以使用RSA SHA512签名哈希?

时间:2016-05-27 12:57:17

标签: c# hash .net-4.0 sha

我使用OpenSSL创建了自签名证书,如下所示:

openssl req -x509 -sha512 -new keyrsa:2048 -keyout key2.pem -out cert2.pem -days 100

openssl pkcs12 -export -out pkcs12_cert_test2.pfx -inkey key2.pem -in cert2.pem

我在Windows上安装了pkcs12_cert_test2.pfx,证书签名算法值为sha512RSA

然后,我在C#.NET 4.0中编写了以下代码:

public static bool DSHandler(string operation, string path, string devicePath)
{
    bool result = false;
        CryptoConfig.AddAlgorithm(typeof(USBSaferAppEFB.RsaPkCs1Sha512SignatureDescription),
            "http://www.w3.org/2001/04/xmldsig-more#rsa-sha512");
        string password = "xxxx";
        bool validSignature = false;
        byte[] hashchain = generateHash(path);
        string digSignFile = Utils.RegVarValue(DIGSIGNFILE);
        string subjectDN = Utils.RegVarValue(SUBJECTDN);

        if (operation == "sign")
        {
            byte[] signature = SignFromContainer(hashchain, subjectDN);
            if (signature != null)
            {
                string signaturestring = Convert.ToBase64String(signature);

                File.WriteAllBytes(devicePath + digSignFile, signature);
                result = true;
            }
            else
                result = false;
        }
}

static byte[] SignFromContainer(byte[] hashchain, string certSubject)
{
    try
    {
        X509Store my = new X509Store(StoreName.My, StoreLocation.CurrentUser);
        my.Open(OpenFlags.ReadOnly);
        RSACryptoServiceProvider csp = null;
        foreach (X509Certificate2 cert in my.Certificates)
        {
            if (cert.Subject.Contains(certSubject))
            {
                // We found it.
                // Get its associated CSP and private key
                csp = (RSACryptoServiceProvider)cert.PrivateKey;
            }
        }

        if (csp == null)
        {
            return null;
        }

        byte[] myHash = { 59,4,248,102,77,97,142,201,
        210,12,224,93,25,41,100,197,
        210,12,224,93};

        // Sign the hash
        return csp.SignHash(hashchain, CryptoConfig.MapNameToOID("SHA-512"));
    }
    catch (Exception e)
    {
        log.Logger("Exception: "+e.Message, "debug");
        log.Logger(e.StackTrace, "debug");
        return null;
    }
}

使用一些文章和答案中的解决方案,我有RsaPkCs1Sha512SignatureDescription类,我尝试实现并注册签名描述:

public class RsaPkCs1Sha512SignatureDescription : SignatureDescription
{
    public RsaPkCs1Sha512SignatureDescription()
    {
        KeyAlgorithm = typeof(RSACryptoServiceProvider).FullName;
        DigestAlgorithm = typeof(SHA512Managed).FullName;
        FormatterAlgorithm = typeof(RSAPKCS1SignatureFormatter).FullName;
        DeformatterAlgorithm = typeof(RSAPKCS1SignatureDeformatter).FullName;
    }

    public override AsymmetricSignatureDeformatter CreateDeformatter(AsymmetricAlgorithm key)
    {
        var sigProcessor = (AsymmetricSignatureDeformatter)CryptoConfig.CreateFromName(DeformatterAlgorithm);
        sigProcessor.SetKey(key);
        sigProcessor.SetHashAlgorithm("SHA-512");
        return sigProcessor;
    }

    public override AsymmetricSignatureFormatter CreateFormatter(AsymmetricAlgorithm key)
    {
        var sigProcessor =
            (AsymmetricSignatureFormatter)CryptoConfig.CreateFromName(FormatterAlgorithm);
        sigProcessor.SetKey(key);
        sigProcessor.SetHashAlgorithm("SHA-512");
        return sigProcessor;
    }
}

我已经验证哈希长度为64个字节,并返回CryptographicException: Bad Hash。但是如果我使用myHash var(20个字节长),虽然SignHash中指定的算法是SHA512,但它可以工作,并使用SHA1算法对哈希进行签名。

另外,如果我打印csp.SignatureAlgorithm,则其值为http://www.w3.org/2000/09/xmldsig#rsa-sha1。如果已安装证书的详细信息显示为sha512RSA作为符号算法,为什么签名算法等于http://www.w3.org/2000/09/xmldsig#rsa-sha1?这点可能是真正的问题吗?如果是这样,我怎样才能正确创建证书?提前谢谢!

2 个答案:

答案 0 :(得分:1)

此过程已在.NET 4.6中简化:

byte[] signature;

using (RSA rsa = cert.GetRSAPrivateKey())
{
    signature = rsa.SignHash(hash, HashAlgorithmName.SHA512, RSASignaturePadding.Pkcs1);
}

请注意,.NET 4.6 RSA类型不再需要转换为RSACryptoServiceProvider,如果使用GetRSAPrivateKey()(而不是PrivateKey属性),则返回的对象可能会处理SHA-512签名生成。 GetRSAPrivateKey每次都返回一个唯一的对象,因此您应该适当地处理它。

答案 1 :(得分:0)

确定。没有必要实现RsaPkCs1Sha512SignatureDescription类或类似的东西,但指定正确的CSP以允许CryptoAPI使用SHA256或SHA512:" Microsoft增强型RSA和AES加密提供程序",类型24。

我们只需要将CSP类型作为CspParameter并导出/导入密钥信息:

    byte[] privateKeyBlob;
    CspParameters cp = new CspParameters(24);
    RSACryptoServiceProvider csp = (RSACryptoServiceProvider)cert.PrivateKey;
    privateKeyBlob = csp.ExportCspBlob(true);
    csp = new RSACryptoServiceProvider(cp);
    csp.ImportCspBlob(privateKeyBlob); 

    // Sign the hash
    return csp.SignHash(hashchain, CryptoConfig.MapNameToOID("SHA-512"));