首页 > 代码库 > .Net(c#)加密解密之Des
.Net(c#)加密解密之Des
Des工具类:
/// <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(); }}
.Net(c#)加密解密之Des
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。