C# 加密解密以及sha256不可逆加密案例
class Program { static void Main(string[] args) { string aa = "身份证"; string bb = "key"; string cc = Encrypt(aa, bb); string dd = Decrypt("xFMIXBr82tTfDLmjbOoGuQWDeNS/jJUCv/p8mMxH/V4=", "key"); string ee = DateTime.Parse("2018-11-28 18:58:55.327").ToString("yyyyMMddHHmmssff"); Console.WriteLine(aa); Console.WriteLine(bb); Console.WriteLine(cc); Console.WriteLine(dd); Console.WriteLine(ee); string AA = sha256("要加密的数字"); Console.WriteLine(AA); Console.ReadKey(); } /// <summary> /// sha256加密 /// </summary> /// <param name="data"></param> /// <returns></returns> public static string sha256(string data) { byte[] bytes = Encoding.UTF8.GetBytes(data); byte[] hash = SHA256Managed.Create().ComputeHash(bytes); StringBuilder builder = new StringBuilder(); for (int i = 0; i < hash.Length; i++) { builder.Append(hash[i].ToString("X2")); } return builder.ToString(); } public static string Encrypt(string encryptStr, string key) { byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key); byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(encryptStr); RijndaelManaged rDel = new RijndaelManaged(); rDel.Key = keyArray; rDel.Mode = CipherMode.ECB; //加密模式 rDel.Padding = PaddingMode.PKCS7; //填充模式 ICryptoTransform cTransform = rDel.CreateEncryptor(); byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return Convert.ToBase64String(resultArray, 0, resultArray.Length); } /// <summary> /// AES解密 /// </summary> /// <param name="decryptStr">密文</param> /// <param name="key">密钥</param> /// <returns></returns> public static string Decrypt(string decryptStr, string key) { byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key); byte[] toEncryptArray = Convert.FromBase64String(decryptStr); RijndaelManaged rDel = new RijndaelManaged(); rDel.Key = keyArray; rDel.Mode = CipherMode.ECB; rDel.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = rDel.CreateDecryptor(); byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return UTF8Encoding.UTF8.GetString(resultArray); } }