今天,我需要做一個DES加密過程.中間出了個問題,就是我把方法直接放到了命名空間下面.之間沒有在意這個問題,這次,我真的費了很大的經,終於找到錯誤.這個錯誤雖然在很多大俠們眼里根本不是錯誤.但是,這是我沒有意識錯誤.下面是我的代碼.自己一定要謹記.
1 using System; 2 using System.Collections.Generic; 3 using System.Text; 4 using System.Security.Cryptography; 5 using System.IO; 6 7 namespace DESJIAMI 8 { 9 public class EncryptDES { 10 /// <summary> 11 /// DES加密字符串 12 /// </summary> 13 /// <param name="encryptString">待加密的字符串</param> 14 /// <param name="encryptKey">加密密鑰,要求為8位</param> 15 /// <returns>加密成功返回加密后的字符串,失敗返回源串</returns> 16 public static string strEncryptDES(string encryptString, string encryptKey) 17 { 18 try 19 { 20 byte[] rgbKey= Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8)); 21 //rgbIV與rgbKey可以不一樣,這里只是為了簡便,讀者可以自行修改 22 byte[] rgbIV = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8)); 23 byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString); 24 DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider(); 25 26 MemoryStream mStream = new MemoryStream(); 27 CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write); 28 cStream.Write(inputByteArray, 0, inputByteArray.Length); 29 cStream.FlushFinalBlock(); 30 return Convert.ToBase64String(mStream.ToArray()); 31 } 32 catch 33 { 34 return encryptString; 35 } 36 } 37 } 38 }