3 回答

TA貢獻(xiàn)1934條經(jīng)驗(yàn) 獲得超2個(gè)贊
RSA + SHA256可以并且將...
您后面的示例可能并非始終有效,它應(yīng)使用哈希算法的OID,而不是名稱。根據(jù)你的第一個(gè)例子,這是從調(diào)用獲得的CryptoConfig.MapNameToOID(AlgorithmName),其中AlgorithmName是您所提供的(即“SHA256”)。
首先,您需要的是帶有私鑰的證書。我通常通過使用公共密鑰文件(.cer)來識(shí)別私鑰,從LocalMachine或CurrentUser存儲(chǔ)中讀取我的私鑰,然后枚舉證書并在哈希上進(jìn)行匹配...
X509Certificate2 publicCert = new X509Certificate2(@"C:\mycertificate.cer");
//Fetch private key from the local machine store
X509Certificate2 privateCert = null;
X509Store store = new X509Store(StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
foreach( X509Certificate2 cert in store.Certificates)
{
if (cert.GetCertHashString() == publicCert.GetCertHashString())
privateCert = cert;
}
無論您到達(dá)那里,一旦獲得帶有私鑰的證書,我們都需要對(duì)其進(jìn)行重建。由于證書創(chuàng)建它的私鑰的方式可能是必需的,但我不確定為什么。無論如何,我們首先導(dǎo)出密鑰,然后使用您喜歡的任何中間格式重新導(dǎo)入密鑰,最簡(jiǎn)單的是xml:
//Round-trip the key to XML and back, there might be a better way but this works
RSACryptoServiceProvider key = new RSACryptoServiceProvider();
key.FromXmlString(privateCert.PrivateKey.ToXmlString(true));
一旦完成,我們現(xiàn)在可以如下簽名數(shù)據(jù):
//Create some data to sign
byte[] data = new byte[1024];
//Sign the data
byte[] sig = key.SignData(data, CryptoConfig.MapNameToOID("SHA256"));
最后,可以直接使用證書的公鑰進(jìn)行驗(yàn)證,而無需像使用私鑰那樣進(jìn)行重建:
key = (RSACryptoServiceProvider)publicCert.PublicKey.Key;
if (!key.VerifyData(data, CryptoConfig.MapNameToOID("SHA256"), sig))
throw new CryptographicException();
- 3 回答
- 0 關(guān)注
- 583 瀏覽
添加回答
舉報(bào)