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

标签 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));
}

最佳答案

根据 .NET Framework team's guidance (必须搜索“Cryptography Updates”,附近似乎没有 anchor ——或者,只需查看 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);
    }
}

注意事项:

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

关于c# - 使用证书在 C# 中加密/解密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41594683/

相关文章:

ios - Apple iOS 配置门户中没有 'add certificate' 按钮

android - 使用 PhoneGap 的客户端证书进行身份验证

python - Python 问题的雪花连接器

c# - 数据模板 x :Bind namespace error

c# - 更改 Winforms 中的连接字符串

c# - 为什么无法识别 bool 默认值 (false)?

sql-server - 数据库文件级加密

php - 如何防止表单变量名泄露数据库结构?

encryption - RSA-OAEP 与 RSA-PKCS1.5 的区别

c# - C# 中的通用空对象模式