本文主要是介绍C#Desc加密解密,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
/// <summary>
/// 使用DES加密
/// </summary>
/// <param name="plain">明文</param>
/// <param name="key">加密钥匙</param>
/// <param name="iv">向量</param>
/// <returns>返回密文</returns>
public static string DesEnCode(string plain, string key)
{
try
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
//byte[] inputByteArray = Encoding.GetEncoding("GB2312").GetBytes(plain);
byte[] inputByteArray = Encoding.UTF8.GetBytes(plain);
//建立加密对象的密钥和偏移量
//原文使用ASCIIEncoding.ASCII方法的GetBytes方法
//使得输入密码必须输入英文文本
//des.Key = ASCIIEncoding.ASCII.GetBytes(key);
//des.IV = ASCIIEncoding.ASCII.GetBytes(key);
des.Key = ASCIIEncoding.UTF8.GetBytes(key);
des.IV = ASCIIEncoding.UTF8.GetBytes(key);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
cs.Close();
StringBuilder ret = new StringBuilder();
foreach (byte b in ms.ToArray())
{
ret.AppendFormat("{0:X2}", b);
}
ms.Close();
return ret.ToString();
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 使用DES解密
/// </summary>
/// <param name="plain">密文</param>
/// <param name="key">解密钥匙</param>
/// <param name="iv">向量</param>
/// <returns>返回结果</returns>
public static string DesDeCode(string pToDecrypt, string Key)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
for (int x = 0; x < pToDecrypt.Length / 2; x++)
{
int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
inputByteArray[x] = (byte)i;
}
//des.Key = ASCIIEncoding.ASCII.GetBytes(Key);
//des.IV = ASCIIEncoding.ASCII.GetBytes(Key);
des.Key = ASCIIEncoding.UTF8.GetBytes(Key);
des.IV = ASCIIEncoding.UTF8.GetBytes(Key);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
cs.Close();
//StringBuilder ret = new StringBuilder();
//return System.Text.Encoding.GetEncoding("GB2312").GetString(ms.ToArray());
return System.Text.Encoding.UTF8.GetString(ms.ToArray());
}
这篇关于C#Desc加密解密的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!