使用证书在C#中加密/解密

时间:2017-01-11 15:26:17

标签: c# encryption certificate x509certificate x509

我在使用证书在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));
}

1 个答案:

答案 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);
    }
}

注意事项:

  • 在.NET Framework 4.6(和.NET Core 1.0 / .NET Standard 1.3)中添加了RSA.Encrypt(byte [],RSAEncryptionPadding),因此请确保构建的项目具有足够高的目标版本。
  • RSA加密主要用于加密对称密钥,而不是实际数据有效负载,因为它很昂贵且具有大小限制(始终低于密钥大小(以字节为单位),不同的填充模式消耗不同的可用空间量)。
  • 当RSA基类讨论OaepSHA256(等)时,.NET Core中的所有提供程序仅支持Pkcs1和OaepSHA1。 (OaepSHA256 +仅限于RSACng)