Nido.Common.Utilities.MD5类
2016-02-28 18:01
369 查看
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; namespace Nido.Common.Utilities.MD5 { public class Crypto { static readonly string PasswordHash = "P@@Sw0rd"; static readonly string SaltKey = "S@LT&KEY"; static readonly string VIKey = "@1B2c3D4e5F6g7H8"; public static string Encrypt(string plainText) { try { byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText); byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8); var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.Zeros }; var encryptor = symmetricKey.CreateEncryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey)); byte[] cipherTextBytes; using (var memoryStream = new MemoryStream()) { using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)) { cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length); cryptoStream.FlushFinalBlock(); cipherTextBytes = memoryStream.ToArray(); cryptoStream.Close(); } memoryStream.Close(); } return Convert.ToBase64String(cipherTextBytes); } catch { return plainText; } } public static string Decrypt(string encryptedText) { try { byte[] cipherTextBytes = Convert.FromBase64String(encryptedText); byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8); var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.None }; var decryptor = symmetricKey.CreateDecryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey)); var memoryStream = new MemoryStream(cipherTextBytes); var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read); byte[] plainTextBytes = new byte[cipherTextBytes.Length]; int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length); memoryStream.Close(); cryptoStream.Close(); return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount).TrimEnd("\0".ToCharArray()); } catch { return encryptedText; } } } }
相关文章推荐
- 【转】Github 上传代码
- 费马小定理证明
- 排序算法之冒泡排序
- RANGE MINIUM/MAXIUM QUERY问题
- iOS:UITextView、UITextField检测用户是否完成输入的选择
- 动态规划入门
- python 在windows下如何切换工作路径
- 5抽象工厂模式
- 4工厂方法模式
- Linux内核分析— —计算机是如何工作的(20135213林涵锦)
- “鸽姆微媒体+互联网商业智慧创业孵化器”会议培训项目方案
- UNIMODAL PALINDROMIC DECOMPOSITIONS-----动态规划-------单峰回文序列分解
- 3单例模式
- 项目管理过程 (1)
- SQLiteOpenHelper对数据库进行版本管理
- 精通JavaScript的this关键字
- 2015寒假总结—做自己
- 表变量与临时表的优缺点
- http server原理,nginx与php之间是如何工作的
- Linux内核设计与实现-第三章 进程管理