标签:des style io ar os sp java for on
/// <summary>
/// DES加密
/// </summary>
/// <param name="str">待加密字符串</param>
/// <param name="key">密钥(8位)</param>
/// <returns></returns>
public static string Encode(string str, string key)
{
try
{
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 ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, provider.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(bytes, 0, bytes.Length);
cs.FlushFinalBlock();
StringBuilder builder = new StringBuilder();
foreach (byte num in ms.ToArray())
{
builder.AppendFormat("{0:X2}", num);
}
ms.Close();
return builder.ToString();
}
catch (Exception) { return "xxxx"; }
}
/// <summary>
/// DES解密
/// </summary>
/// <param name="str">待解密字符串</param>
/// <param name="key">密钥(8位)</param>
/// <returns></returns>
public static string Decode(string str, string key)
{
try
{
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 ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, provider.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(buffer, 0, buffer.Length);
cs.FlushFinalBlock();
ms.Close();
return Encoding.GetEncoding("GB2312").GetString(ms.ToArray());
}
catch (Exception) { return ""; }
}
标签:des style io ar os sp java for on
原文地址:http://www.cnblogs.com/top15from/p/4119330.html