我想在 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);
}
如果您希望加密数据看起来非常像您的原始数据,如您问题中的示例 (122ujhdheiwe ==> uoi8asdf8asdf),那么您正在寻找的是保留格式的加密 -- cf. here ,对此我没有示例。
编辑:我刚刚注意到在您的问题中您写道您希望能够再次加密相同的字符串并获得相同的加密结果,在这种情况下 ProtectedData 将不起作用,因为加密中使用的 key 将发生变化随着时间的推移。
关于c# - 如何在C#中加密和解密字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4745061/