加密分爲:單向加密,雙向加密和對稱加密。算法
單向加密:經過對數據進行摘要計算生成密文,密文不可逆推還原。算法表明:Base64,MD5,SHA;ide
雙向加密:與單向加密相反,能夠把密文逆推還原成明文,雙向加密又分爲對稱加密和非對稱加密。ui
對稱加密:指數據使用者必須擁有相同的密鑰才能夠進行加密解密,就像彼此約定的一串暗號。算法表明:DES,3DES,AES,IDEA,RC4,RC5;加密
1 //加密 2 public static string Encode(string decryptString="須要加密的字符串", string encryptKey = "加密方式") 3 { 4 StringBuilder sb = new StringBuilder(); 5 using (DESCryptoServiceProvider des = new DESCryptoServiceProvider()) 6 { 7 byte[] key = ASCIIEncoding.ASCII.GetBytes(encryptKey); 8 byte[] iv = ASCIIEncoding.ASCII.GetBytes(encryptKey); 9 byte[] dataByteArray = Encoding.UTF8.GetBytes(decryptString); 10 des.Mode = System.Security.Cryptography.CipherMode.CBC; 11 des.Key = key; 12 des.IV = iv; 13 string encrypt = ""; 14 using (MemoryStream ms = new MemoryStream()) 15 using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write)) 16 { 17 cs.Write(dataByteArray, 0, dataByteArray.Length); 18 cs.FlushFinalBlock(); 19 encrypt = Convert.ToBase64String(ms.ToArray()); 20 } 21 string str1 = Decrypt(encrypt); 22 return encrypt.Replace("+","%2b");//在頁面間傳遞的時候可能會使‘+’字符丟失因此用‘%2b’替換 23 } 24 } 25 26 27 28 29 //解密 30 public static string Decrypt(string decryptString="須要解密的字符串", string encryptKey = "加密方式") 31 { 32 try 33 {
decryptstring=decryptstring.Replace("%2b","+");//解密的時候替換回本來的加密字符串 34 byte[] inputByteArray = Convert.FromBase64String(decryptString); 35 using (DESCryptoServiceProvider des = new DESCryptoServiceProvider()) 36 { 37 des.Key = ASCIIEncoding.ASCII.GetBytes(encryptKey); 38 des.IV = ASCIIEncoding.ASCII.GetBytes(encryptKey); 39 System.IO.MemoryStream ms = new System.IO.MemoryStream(); 40 using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write)) 41 { 42 cs.Write(inputByteArray, 0, inputByteArray.Length); 43 cs.FlushFinalBlock(); 44 cs.Close(); 45 } 46 string str1 = Encoding.UTF8.GetString(ms.ToArray()); 47 ms.Close(); 48 return str1; 49 } 50 } 51 catch (Exception ex) 52 { 53 return null; 54 } 55 }