我需要加密我在URL中发送的字符串,稍后我需要解密它...
哪种方法会更好?我尝试了以下方法:
string s = "String to be encrypted";
string encrypted = CipherUtility.Encrypt<RijndaelManaged>(s, "pass", "salt");
string decrypted = CipherUtility.Decrypt<RijndaelManaged>(encrypted, "pass", "salt");
但加密后的字符串最后得到“=”......我想避免这种情况。
我不确定这是最好的选择......
CipherUtility如下:
public class CipherUtility
{
public static string Encrypt<T>(string value, string password, string salt)
where T : SymmetricAlgorithm, new()
{
DeriveBytes rgb = new Rfc2898DeriveBytes(password, Encoding.Unicode.GetBytes(salt));
SymmetricAlgorithm algorithm = new T();
byte[] rgbKey = rgb.GetBytes(algorithm.KeySize >> 3);
byte[] rgbIV = rgb.GetBytes(algorithm.BlockSize >> 3);
ICryptoTransform transform = algorithm.CreateEncryptor(rgbKey, rgbIV);
using (MemoryStream buffer = new MemoryStream())
{
using (CryptoStream stream = new CryptoStream(buffer, transform, CryptoStreamMode.Write))
{
using (StreamWriter writer = new StreamWriter(stream, Encoding.Unicode))
{
writer.Write(value);
}
}
return Convert.ToBase64String(buffer.ToArray());
}
}
public static string Decrypt<T>(string text, string password, string salt)
where T : SymmetricAlgorithm, new()
{
DeriveBytes rgb = new Rfc2898DeriveBytes(password, Encoding.Unicode.GetBytes(salt));
SymmetricAlgorithm algorithm = new T();
byte[] rgbKey = rgb.GetBytes(algorithm.KeySize >> 3);
byte[] rgbIV = rgb.GetBytes(algorithm.BlockSize >> 3);
ICryptoTransform transform = algorithm.CreateDecryptor(rgbKey, rgbIV);
using (MemoryStream buffer = new MemoryStream(Convert.FromBase64String(text)))
{
using (CryptoStream stream = new CryptoStream(buffer, transform, CryptoStreamMode.Read))
{
using (StreamReader reader = new StreamReader(stream, Encoding.Unicode))
{
return reader.ReadToEnd();
}
}
}
}
}
谢谢你, 米格尔
答案 0 :(得分:2)
在我收到的时事通讯上,我看到/ unsubscribe之类的东西?u = 16b832d9ad4b28edf261f56df。我正在寻找类似的东西,电子邮件不知何故“隐藏”
这不是“隐藏的”。所有这些都是对存储库(例如数据库)的引用,该存储库包含取消订阅所需的所有信息。基本上是包含有关订户的所有必要信息的记录的密钥。
如果可行的话,这可能比加密URL中的单个值更容易。
如果您仍想加密该值(以避免在数据库中存储并重新设计),在网址末尾使用=
会出现什么问题?它只是一个字符作为加密输出的一部分?