需要引用名稱空間
using System; using System.Text; using System.Security.Cryptography; using System.IO;
具體代碼:
1 public class CryptoHelper 2 { 3 /// <summary> 4 /// 使用DES加密 5 /// </summary> 6 /// <param name="plain">明文</param> 7 /// <param name="key">加密鑰匙</param> 8 /// <param name="iv">向量</param> 9 /// <returns>返回密文</returns> 10 public static string DesEncode(string plain, string key, string iv) 11 { 12 //把密鑰轉換成字節數組 13 byte[] keyBytes = Encoding.ASCII.GetBytes(key); 14 15 //把向量轉換成字節數組 16 byte[] ivBytes = Encoding.ASCII.GetBytes(iv); 17 18 //聲明1個新的DES對象 19 DESCryptoServiceProvider des = new DESCryptoServiceProvider(); 20 21 //開辟一塊內存流 22 MemoryStream msEncrypt = new MemoryStream(); 23 24 //把內存流對象包裝成加密流對象 25 CryptoStream csEncrypt = new CryptoStream(msEncrypt, des.CreateEncryptor(keyBytes, ivBytes), CryptoStreamMode.Write); 26 27 //把加密流對象包裝成寫入流對象 28 StreamWriter swEncrypt = new StreamWriter(csEncrypt); 29 30 //寫入流對象寫入明文 31 swEncrypt.WriteLine(plain); 32 33 //寫入流關閉 34 swEncrypt.Close(); 35 36 //加密流關閉 37 csEncrypt.Close(); 38 39 //把內存流轉換成字節數組,內存流現在已經是密文了 40 byte[] bytesCipher=msEncrypt.ToArray(); 41 42 //內存流關閉 43 msEncrypt.Close(); 44 //將字節數組轉化成Base64字符串 45 return Convert.ToBase64String(bytesCipher); 46 } 47 48 public static string DesDeCode(string cipher, string key, string iv) 49 { 50 //將密文通過Base64位還原成字節數組 51 byte[] cipherByte = Convert.FromBase64String(cipher); 52 53 //把密鑰轉換成字節數組 54 byte[] keyBytes = Encoding.ASCII.GetBytes(key); 55 56 //把向量轉換成字節數組 57 byte[] ivBytes = Encoding.ASCII.GetBytes(iv); 58 59 //聲明1個新的DES對象 60 DESCryptoServiceProvider des = new DESCryptoServiceProvider(); 61 62 //開辟一塊內存流,並存放密文字節數組 63 MemoryStream msDecrypt = new MemoryStream(cipherByte); 64 65 //把內存流對象包裝成解密流對象 66 CryptoStream csDecrypt = new CryptoStream(msDecrypt, des.CreateDecryptor(keyBytes, ivBytes), CryptoStreamMode.Read); 67 68 //把解密流對象包裝成寫入流對象 69 StreamReader srDecrypt = new StreamReader(csDecrypt); 70 71 //明文=讀出流的讀出內容 72 string strPlainText=srDecrypt.ReadLine(); 73 74 //讀出流關閉 75 srDecrypt.Close(); 76 77 //解密流關閉 78 csDecrypt.Close(); 79 80 //內存流關閉 81 msDecrypt.Close(); 82 83 //返回明文 84 return strPlainText; 85 } 86 }