实全加密解密

点点圈 提交于 2019-12-01 23:37:57
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ShiQuan.Security
{
    /// <summary>
    /// Base64编码可用于在HTTP环境下传递较长的标识信息。
    /// </summary>
    public static class Base64Security
    {
        /// <summary>
        /// base64加密
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string EncryptBase64(this string input)
        {
            byte[] inputBytes = Encoding.UTF8.GetBytes(input);

            return Convert.ToBase64String(inputBytes);
        }

        /// <summary>
        /// base64解密
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string DecryptBase64(this string input)
        {
            byte[] inputBytes = Convert.FromBase64String(input);

            return Encoding.UTF8.GetString(inputBytes);
        }
    }
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web.Security;

namespace ShiQuan.Security
{
    /// <summary>
    ///  DES全称为Data Encryption Standard,即数据加密标准,是一种使用密钥加密的块算法。
    /// </summary>
    public static class DESSecurity
    {
        #region Des 加密、解密

        //DES加密秘钥,要求为8位  
        private static readonly string key = "ShiQuan$";
        /// <summary>
        /// DES数据加密
        /// </summary>
        /// <param name="targetValue">目标值</param>
        /// <returns>加密值</returns>
        public static string EncryptDES(this string input)
        {
            return Encrypt(input, key);
        }
        /// <summary>
        /// DES数据加密
        /// </summary>
        /// <param name="input">目标值</param>
        /// <param name="key">密钥</param>
        /// <returns>加密值</returns>
        public static string EncryptDES(this string input, string key)
        {
            return Encrypt(input, key);
        }
        /// <summary>
        /// DES 数据加密
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string Encrypt(string input)
        {
            return Encrypt(input, key);
        }
        /// <summary>
        /// DES数据加密
        /// </summary>
        /// <param name="input">目标值</param>
        /// <param name="key">密钥</param>
        /// <returns>加密值</returns>
        public static string Encrypt(string input, string key)
        {
            if (string.IsNullOrEmpty(input))
            {
                return string.Empty;
            }
            try
            {
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                byte[] inputByteArray = Encoding.Default.GetBytes(input);
                des.Key = ASCIIEncoding.ASCII.GetBytes(MD5Security.Encrypt(key).ToUpper().Substring(0, 8));
                des.IV = ASCIIEncoding.ASCII.GetBytes(MD5Security.Encrypt(key).ToUpper().Substring(0, 8));

                System.IO.MemoryStream mStream = new System.IO.MemoryStream();
                CryptoStream cs = new CryptoStream(mStream, des.CreateEncryptor(), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                /*2019-06-28 侯连文 转码有问题*/
                //return Encoding.UTF8.GetString(mStream.ToArray());
                StringBuilder result = new StringBuilder();
                foreach (byte b in mStream.ToArray())
                {
                    result.AppendFormat("{0:X2}", b);
                }
                return result.ToString();
            }
            catch
            {
                return input;
            }
        }


        #endregion

        #region 解密
        /// <summary>
        /// DES数据解密
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string DecryptDES(this string input)
        {
            return Decrypt(input, key);
        }
        /// <summary>
        /// DES数据解密
        /// </summary>
        /// <param name="targetValue"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string DecryptDES(this string input, string key)
        {
            return Decrypt(input, key);
        }
        /// <summary>
        /// 解密数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string Decrypt(string input)
        {
            return Decrypt(input, key);
        }
        /// <summary>
        /// 解密数据
        /// </summary>
        /// <param name="input"></param>
        /// <param name="sKey"></param>
        /// <returns></returns>
        public static string Decrypt(string input, string key)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            int len = input.Length / 2;
            byte[] inputByteArray = new byte[len];
            int x, i;
            for (x = 0; x < len; x++)
            {
                i = Convert.ToInt32(input.Substring(x * 2, 2), 16);
                inputByteArray[x] = (byte)i;
            }
            des.Key = ASCIIEncoding.ASCII.GetBytes(MD5Security.Encrypt(key).ToUpper().Substring(0, 8));
            des.IV = ASCIIEncoding.ASCII.GetBytes(MD5Security.Encrypt(key).ToUpper().Substring(0, 8));
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            /*2019-06-28 侯连文 中文返回乱码*/
            //return Encoding.UTF8.GetString(ms.ToArray());
            return Encoding.Default.GetString(ms.ToArray());
        }

        
        #endregion
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace ShiQuan.Security
{
    /// <summary>
    /// MD5主要是用来做数据校验的,用于确保信息传输完整一致。
    /// </summary>
    public static class MD5Security
    {
        /// <summary>
        /// MD5 加密
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string EncryptMD5(this string input)
        {
            // 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择 
            byte[] bytes = MD5Security.Encrypt(System.Text.Encoding.UTF8.GetBytes(input));
            return System.Text.Encoding.UTF8.GetString(bytes);
        }

        /// <summary>
        /// MD5 加密
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string Encrypt(string input)
        {
            // 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择 
            byte[] bytes = MD5Security.Encrypt(System.Text.Encoding.UTF8.GetBytes(input));
            return System.Text.Encoding.UTF8.GetString(bytes);
        }
        /// <summary>
        /// MD5 加密
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static byte[] Encrypt(byte[] input)
        { 
            MD5 md5 = MD5.Create();
            return md5.ComputeHash(input);
        }
        
        /// <summary>
        /// 32位MD5加密
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string EncryptMD532(this string input)
        {
            // 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择 
            return MD5Security.Encrypt32(System.Text.Encoding.UTF8.GetBytes(input));
        }
        /// <summary>
        /// 32位MD5加密
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string Encrypt32(string input)
        {
            // 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择 
            return MD5Security.Encrypt32(System.Text.Encoding.UTF8.GetBytes(input));
        }
        /// <summary>
        /// 32位MD5加密
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string Encrypt32(byte[] input)
        {
            string result = "";
            // 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择 
            byte[] s = MD5Security.Encrypt(input);
            // 通过使用循环,将字节类型的数组转换为字符串,此字符串是常规字符格式化所得
            for (int i = 0; i < s.Length; i++)
            {
                // 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母,如果使用大写(X)则格式后的字符是大写字符 
                result = result + s[i].ToString("X");
            }
            return result;
        }
        /// <summary>
        /// 64位MD5加密
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string EncryptMD564(this string input)
        {
            // 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择 
            return MD5Security.Encrypt64(System.Text.Encoding.UTF8.GetBytes(input));
        }
        /// <summary>
        /// 64位MD5加密
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string Encrypt64(string input)
        {
            // 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择 
            return MD5Security.Encrypt64(System.Text.Encoding.UTF8.GetBytes(input));
        }
        /// <summary>
        /// 64位MD5加密
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string Encrypt64(byte[] input)
        {
            //实例化一个md5对像
            MD5 md5 = MD5.Create();
            // 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择 
            byte[] result = md5.ComputeHash(input);
            return Convert.ToBase64String(result);
        }
        /// <summary>
        /// 验证Md5 hash
        /// </summary>
        /// <param name="input">原字符串</param>
        /// <param name="encrypt32Str">原字符串的md5码</param>
        /// <returns></returns>
        public static bool VerifyMd5Hash(this string input, string encrypt32Str)
        {
            return input.VerifyMd532Hash(encrypt32Str);
        }
        /// <summary>
        /// 验证Md5 hash
        /// </summary>
        /// <param name="input">原字符串</param>
        /// <param name="encrypt32Str">原字符串的md5码</param>
        /// <returns></returns>
        public static bool VerifyMd532Hash(this string input, string encrypt32Str)
        {
            string hashOfInput = input.EncryptMD532();
            StringComparer comparer = StringComparer.OrdinalIgnoreCase;
            if (0 == comparer.Compare(hashOfInput, encrypt32Str))
                return true;
            else
                return false;
        }
        /// <summary>
        /// 验证Md5 hash
        /// </summary>
        /// <param name="input">原字符串</param>
        /// <param name="encrypt64Str">原字符串的md5码</param>
        /// <returns></returns>
        public static bool VerifyMd564Hash(this string input, string encrypt64Str)
        {
            string hashOfInput = input.EncryptMD564();
            StringComparer comparer = StringComparer.OrdinalIgnoreCase;
            if (0 == comparer.Compare(hashOfInput, encrypt64Str))
                return true;
            else
                return false;
        }
    }
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace ShiQuan.Security
{
    /// <summary>
    /// 非对称加密的代表算法是RSA算法。
    /// </summary>
    public static class RSASecurity
    {
        #region RSA加密、解密
        
        private static string RSAKey = "ShiQuan$";
        /// <summary>
        /// 生成RSA public key private key
        /// </summary>
        public static void GenerateRSAKey(string privatekeyFile, string publicKeyFile)
        {
            GenerateRSAKey(RSAKey, privatekeyFile, publicKeyFile);
        }
        /// <summary>
        /// 生成RSA public key private key
        /// </summary>
        public static void GenerateRSAKey(string keyContainerName, string privatekeyFile, string publicKeyFile)
        {
            CspParameters param = new CspParameters();
            param.KeyContainerName = keyContainerName;//密匙容器的名称,保持加密解密一致才能解密成功
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(param);
            using (StreamWriter writer = new StreamWriter(privatekeyFile))
            {
                writer.WriteLine(rsa.ToXmlString(true));
            }

            using (StreamWriter writer = new StreamWriter(publicKeyFile))
            {
                writer.WriteLine(rsa.ToXmlString(false));
            }
        }
        /// <summary>
        /// RSA加密
        /// </summary>
        public static string EncryptRSA(this string input)
        {
            return input.EncryptRSA(RSAKey);
        }

        /// <summary>
        /// RSA加密
        /// </summary>
        public static string EncryptRSA(this string input, string keyContainerName)
        {
            CspParameters param = new CspParameters();
            param.KeyContainerName = keyContainerName;//密匙容器的名称,保持加密解密一致才能解密成功
            return input.EncryptRSA(param);
        }

        /// <summary>
        /// RSA加密
        /// </summary>
        public static string EncryptRSA(this string input, CspParameters param)
        {
            if (string.IsNullOrEmpty(input))
            {
                return input;
            }
            try
            {
                using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(param))
                {
                    byte[] plaindata = Encoding.Default.GetBytes(input);//将要加密的字符串转换为字节数组
                    byte[] encryptdata = rsa.Encrypt(plaindata, false);//将加密后的字节数据转换为新的加密字节数组
                    return Convert.ToBase64String(encryptdata);//将加密后的字节数组转换为字符串
                }
            }
            catch
            {
                return input;
            }
        }

        /// <summary>
        /// RSA加密
        /// </summary>
        public static string EncryptRSA(this string input, string publicKey, bool fOAEP = false)
        {
            if (string.IsNullOrEmpty(input))
            {
                return input;
            }
            try
            {
                //publicKey = @"<RSAKeyValue><Modulus>pHfhtj8f/50PMyRq1MjcmbOSvrIIXRihzLTmrZKyo3o9ID6XEc5p4Tyjz9fbwYc8asfAF4GYJ3C/hPLvMST9M9WMKnT+sEsItG6jSVTSM0N580ORIusJRsoVBBgqczr0hNvaGmDxOvGeomqF1P/8tNQzY8L3a/szdrOSa0v6kW0=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
                using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
                {
                    rsa.FromXmlString(publicKey);
                    byte[] plaindata = Encoding.Default.GetBytes(input);//将要加密的字符串转换为字节数组
                    byte[] encryptdata = rsa.Encrypt(plaindata, fOAEP);//将加密后的字节数据转换为新的加密字节数组
                    return Convert.ToBase64String(encryptdata);//将加密后的字节数组转换为字符串
                }
            }
            catch
            {
                return input;
            }
        }

        /// <summary>
        /// RSA解密
        /// </summary>
        public static string DecryptRSA(this string input)
        {
            return input.DecryptRSA(RSAKey);
        }

        /// <summary>
        /// RSA解密
        /// </summary>
        public static string DecryptRSA(this string input, string keyContainerName)
        {
            if (string.IsNullOrEmpty(input))
            {
                return input;
            }
            try
            {
                CspParameters param = new CspParameters();
                param.KeyContainerName = keyContainerName;
                using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(param))
                {
                    byte[] encryptdata = Convert.FromBase64String(input);
                    byte[] decryptdata = rsa.Decrypt(encryptdata, false);
                    return Encoding.Default.GetString(decryptdata);
                }
            }
            catch
            {
                return input;
            }
        }
        /// <summary>
        /// RSA解密
        /// </summary>
        public static string DecryptRSA(this string input, string privateKey, bool fOAEP = false)
        {
            if (string.IsNullOrEmpty(input))
            {
                return input;
            }
            try
            {
                using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
                {
                    rsa.FromXmlString(privateKey);
                    byte[] encryptdata = Convert.FromBase64String(input);
                    byte[] decryptdata = rsa.Decrypt(encryptdata, fOAEP);
                    return Encoding.Default.GetString(decryptdata);
                }
            }
            catch
            {
                return input;
            }
        }
        #endregion
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace ShiQuan.Security
{
    /// <summary>
    /// 安全哈希算法(Secure Hash Algorithm)主要适用于数字签名标准 (Digital Signature Standard DSS)里面定义的数字签名算法(Digital Signature Algorithm DSA)。
    /// </summary>
    public static class SHA1Security
    {
        /// <summary>
        /// SHA1加密
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string EncryptSHA1(this string input)
        {
            byte[] inputBytes = Encoding.Default.GetBytes(input);

            SHA1 sha = new SHA1CryptoServiceProvider();

            byte[] result = sha.ComputeHash(inputBytes);

            StringBuilder sBuilder = new StringBuilder();

            for (int i = 0; i < result.Length; i++)
            {
                sBuilder.Append(result[i].ToString("x2"));
            }
            return sBuilder.ToString();
        }
        /// <summary>
        /// SHA1验证
        /// </summary>
        /// <param name="input"></param>
        /// <param name="encrypt32Str"></param>
        /// <returns></returns>
        public static bool VerifySha1Hash(string input, string encrypt32Str)
        {
            string hashOfInput = input.EncryptSHA1();
            StringComparer comparer = StringComparer.OrdinalIgnoreCase;
            if (0 == comparer.Compare(hashOfInput, encrypt32Str))
                return true;
            else
                return false;
        }
    }
}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!