该类使用著名的加密算法DES来实现网站信息的加密与解密程序。DES属于一种私钥加密,也称为对称加密。所谓对称加密,就是使用一个密钥加密,也必须使用该密钥进行解密。
私钥加密算法的速度非常快,它特别适合用于对较大的数据流执行加密。
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Security.Cryptography; 6 using System.Text; 7 using System.IO; 8 9 namespace ECExp 10 { 11 public class SafeUtil 12 { 13 private string iv = "12345678";//种子 14 private string key = "12345678";//密钥 15 private Encoding encoding = new UnicodeEncoding(); 16 private DES des = null; 17 18 /// <summary> 19 /// 构造函数 20 /// </summary> 21 public SafeUtil() 22 { 23 des = new DESCryptoServiceProvider(); 24 } 25 26 /// <summary> 27 /// 设置密钥 28 /// </summary> 29 public string EncryptKey 30 { 31 set 32 { 33 this.key = value; 34 } 35 } 36 37 /// <summary> 38 /// 设置或获取密文编码格式(默认为UTF-8) 39 /// </summary> 40 public Encoding EncodingMode 41 { 42 get { return this.encoding; } 43 set { this.encoding = value; } 44 } 45 46 /// <summary> 47 /// 加密字符串并返回加密后的结果 48 /// </summary> 49 /// <param name="str">要加密的字符串</param> 50 /// <returns></returns> 51 public string EncryptString(string str) 52 { 53 byte[] ivb = Encoding.ASCII.GetBytes(this.iv); 54 byte[] keyb = Encoding.ASCII.GetBytes(this.key);//得到加密密钥 55 byte[] toEncrypt = this.EncodingMode.GetBytes(str);//得到要加密的内容 56 byte[] encrypted; 57 58 //DES加密工具类 59 ICryptoTransform encryptor = des.CreateEncryptor(keyb, ivb); 60 MemoryStream msEncrypt = new MemoryStream(); 61 CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write); 62 63 csEncrypt.Write(toEncrypt, 0, toEncrypt.Length); 64 csEncrypt.FlushFinalBlock(); 65 encrypted = msEncrypt.ToArray(); 66 csEncrypt.Close(); 67 msEncrypt.Close(); 68 return Convert.ToBase64String(encrypted); 69 } 70 71 /// <summary> 72 /// 解密给定的字符串 73 /// </summary> 74 /// <param name="str">要解密的字符,Base64</param> 75 /// <returns></returns> 76 public string DecryptString(string str) 77 { 78 byte[] ivb = Encoding.ASCII.GetBytes(this.iv); 79 byte[] keyb = Encoding.ASCII.GetBytes(this.key); 80 byte[] toDecrypt = Convert.FromBase64String(str); 81 byte[] deCrypted = new byte[toDecrypt.Length]; 82 83 ICryptoTransform deCryptor = des.CreateDecryptor(keyb, ivb); 84 MemoryStream msDecrypt = new MemoryStream(toDecrypt); 85 CryptoStream csDecrypt = new CryptoStream(msDecrypt, deCryptor, CryptoStreamMode.Read); 86 87 try 88 { 89 csDecrypt.Read(deCrypted, 0, deCrypted.Length); 90 } 91 catch (Exception err) 92 { 93 94 throw new ApplicationException(err.Message); 95 } 96 finally 97 { 98 try 99 { 100 msDecrypt.Close(); 101 csDecrypt.Close(); 102 } 103 catch (Exception) 104 { 105 106 } 107 } 108 return this.EncodingMode.GetString(deCrypted); 109 } 110 } 111 }
如何使用:
SafeUtil safeutil = new SafeUtil(); string str = safeutil.EncryptString("456123"); lblText.Text = str; string str2 = safeutil.DecryptString(safeutil.EncryptString("456123")); Label1.Text = str2;