我在使用证书在C#中加密/解密字符串时遇到了很好的例子。我能够找到并实现签名的示例并验证签名,如下所示。有人能指出一个简单,类似的加密示例吗?
private static string Sign(RSACryptoServiceProvider privateKey, string content)
{
SHA1Managed sha1 = new SHA1Managed();
UnicodeEncoding encoding = new UnicodeEncoding ();
byte[] data = encoding.GetBytes(content);
byte[] hash = sha1.ComputeHash(data);
// Sign the hash
var signature = privateKey.SignHash(hash, CryptoConfig.MapNameToOID("SHA1"));
return Convert.ToBase64String(signature);
}
public static bool Verify(RSACryptoServiceProvider publicKey, string content, string hashString)
{
SHA1Managed sha1 = new SHA1Managed();
UnicodeEncoding encoding = new UnicodeEncoding ();
byte[] data = encoding.GetBytes(content);
byte[] hash = sha1.ComputeHash(data);
return publicKey.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA1"), Convert.FromBase64String(hashString));
}
答案 0 :(得分:12)
根据.NET Framework team's guidance(必须搜索“加密更新”,附近似乎没有锚点 - 或者,只需查看the code samples)。
public static byte[] EncryptDataOaepSha1(X509Certificate2 cert, byte[] data)
{
// GetRSAPublicKey returns an object with an independent lifetime, so it should be
// handled via a using statement.
using (RSA rsa = cert.GetRSAPublicKey())
{
// OAEP allows for multiple hashing algorithms, what was formermly just "OAEP" is
// now OAEP-SHA1.
return rsa.Encrypt(data, RSAEncryptionPadding.OaepSHA1);
}
}
因此解密将是
public static byte[] DecryptDataOaepSha1(X509Certificate2 cert, byte[] data)
{
// GetRSAPrivateKey returns an object with an independent lifetime, so it should be
// handled via a using statement.
using (RSA rsa = cert.GetRSAPrivateKey())
{
return rsa.Decrypt(data, RSAEncryptionPadding.OaepSHA1);
}
}
注意事项: