軟件開發技術交流,同窗習共進步,歡迎加羣, 羣號:169600532 算法
加密或解密,先設置一個偏移量也就是密鑰,注意:只支持8字節密鑰數組
在配置文件中設置密鑰,而後讀取ide
private static readonly string sKey = ReadConfig.ReadAppSetting("DecKey");
加密過程學習
/// <summary> /// DEC 加密過程 /// </summary> /// <param name="pToEncrypt">被加密的字符串</param> /// <param name="sKey">密鑰(只支持8個字節的密鑰)</param> /// <returns>加密後的字符串</returns> public static string Encrypt(string pToEncrypt) { //訪問數據加密標準(DES)算法的加密服務提供程序 (CSP) 版本的包裝對象 DESCryptoServiceProvider des = new DESCryptoServiceProvider(); des.Key = ASCIIEncoding.ASCII.GetBytes(sKey); //創建加密對象的密鑰和偏移量 des.IV = ASCIIEncoding.ASCII.GetBytes(sKey); //原文使用ASCIIEncoding.ASCII方法的GetBytes方法 byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);//把字符串放到byte數組中 MemoryStream ms = new MemoryStream();//建立其支持存儲區爲內存的流 //定義將數據流連接到加密轉換的流 CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); //上面已經完成了把加密後的結果放到內存中去 StringBuilder ret = new StringBuilder(); foreach (byte b in ms.ToArray()) { ret.AppendFormat("{0:X2}", b); } ret.ToString(); return ret.ToString(); }
解密過程ui
/// <summary> /// DEC 解密過程 /// </summary> /// <param name="pToDecrypt">被解密的字符串</param> /// <param name="sKey">密鑰(只支持8個字節的密鑰,同前面的加密密鑰相同)</param> /// <returns>返回被解密的字符串</returns> public static string Decrypt(string pToDecrypt) { try { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); byte[] inputByteArray = new byte[pToDecrypt.Length / 2]; for (int x = 0; x < pToDecrypt.Length / 2; x++) { int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16)); inputByteArray[x] = (byte)i; } des.Key = ASCIIEncoding.ASCII.GetBytes(sKey); //創建加密對象的密鑰和偏移量,此值重要,不能修改 des.IV = ASCIIEncoding.ASCII.GetBytes(sKey); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); //創建StringBuild對象,createDecrypt使用的是流對象,必須把解密後的文本變成流對象 StringBuilder ret = new StringBuilder(); return System.Text.Encoding.Default.GetString(ms.ToArray()); } catch (Exception ex) { BLL.NLogHelper.Instance.ErrorException("解密失敗(" + pToDecrypt + "):", ex); return ""; } }