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

Encrypt / Decrypt in C# using Certificate

我找不到在 C# 中加密/解密字符串的好例子使用证书。我能够找到并实现 signing 和验证签名的示例,如下所示。有人能给我指出一个简单、类似的加密示例吗?

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 (have to search for "Cryptography Updates", there doesn't seem to be an anchor nearby -- or, just look at 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加密主要用于加密对称密钥,而不是实际的数据有效载荷,因为它很昂贵并且有大小限制(总是低于密钥大小(以字节为单位),不同的填充模式消耗不同数量的可用space).
  • 虽然 RSA 基础 class 谈论 OaepSHA256(等),但 .NET Core 中的所有提供程序仅支持 Pkcs1 和 OaepSHA1。 (OaepSHA256+ 仅限于 RSACng)