公司協議安全需求、需要對傳輸內容做des、md5加密。
因為是新人、剛交給我這個任務的時候有點眩暈。就開始在網上找各種des加密的內容。因為不懂以為需要把原理也搞明白,最后誤了時間、把自己也搞糊塗了。當然,邏輯能力強、有興趣的朋友可以試着去搞搞。
網上很多加密方式,做為開發人員,只要懂得怎么運用就行。
第一次寫文章、優美的語句等有經驗了再獻丑,咱們直入正題。
先貼加密、解密的源碼:

1 /// <summary> 2 3 /// 加密數據 4 5 /// </summary> 6 7 /// <param name="Text"></param> 8 9 /// <param name="sKey"></param> 10 11 /// <returns></returns> 12 13 public static string Encrypt(string Text, string sKey) { 14 15 DESCryptoServiceProvider des = new DESCryptoServiceProvider(); 16 17 byte[] inputByteArray; 18 19 inputByteArray = Encoding.Default.GetBytes(Text); 20 21 des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8)); 22 23 des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8)); 24 25 System.IO.MemoryStream ms = new System.IO.MemoryStream(); 26 27 CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write); 28 29 cs.Write(inputByteArray, 0, inputByteArray.Length); 30 31 cs.FlushFinalBlock(); 32 33 StringBuilder ret = new StringBuilder(); 34 35 foreach (byte b in ms.ToArray()) { 36 37 ret.AppendFormat("{0:X2}", b); 38 39 } 40 41 return ret.ToString(); 42 43 } 44 45 #endregion 46 47 /// <summary> 48 49 /// 解密數據 50 51 /// </summary> 52 53 /// <param name="Text"></param> 54 55 /// <param name="sKey"></param> 56 57 /// <returns></returns> 58 59 public static string Decrypt(string Text, string sKey) { 60 61 DESCryptoServiceProvider des = new DESCryptoServiceProvider(); 62 63 int len; 64 65 len = Text.Length / 2; 66 67 byte[] inputByteArray = new byte[len]; 68 69 int x, i; 70 71 for (x = 0; x < len; x++) { 72 73 i = Convert.ToInt32(Text.Substring(x * 2, 2), 16); 74 75 inputByteArray[x] = (byte)i; } 76 77 des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8)); 78 79 des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8)); 80 81 System.IO.MemoryStream ms = new System.IO.MemoryStream(); 82 83 CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write); 84 85 cs.Write(inputByteArray, 0, inputByteArray.Length); 86 87 cs.FlushFinalBlock(); 88 89 return Encoding.Default.GetString(ms.ToArray()); } 90 91 #endregion
因為是第一次接觸des並且公司協議文檔的需求、讓我對這段代碼里面迷糊的有:
1:倆個參數
Text 是要加密的內容
sKey是作為加密內容的密鑰。當然加密、解密時候的sKey值,是要保持一致的。
2:des對象的key值
這個key值和IV值是固定的8位長度,一定要牢記。因為咱們的參數sKey是不定長度的、所以采取了一個方式就是對其進行MD5加密、然后再截取他的前8位。這是為了在解密的時候保證key一致。不然會解密出錯。
最后,我說一下做為新人,我感覺牢記的幾個地方,或許是大大們眼中寫des必需的幾點~~別噴我啊、
幾個必要的對象:
DESCryptoServiceProvider 沒有它你想怎么des呢、嘿嘿
MemoryStream 存儲在內存的流對象
CryptoStream 定義將數據流鏈接到加密轉換流。通過它寫入MemoryStream對象當中
最后轉換成String、
就這么搞定了、我也有好多不懂的、歡迎朋友們一起討論、大大們多多指教。