总会用到的
public class Urlencrypt
{
///
/// If don't input key , Use default key
///
///
///
public static string Encode(string str)
{
return Encode(str, "Rainight");
}
///
/// Des 加密 GB2312
///
///
///
///
public static string Encode(string str, string key)
{
if (str != null)
{
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
provider.Key = Encoding.ASCII.GetBytes(key.Substring(0, 8));
provider.IV = Encoding.ASCII.GetBytes(key.Substring(0, 8));
byte[] bytes = Encoding.GetEncoding("GB2312").GetBytes(str);
MemoryStream stream = new MemoryStream();
CryptoStream stream2 = new CryptoStream(stream, provider.CreateEncryptor(), CryptoStreamMode.Write);
stream2.Write(bytes, 0, bytes.Length);
stream2.FlushFinalBlock();
StringBuilder builder = new StringBuilder();
foreach (byte num in stream.ToArray())
{
builder.AppendFormat("{0:X2}", num);
}
stream.Close();
return builder.ToString();
}
else return str;
}
///
/// if don't input key , Use default key
///
///Desc string
///
public static string Decode(string str)
{
return Decode(str, "Rainight");
}
///
/// Des 解密 GB2312
///
///Desc string
///Key ,必须为8位
///
public static string Decode(string str, string key)
{
if (str != null)
{
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
provider.Key = Encoding.ASCII.GetBytes(key.Substring(0, 8));
provider.IV = Encoding.ASCII.GetBytes(key.Substring(0, 8));
byte[] buffer = new byte[str.Length / 2];
for (int i = 0; i < (str.Length / 2); i++)
{
int num2 = Convert.ToInt32(str.Substring(i * 2, 2), 0x10);
buffer[i] = (byte)num2;
}
MemoryStream stream = new MemoryStream();
CryptoStream stream2 = new CryptoStream(stream, provider.CreateDecryptor(), CryptoStreamMode.Write);
stream2.Write(buffer, 0, buffer.Length);
stream2.FlushFinalBlock();
stream.Close();
return Encoding.GetEncoding("GB2312").GetString(stream.ToArray());
}
else return str;
}
}
加密前:
![Url加密算法](http://i2.tietuku.com/3e1a50d55933fc78.png)
加密后:
![Url加密算法](http://i2.tietuku.com/efeb97b66405031c.png)
(原文转自:咋卡哩博客:http://www.zacharyblog.com/post/10.html)