C#.NET 加密解密:AES/DES/Base64/RSA/MD5/SHA256

來源:互聯網
上載者:User
using System;using System.Globalization;using System.IO;using System.Security.Cryptography;using System.Text;namespace Pub.Class{    public static class EncryptExtensions    {        private static readonly byte[] AESKeys = {0x41, 0x72, 0x65, 0x79, 0x6F, 0x75, 0x6D, 0x79, 0x53, 0x6E, 0x6F, 0x77, 0x6D, 0x61, 0x6E, 0x3F};        private static readonly byte[] DESKeys = {0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF};        public static string AESEncode(this string encryptString, string encryptKey)        {            encryptKey = encryptKey.SubString(32, "");            encryptKey = encryptKey.PadRight(32, ' ');            var rijndaelProvider = new RijndaelManaged();            rijndaelProvider.Key = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 32));            rijndaelProvider.IV = AESKeys;            ICryptoTransform rijndaelEncrypt = rijndaelProvider.CreateEncryptor();            byte[] inputData = Encoding.UTF8.GetBytes(encryptString);            byte[] encryptedData = rijndaelEncrypt.TransformFinalBlock(inputData, 0, inputData.Length);            return Convert.ToBase64String(encryptedData);        }        public static string AESDecode(this string decryptString, string decryptKey)        {            try            {                decryptKey = decryptKey.SubString(32, "");                decryptKey = decryptKey.PadRight(32, ' ');                var rijndaelProvider = new RijndaelManaged();                rijndaelProvider.Key = Encoding.UTF8.GetBytes(decryptKey);                rijndaelProvider.IV = AESKeys;                ICryptoTransform rijndaelDecrypt = rijndaelProvider.CreateDecryptor();                byte[] inputData = Convert.FromBase64String(decryptString);                byte[] decryptedData = rijndaelDecrypt.TransformFinalBlock(inputData, 0, inputData.Length);                return Encoding.UTF8.GetString(decryptedData);            }            catch            {                return string.Empty;            }        }        public static string DESEncode(this string encryptString, string encryptKey)        {            encryptKey = encryptKey.SubString(8, "");            encryptKey = encryptKey.PadRight(8, ' ');            byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));            byte[] rgbIV = DESKeys;            byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);            var dCSP = new DESCryptoServiceProvider();            var mStream = new MemoryStream();            var cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);            cStream.Write(inputByteArray, 0, inputByteArray.Length);            cStream.FlushFinalBlock();            return Convert.ToBase64String(mStream.ToArray());        }        public static string DESDecode(this string decryptString, string decryptKey)        {            try            {                decryptKey = decryptKey.SubString(8, "");                decryptKey = decryptKey.PadRight(8, ' ');                byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey);                byte[] rgbIV = DESKeys;                byte[] inputByteArray = Convert.FromBase64String(decryptString);                var DCSP = new DESCryptoServiceProvider();                var mStream = new MemoryStream();                var cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);                cStream.Write(inputByteArray, 0, inputByteArray.Length);                cStream.FlushFinalBlock();                return Encoding.UTF8.GetString(mStream.ToArray());            }            catch            {                return string.Empty;            }        }        public static string Base64Encode(this string encryptString)        {            byte[] encbuff = Encoding.UTF8.GetBytes(encryptString);            return Convert.ToBase64String(encbuff);        }        public static string Base64Decode(this string decryptString)        {            byte[] decbuff = Convert.FromBase64String(decryptString);            return Encoding.UTF8.GetString(decbuff);        }        public static string RSADecrypt(this string s, string key)        {            string result = null;            if (string.IsNullOrEmpty(s)) throw new ArgumentException("An empty string value cannot be encrypted.");            if (string.IsNullOrEmpty(key)) throw new ArgumentException("Cannot decrypt using an empty key. Please supply a decryption key.");            var cspp = new CspParameters();            cspp.KeyContainerName = key;            var rsa = new RSACryptoServiceProvider(cspp);            rsa.PersistKeyInCsp = true;            string[] decryptArray = s.Split(new[] {"-"}, StringSplitOptions.None);            byte[] decryptByteArray = Array.ConvertAll(decryptArray, (a => Convert.ToByte(byte.Parse(a, NumberStyles.HexNumber))));            byte[] bytes = rsa.Decrypt(decryptByteArray, true);            result = Encoding.UTF8.GetString(bytes);            return result;        }        public static string RSAEncrypt(this string s, string key)        {            if (string.IsNullOrEmpty(s)) throw new ArgumentException("An empty string value cannot be encrypted.");            if (string.IsNullOrEmpty(key)) throw new ArgumentException("Cannot encrypt using an empty key. Please supply an encryption key.");            var cspp = new CspParameters();            cspp.KeyContainerName = key;            var rsa = new RSACryptoServiceProvider(cspp);            rsa.PersistKeyInCsp = true;            byte[] bytes = rsa.Encrypt(Encoding.UTF8.GetBytes(s), true);            return BitConverter.ToString(bytes);        }        public static string MD5(this string str)        {            string cl1 = str;            string pwd = "";            MD5 md5 = System.Security.Cryptography.MD5.Create(); // 加密後是一個位元組類型的數組             byte[] s = md5.ComputeHash(Encoding.Unicode.GetBytes(cl1));            for (int i = 0; i < s.Length; i++)            {// 通過使用迴圈,將位元組類型的數群組轉換為字串,此字串是常規字元格式設定化所得                 pwd = pwd + s[i].ToString("x"); // 將得到的字串使用十六進位類型格式。格式後的字元是小寫字母,如果使用大寫(X)則格式後的字元是大寫字元             }            return pwd;        }        public static string MD5CSP(this string encypStr)        {            string retStr;            var m5 = new MD5CryptoServiceProvider();            //建立md5對象            byte[] inputBye;            byte[] outputBye;            //使用GB2312編碼方式把字串轉化為位元組數組.            inputBye = Encoding.GetEncoding("GB2312").GetBytes(encypStr);            outputBye = m5.ComputeHash(inputBye);            retStr = BitConverter.ToString(outputBye);            retStr = retStr.Replace("-", "").ToLower();            return retStr;        }        public static string SHA256(this string str)        {            byte[] SHA256Data = Encoding.UTF8.GetBytes(str);            var Sha256 = new SHA256Managed();            byte[] Result = Sha256.ComputeHash(SHA256Data);            return Convert.ToBase64String(Result); //返回長度為44位元組的字串        }    }}

  

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.