X509Certificate2崩溃IIS

时间:2015-08-14 13:58:31

标签: c# iis cryptography

以下是破解IIS的代码,经过研究后我发现了以下帖子 X509Certificate2 makes IIS crash并解决了我的问题

        var cert = new X509Certificate2();
        cert.Import(Resources.wildcard, "xxx", X509KeyStorageFlags.Exportable);

固定代码

        var cert = new X509Certificate2();
        cert.Import(Resources.wildcard, "xxx", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);

但现在这导致我的签名抛出以下异常

n exception of type 'System.Security.Cryptography.CryptographicException' occurred in mscorlib.dll but was not handled in user code
Additional information: Invalid provider type specified.

我的代码

public class RsaSha1
{
    private readonly X509Certificate2 _certificate;

    public RsaSha1(X509Certificate2 certificate)
    {
        _certificate = certificate;
    }

    public string Sign(string signatureBaseString)
    {
        return SignCore(signatureBaseString);
    }

    string SignCore(string baseString)
    {
        using (var hash = Hash(baseString))
        {
            return Base64Encode(Sign(hash));
        }
    }

    private static string Base64Encode(byte[] signature)
    {
        return Convert.ToBase64String(signature);
    }


    private byte[] Sign(SHA1CryptoServiceProvider hash)
    {
        var formatter = new RSAPKCS1SignatureFormatter(_certificate.PrivateKey).
            Tap(it => it.SetHashAlgorithm("MD5"));
   //The line above throws the Exception if X509KeyStorageFlags.MachineKeySet is added,
   //but without X509KeyStorageFlags.MachineKeySet my application works in a console application (stress testing) but not in IIS (in a web application)
        return formatter.CreateSignature(hash);
    }

    SHA1CryptoServiceProvider Hash(string signatureBaseString)
    {
        var sha1 = new SHA1CryptoServiceProvider();

        var bytes = Encoding.ASCII.GetBytes(signatureBaseString);

        using (var crypto = new CryptoStream(Stream.Null, sha1, CryptoStreamMode.Write))
        {
            crypto.Write(bytes, 0, bytes.Length);
        }

        return sha1;
    }
}

编辑1: 新的信息,似乎当我添加X509KeyStorageFlags.MachineKeySet然后_certificate.PrivateKey会抛出异常但当我删除X509KeyStorageFlags.MachineKeySet然后IIS会崩溃。 PS我使用的是从StartSSL生成的证书

1 个答案:

答案 0 :(得分:1)

我将证书导入LocalMachine商店(不是通过代码) 然后在我的软件中我改变了

   var cert = new X509Certificate2();
   cert.Import(Resources.wildcard, "xxx", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);

        X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
        store.Open(OpenFlags.ReadOnly);
        foreach (X509Certificate2 certificate in store.Certificates)
        {
            if (certificate.SubjectName.Name != null && certs.SubjectName.Name.Contains("*.domain.xxx"))
            {
                cert = certificate;
            }
        }

这似乎比从文件加载证书更好,并且在加载时也不会破坏IIS