标签:
using System; using System.Collections.Generic; using System.Text; using System.Security.Cryptography; using System.IO; namespace EncryptAndDecrypt { public class CryptoUtil { //随机定义8个字节密钥和初始化向量 private byte[] Key_64 = new byte[] { 1, 2, 3, 3, 4, 5, 6, 4}; private byte[] IV_64 = new byte[] { 2, 3, 4, 5, 3, 4, 3, 2}; /// <summary> /// 加密 /// </summary> /// <param name="str">需要加密的字符串</param> /// <returns>加密后的字符串</returns> public string Encrypt(string str) { if (str == "") return str; DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider(); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, cryptoProvider.CreateEncryptor(Key_64, IV_64), CryptoStreamMode.Write); StreamWriter sw = new StreamWriter(cs); string cyrStr = ""; try { sw.Write(str); sw.Flush(); cs.FlushFinalBlock(); ms.Flush(); //将加密后的字节数组转化为字符串 cyrStr = Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length); } finally { sw.Close(); cs.Close(); ms.Close(); cryptoProvider.Clear(); } return cyrStr; } /// <summary> /// 解密 /// </summary> /// <param name="str">加密过的字符串</param> /// <returns>解密后的字符串</returns> public string Decrypt(string str) { if (str == "") return str; //将字符串转换成字节数组 byte[] strbyte = Convert.FromBase64String(str); DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider(); MemoryStream ms = new MemoryStream(strbyte); CryptoStream cs = new CryptoStream(ms, cryptoProvider.CreateDecryptor(Key_64, IV_64), CryptoStreamMode.Read); StreamReader sr = new StreamReader(cs); string uncryStr = ""; try { uncryStr = sr.ReadToEnd(); } finally { sr.Close(); cs.Close(); ms.Close(); cryptoProvider.Clear(); } return uncryStr; } } public class Program { public static void Main(string[] args) { CryptoUtil crypt = new CryptoUtil(); string text = "KingSoft"; string en = crypt.Encrypt(text); Console.WriteLine(en); string de = crypt.Decrypt(en); Console.WriteLine(de); } } }
标签:
原文地址:http://www.cnblogs.com/mtsl/p/4234593.html