2017-01-09 212 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次以上...謝謝 –