c# - 如何在C#中加密和解密字符串

标签 c# encryption

我想在 C# 中使用一种算法加密和解密一个字符串,该算法将我引向相同的加密字符串。例如,如果我加密一个字符串122ujhdheiwe,结果是uoi8asdf8asdf,如果我再次加密相同的字符串122ujhdheiwe,它会引导我到 uoi8asdf8asdf 字符串。我可以使用哪些可能的加密算法以及如何使用?

最佳答案

如果你想要一个简单的解决方案,你可以使用 ProtectedData 类:

using System;
using System.Security.Cryptography;
using System.Text;

private void example()
{
    string data = "122ujhdheiwe";

    // Encrypt
    UnicodeEncoding unicodeEncoding = new UnicodeEncoding();
    byte[] secret = ProtectedData.Protect(unicodeEncoding.GetBytes(data), null, DataProtectionScope.CurrentUser);
    Console.WriteLine(BitConverter.ToString(secret));

    // If you need it as a printable string, you can convert the binary to Base64
    string base64 = Convert.ToBase64String(secret);
    Console.WriteLine(base64);

    // Back to binary...
    byte[] backagain = Convert.FromBase64String(base64);

    // Decrypt
    byte[] clearbytes = ProtectedData.Unprotect(backagain, null, DataProtectionScope.CurrentUser);
    string roundtripped = unicodeEncoding.GetString(clearbytes);
    Console.WriteLine(roundtripped);
}

比照。 ProtectedDataClass

如果您希望加密数据看起来非常像您的原始数据,如您问题中的示例 (122ujhdheiwe ==> uoi8asdf8asdf),那么您正在寻找的是保留格式的加密 -- cf. here ,对此我没有示例。

编辑:我刚刚注意到在您的问题中您写道您希望能够再次加密相同的字符串并获得相同的加密结果,在这种情况下 ProtectedData 将不起作用,因为加密中使用的 key 将发生变化随着时间的推移。

关于c# - 如何在C#中加密和解密字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4745061/

相关文章:

c# - 可空泛型扩展方法

c# - 局部 View 中的 ASP.NET MVC 验证并返回到父 View

c# - 什么是NullReferenceException,如何解决?

java - Android AES 无填充解密,字符串末尾有未知字符 'NUL'

c# - 解密在 ASP.NET 之外的 web.config 文件中使用 RsaProtectedConfigurationProvider 完成的加密

iphone - Google Map API V3是否包含加密

c# - 我什么时候启动和处置我的用户控件?

c# - 根据主题更改图像

python - 如何使用 pycrypto 执行河豚解密

php - 对多个字段使用相同的盐