通过OpenSSL和Microsoft Cryptography库签名有什么区别?

时间:2015-03-07 11:41:43

标签: c# cryptography openssl x509certificate signing

我写了两个使用RSA和SHA256签名的方法,第一个使用OpenSSL库,第二个使用Microsoft Cryptography库。

OpenSSL实施:

    private string PasswordHandler(bool verify, object userdata)
    {
        return userdata.ToString();
    }

    private string Sign(string signParams)
    {
        var privateCertPath = HttpContext.Current.Server.MapPath(@"~\certificate.pem");
        string privateKey;

        using (StreamReader sr = new StreamReader(privateCertPath))
        {
            privateKey = sr.ReadToEnd();                
        }

        OpenSSL.Crypto.RSA rsa = OpenSSL.Crypto.RSA.FromPrivateKey(new BIO(privateKey), PasswordHandler, _password);
        //hash method
        MessageDigest md = MessageDigest.SHA1;

        BIO b = new BIO(signParams);
        CryptoKey ck = new CryptoKey(rsa);

        byte[] res1 = MessageDigestContext.Sign(md, b, ck);

        return Uri.EscapeDataString(System.Convert.ToBase64String(res1));
    }

加密实施:

    private string Sign(string data)
    {
        var privateCertPath = HttpContext.Current.Server.MapPath(@"~\certificate.pfx");

        X509Certificate2 privateCert = new X509Certificate2(privateCertPath, _password, X509KeyStorageFlags.Exportable);

        RSACryptoServiceProvider privateKey = (RSACryptoServiceProvider)privateCert.PrivateKey;
        RSACryptoServiceProvider privateKey1 = new RSACryptoServiceProvider();
        privateKey1.ImportParameters(privateKey.ExportParameters(true));

        // Get the bytes to be signed from the string 
        var bytes = System.Text.Encoding.UTF8.GetBytes(data);

        //const string sha256Oid = "2.16.840.1.101.3.4.2.1";
        //HashAlgorithm algorithm = new SHA256CryptoServiceProvider();
        //byte[] hashBytes = algorithm.ComputeHash(bytes);
        //byte[] signature = privateKey1.SignHash(hashBytes, sha256Oid);

        byte[] signature = privateKey1.SignData(bytes, "SHA256");

        // Base 64 encode the sig so its 8-bit clean 
        return Convert.ToBase64String(signature);
    }

使用OpenSSL签名工作,生成有效的数字签名,但使用Cryptography lib签名会生成无效签名,所以我的问题是我实施的错误?

我尝试使用不同的编码,但它没有帮助。证书生成正确。

告诉.pem证书的基本信息也很有用:

-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC

0 个答案:

没有答案