简体   繁体   English

使用 .Net 进行 RSA 签名并使用 OpenSSL 命令进行验证

[英]RSA Signing with .Net and verifying with OpenSSL command

I'm trying to sign a simple data with C# using Sha1 hash and RSA and then verify it with the OpenSSL command.我正在尝试使用 Sha1 哈希和 RSA 用 C# 签署一个简单的数据,然后使用 OpenSSL 命令对其进行验证。

For my tests, I've taken the localhost certificate that is preexisting on Windows.对于我的测试,我采用了 Windows 上预先存在的 localhost 证书。

Here's the code used with C#:这是与 C# 一起使用的代码:

static void Main(string[] args)
{
    string sValTest = "sampledata";
    byte[] signature = Sign(sValTest, "localhost");
    string b64 = Convert.ToBase64String(signature);
    bool verified = Verify(sValTest, signature, @"pathToCer");
}

static byte[] Sign(string text, string certSubject)
{
    X509Store my = new X509Store(StoreName.My, StoreLocation.LocalMachine);
    my.Open(OpenFlags.ReadOnly);

    RSACryptoServiceProvider csp = null;
    foreach (X509Certificate2 cert in my.Certificates)
    {
        if (cert.Subject.Contains(certSubject))
        {
            csp = (RSACryptoServiceProvider)cert.PrivateKey;
            break;
        }
    }

    SHA1Managed sha1 = new SHA1Managed();
    byte[] data = Enconding.ASCII.GetBytes(text);
    byte[] hash = sha1.ComputeHash(data);

    return csp.SignHash(hash, CryptoConfig.MapNameToOID("SHA1"));
}

static bool Verify(string text, byte[] signature, string certPath)
{
    X509Certificate2 cert = new X509Certificate2(certPath);
    RSACryptoServiceProvider csp = RSACryptoServiceProvider)cert.PublicKey.Key;

    SHA1Managed sha1 = new SHA1Managed();
    byte[] data = Encoding.ASCII.GetBytes(text);
    byte[] hash = sha1.ComputeHash(data);

    return csp.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA1"), signature);
}

(In that example, verified yields true ) (在那个例子中, verified产生true

I sent the public part of the PFX to my linux computer as well as the signature as base 64.我将 PFX 的公共部分以及作为 base 64 的签名发送到我的 linux 计算机。

I then did the following:然后我做了以下事情:

base64 --decode sig.b64 > sig
openssl x509 -inform der -in localhost.cer  -out localhost.pem
openssl x509 -pubkey -noout -in localhost.pem > localhost.pub.pem
echo -n "sampledata" | openssl dgst -verify localhost.pub.pem -signature sig

Which ends with a Verification Failure .Verification Failure结束。

I checked the serial number of the certificates on both sides and it matches.我检查了两边证书的序列号,它匹配。 Just in case, I also checked the md5 of the signature in both stations, all clear.以防万一,我还检查了两个站签名的md5,都清楚了。

Any pointers on where is the obvious fail?关于明显失败在哪里的任何指示?

You are missing the hash algorithm identifier into the openssl dgst command, which defaults to MD5.您在openssl dgst命令中缺少哈希算法标识符,该命令默认为 MD5。

Your correct last line is你正确的最后一行是

echo -n "sampledata" | openssl dgst -verify localhost.pub.pem -signature sig -sha1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM