經常使用加密方法有 對稱加密和非對稱加密。對稱加密經常使用的有 DES 和 AES。DES 可被破解。這裏介紹 c# 的 AES 加密方式。c#
// AES 的 key 支持 128 位,最大支持 256 位。256 位須要 32 個字節。 // 因此這裏使用密鑰的前 32 字節做爲 key ,不足 32 補 0。 public static byte[] GetKey(string pwd) { while (pwd.Length < 32) { pwd += '0'; } pwd = pwd.Substring(0, 32); return Encoding.UTF8.GetBytes(pwd); } // AES 加密的初始化向量,加密解密需設置相同的值。 // 這裏設置爲 16 個 0。 public static byte[] AES_IV = Encoding.UTF8.GetBytes("0000000000000000"); public static string Encrypt(string pwd, object data) { var converter = new JavaScriptSerializer(); var str = converter.Serialize(data); return Encrypt(pwd, str); } // 加密 public static string Encrypt(string pwd, string data) { using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider()) { aesAlg.Key = GetKey(pwd); aesAlg.IV = AES_IV; ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); using (MemoryStream msEncrypt = new MemoryStream()) { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) { swEncrypt.Write(data); } byte[] bytes = msEncrypt.ToArray(); return Convert.ToBase64String(bytes); } } } } // 解密 public static string Decrypt(string pwd, string data) { byte[] inputBytes = Convert.FromBase64String(data); using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider()) { aesAlg.Key = GetKey(pwd); aesAlg.IV = AES_IV; ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV); using (MemoryStream msEncrypt = new MemoryStream(inputBytes)) { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, decryptor, CryptoStreamMode.Read)) { using (StreamReader srEncrypt = new StreamReader(csEncrypt)) { return srEncrypt.ReadToEnd(); } } } } }