标准的DES 加密 JAVA C# 通用

/// <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 ""; }
}

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。