gpt4 book ai didi

c# - 加密包含 key 的查询字符串

转载 作者:太空狗 更新时间:2023-10-29 20:45:03 26 4
gpt4 key购买 nike

我有一个应用程序使用查询字符串在页面周围传递一些值。我发现很少有关于如何加密查询字符串中的值的示例,但问题是我的 KEYS 告诉更多关于查询字符串的信息,然后是所有整数都转换为字符串的值。

有没有办法在 ASP.NET 中加密整个查询字符串,包括键和键值?

类似于:

Default.aspx?value1=40&value2=30&value3=20

 Default.aspx?56sdf78fgh90sdf4564k34klog5646l

谢谢!

最佳答案

上面的许多引用资料都忽略了一个问题,那就是在返回加密字符串之前,URL 编码(见下方字符串返回之前)。我正在使用 IIS 7.5,它会自动为您“解码”字符串,因此解密“应该”没问题。加密和解密代码如下所示。

public string EncryptQueryString(string inputText, string key, string salt)
{
byte[] plainText = Encoding.UTF8.GetBytes(inputText);

using (RijndaelManaged rijndaelCipher = new RijndaelManaged())
{
PasswordDeriveBytes secretKey = new PasswordDeriveBytes(Encoding.ASCII.GetBytes(key), Encoding.ASCII.GetBytes(salt));
using (ICryptoTransform encryptor = rijndaelCipher.CreateEncryptor(secretKey.GetBytes(32), secretKey.GetBytes(16)))
{
using (MemoryStream memoryStream = new MemoryStream())
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
{
cryptoStream.Write(plainText, 0, plainText.Length);
cryptoStream.FlushFinalBlock();
string base64 = Convert.ToBase64String(memoryStream.ToArray());

// Generate a string that won't get screwed up when passed as a query string.
string urlEncoded = HttpUtility.UrlEncode(base64);
return urlEncoded;
}
}
}
}
}

public string DecryptQueryString(string inputText, string key, string salt)
{
byte[] encryptedData = Convert.FromBase64String(inputText);
PasswordDeriveBytes secretKey = new PasswordDeriveBytes(Encoding.ASCII.GetBytes(key), Encoding.ASCII.GetBytes(salt));

using (RijndaelManaged rijndaelCipher = new RijndaelManaged())
{
using (ICryptoTransform decryptor = rijndaelCipher.CreateDecryptor(secretKey.GetBytes(32), secretKey.GetBytes(16)))
{
using (MemoryStream memoryStream = new MemoryStream(encryptedData))
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
{
byte[] plainText = new byte[encryptedData.Length];
cryptoStream.Read(plainText, 0, plainText.Length);
string utf8 = Encoding.UTF8.GetString(plainText);
return utf8;
}
}
}
}
}

关于c# - 加密包含 key 的查询字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9110561/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com