码迷,mamicode.com
首页 > 编程语言 > 详细

标准的DES 加密 JAVA C# 通用

时间:2014-11-24 20:29:48      阅读:213      评论:0      收藏:0      [点我收藏+]

标签: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 加密 JAVA C# 通用

标签:des   style   io   ar   os   sp   java   for   on   

原文地址:http://www.cnblogs.com/top15from/p/4119330.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!