2017-01-09 199 views
2

我想用C#使用Sha1哈希和RSA签署简单数据,然后使用OpenSSL命令对其进行验证。RSA使用.Net签名并使用OpenSSL命令进行验证

对于我的测试,我已经取得了Windows上预先存在的localhost证书。

下面是用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); 
} 

(在该示例中,verified产量true

我发送的PFX的公共部分到我的Linux计算机以及该签名作为碱64.

然后我做了以下内容:

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 

Verification Failure结尾。

我检查了双方证书的序列号,它匹配。为了以防万一,我还检查了两个电台中签名的md5,全部清楚。

任何指针在哪里是明显的失败?

+0

我猜(和它只是猜测),这是使用16位的Unicode字符:'UnicodeEncoding编码=新UnicodeEncoding';而这是使用8位干净的ASCII:'echo -n“sampledata”'。 – jww

+0

@jww我在另一个代码部分使用UTF8,只是为了确保我已经用ASCII再次尝试,没有帮助 –

回答

1

您错过了哈希算法标识符到openssl dgst命令,该命令默认为MD5。

你正确的最后一行是

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

我绝对确定这个默认为sha1,应该已经验证了10次以上...谢谢 –