1 加密字符串: public static string Hash(string toHash) { MD5CryptoServiceProvider crypto = new MD5CryptoServiceProvider(); byte[] bytes = Encoding.Default.GetBytes(toHash); bytes = crypto.ComputeHash(bytes); StringBuilder sb = new StringBuilder(); foreach (byte num in bytes) { sb.AppendFormat("{0:x2}", num); } return sb.ToString(); } byte[] bytes = Encoding.Default.GetBytes(toHash)中Encodin的编码不一样,加密后的字符也不一样。 2 对文件中的文本加密 byte[] hash; using (Stream fs=File .OpenRead ("123.txt")) hash = MD5.Create().ComputeHash(fs); foreach (byte b in hash) { sb.Append (b.ToString ("x2")); } Console.WriteLine(sb); 3 综合实例 namespace Test { class example { byte[] key = {15,126,215,45,6,8,15,46,12,56,65,98,87,46,123,102 }; byte[] iv = {1,2,8,56,54,89,63,125,36,89,54,123,42,38,25,25 }; byte[] data = { 1,2,3,4,5}; //对data进行加密后写进txt文档 public void Jaimi() { using (SymmetricAlgorithm algorithm = Rijndael.Create()) using (ICryptoTransform encryptor = algorithm.CreateEncryptor(key, iv)) using (Stream f = File.Create("encrypted.txt")) using (Stream c = new CryptoStream(f, encryptor, CryptoStreamMode.Write)) c.Write(data, 0, data.Length); } //打开文档并解密 public void Jiemi() { // byte[] decrypted = new byte[5]; using(SymmetricAlgorithm algorithm=Rijndael .Create ()) using (ICryptoTransform encryptor=algorithm .CreateDecryptor (key,iv)) using (Stream f=File .OpenRead ("encrypted.txt")) using (Stream c=new CryptoStream (f,encryptor ,CryptoStreamMode .Read )) for(int b;(b=c.ReadByte ())>-1;) Console .WriteLine (b+""); } //加密文件 public void jiami2() { SymmetricAlgorithm algorithm = Rijndael.Create(); ICryptoTransform encryptor = algorithm.CreateEncryptor(key, iv); FileStream f = new FileStream("123.txt", FileMode.Open, FileAccess.ReadWrite); byte[] b = StreamToBytes(f); using( Stream c = new CryptoStream(f, encryptor, CryptoStreamMode.Write)) c.Write(b, 0, b.Length); } public byte[] StreamToBytes(Stream stream) { byte[] bytes = new byte[stream.Length]; stream.Read(bytes, 0, bytes.Length); // 设置当前流的位置为流的开始 stream.Seek(0, SeekOrigin.Begin); return bytes; } static void Main() { example ex = new example(); ex.Jaimi(); ex.Jiemi(); ex.jiami2(); } } } 用RSA加密: //RSA加密 public void RSA(byte[] data) { using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) { byte[] encryted = rsa.Encrypt(data, true); byte[] decryted = rsa.Decrypt(encryted, true); foreach (byte b in encryted) { Console.WriteLine(b); //打印加密数据 } foreach (byte b in decryted) { Console.WriteLine(b); //打印原数据 } Console.WriteLine(encryted.Length + "---------"); } }