DESC加密方法
直接上代碼:
1、加密
/// <summary>
/// 加密
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static string EncryptParameter(object obj)
{
if (obj == null)
{
return "";
}
StringBuilder builder = new StringBuilder();
try
{
string str = obj.ToString();
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
provider.Key = Encoding.UTF8.GetBytes(_securityKey);
provider.IV = Encoding.UTF8.GetBytes(_securityKey);
byte[] bytes = Encoding.UTF8.GetBytes(str);
MemoryStream stream = new MemoryStream();
CryptoStream stream2 = new CryptoStream(stream, provider.CreateEncryptor(), CryptoStreamMode.Write);
stream2.Write(bytes, 0, bytes.Length);
stream2.FlushFinalBlock();
foreach (byte num in stream.ToArray())
{
builder.AppendFormat("{0:X2}", num);
}
stream.Close();
}
catch (Exception ex)
{
LogHelper.LogError(ex);
}
return builder.ToString();
}
View Code
2、解密
/// <summary>
/// 解密
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string DecryptParameter(string str)
{
try
{
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
provider.Key = Encoding.ASCII.GetBytes(_securityKey);
provider.IV = Encoding.ASCII.GetBytes(_securityKey);
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());
}
catch
{
return string.Empty;
}
}
設定一個_securityKey字元串,加密、解密的密鑰要同一個才行。
是以正如其它人加密後的檔案,用常用方法是打不開的,密鑰不一樣~
作者:
唐宋元明清2188出處:
http://www.cnblogs.com/kybs0/本文版權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須在文章頁面給出原文連接配接,否則保留追究法律責任的權利。