标签:
/// <summary> /// .Net加密解密帮助类 /// </summary> public class NetCryptoHelper { /// <summary> /// Des默认密钥向量 /// </summary> public static byte[] DesIv = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; /// <summary> /// Des加解密钥必须8位 /// </summary> public const string DesKey = "deskey8w"; /// <summary> /// Des加密 /// </summary> /// <param name="source">源字符串</param> /// <param name="key">des密钥,长度必须8位</param> /// <param name="iv">密钥向量</param> /// <returns>加密后的64位字符串</returns> public static string EncryptDes(string source, string key, byte[] iv) { try { byte[] rgbKeys = Encoding.UTF8.GetBytes(key.Length > 8 ? key.Substring(0, 8) : key); byte[] rgbIvs = iv; byte[] inputByteArray = Encoding.UTF8.GetBytes(source); DESCryptoServiceProvider desProvider = new DESCryptoServiceProvider(); MemoryStream memoryStream = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream(memoryStream, desProvider.CreateEncryptor(rgbKeys, rgbIvs), CryptoStreamMode.Write); cryptoStream.Write(inputByteArray, 0, inputByteArray.Length); cryptoStream.FlushFinalBlock(); // 1.第一种 return Convert.ToBase64String(memoryStream.ToArray()); // 2.第二种 //StringBuilder result = new StringBuilder(); //foreach (byte b in memoryStream.ToArray()) //{ // result.AppendFormat("{0:X2}", b); //} //return result.ToString(); } catch { return source; } } /// <summary> /// Des解密 /// </summary> /// <param name="source">源字符串</param> /// <param name="key">des密钥,长度必须8位</param> /// <param name="iv">密钥向量</param> /// <returns>解密后的字符串</returns> public static string DecryptDes(string source, string key, byte[] iv) { try { byte[] rgbKeys = Encoding.UTF8.GetBytes(key.Length > 8 ? key.Substring(0, 8) : key); byte[] rgbIvs = iv; byte[] inputByteArray = Convert.FromBase64String(source); DESCryptoServiceProvider desProvider = new DESCryptoServiceProvider(); MemoryStream memoryStream = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream(memoryStream, desProvider.CreateDecryptor(rgbKeys, rgbIvs), CryptoStreamMode.Write); cryptoStream.Write(inputByteArray, 0, inputByteArray.Length); cryptoStream.FlushFinalBlock(); return Encoding.UTF8.GetString(memoryStream.ToArray()); } catch { return source; } } }
class Program { static void Main(string[] args) { string plainText = "博客园", encryptString = NetCryptoHelper.EncryptDes(plainText, NetCryptoHelper.DesKey, NetCryptoHelper.DesIv); Console.WriteLine("加密前的字符串:{0}", plainText); Console.WriteLine("加密后的字符串:{0}", encryptString); Console.WriteLine("解密后的字符串:{0}", NetCryptoHelper.DecryptDes(encryptString, NetCryptoHelper.DesKey, NetCryptoHelper.DesIv)); Console.ReadKey(); } }
标签:
原文地址:http://www.cnblogs.com/GodX/p/4223488.html