C# 加密解密

BaseEncrypt

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace CommonLib.EncryptUtils.BaseEncrypt
{
    /// <summary>
    /// AES加密解密帮助类
    /// </summary>
    public class AESHelper
    {

        /// <summary>
        /// 获取Base64编码后的Key和IV
        /// </summary>
        /// <returns>Base64编码后的(Key、IV)字符串数组</returns>
        public static string[] GetKeys()
        {
            using (Aes aes = Aes.Create())
            {
                return new string[] { Convert.ToBase64String(aes.Key), Convert.ToBase64String(aes.IV) };
            }
        }

        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="key">Key字节数组,可以用DESHelper.GetKeys()获取后通过Base64解码得到。</param>
        /// <param name="iv">IV字节数组,可以用DESHelper.GetKeys()获取后通过Base64解码得到。</param>
        public AESHelper(byte[] key, byte[] iv)
        {
            _Key = key;
            _IV = iv;
        }

        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="key">经过Base64编码后的Key</param>
        /// <param name="iv">经过Base64编码后的IV</param>
        public AESHelper(string key, string iv)
        {
            _Key = Convert.FromBase64String(key);
            _IV = Convert.FromBase64String(iv);
        }

        /// <summary>
        /// Key字节数组
        /// </summary>
        private readonly byte[] _Key;

        /// <summary>
        /// IV字节数组
        /// </summary>
        private readonly byte[] _IV;

        /// <summary>
        /// 加密(字节数组)
        /// </summary>
        /// <param name="encryptBytes">待加密的字节数组</param>
        /// <returns>加密后的字节数组</returns>
        public byte[] Encrypt(byte[] encryptBytes)
        {
            using (MemoryStream mStream = new MemoryStream())
            {
                using (Aes aes = Aes.Create())
                {
                    using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateEncryptor(_Key, _IV), CryptoStreamMode.Write))
                    {
                        cStream.Write(encryptBytes, 0, encryptBytes.Length);
                        cStream.FlushFinalBlock();
                        return mStream.ToArray();
                    }
                }
            }
        }

        /// <summary>
        /// 解密(字节数组)
        /// </summary>
        /// <param name="decryptBytes">待解密的字节数组</param>
        /// <returns>解密后的字节数组</returns>
        public byte[] Decrypt(byte[] decryptBytes)
        {
            using (MemoryStream mStream = new MemoryStream(decryptBytes))
            {
                using (Aes aes = Aes.Create())
                {
                    aes.Key = _Key;
                    aes.IV = _IV;
                    using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateDecryptor(_Key, _IV), CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(cStream))
                        {
                            return Encoding.UTF8.GetBytes(srDecrypt.ReadToEnd());
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 加密(字符串)
        /// </summary>
        /// <param name="encryptString">待加密字符串</param>
        /// <returns>加密后的字符串</returns>
        public string EncryptString(string encryptString)
        {
            byte[] data = Encoding.UTF8.GetBytes(encryptString);
            return Convert.ToBase64String(Encrypt(data));
        }

        /// <summary>
        /// 解密(字符串)
        /// </summary>
        /// <param name="decryptString">待解密字符串</param>
        /// <returns>解密后的字符串</returns>
        public string DecryptString(string decryptString)
        {
            byte[] data = Convert.FromBase64String(decryptString);
            return Encoding.UTF8.GetString(Decrypt(data));
        }

    }
}

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace CommonLib.EncryptUtils.BaseEncrypt
{
    /// <summary>
    /// DES加密解密帮助类
    /// </summary>
    public class DESHelper
    {
        /// <summary>
        /// 获取Base64编码后的Key和IV
        /// </summary>
        /// <returns>Base64编码后的(Key、IV)字符串数组</returns>
        public static string[] GetKeys()
        {
            using (DES des = DES.Create())
            {
                return new string[] { Convert.ToBase64String(des.Key), Convert.ToBase64String(des.IV) };
            }
        }

        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="key">Key字节数组,可以用DESHelper.GetKeys()获取后通过Base64解码得到。</param>
        /// <param name="iv">IV字节数组,可以用DESHelper.GetKeys()获取后通过Base64解码得到。</param>
        public DESHelper(byte[] key, byte[] iv)
        {
            _Key = key;
            _IV = iv;
        }

        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="key">经过Base64编码后的Key</param>
        /// <param name="iv">经过Base64编码后的IV</param>
        public DESHelper(string key, string iv)
        {
            _Key = Convert.FromBase64String(key);
            _IV = Convert.FromBase64String(iv);
        }

        /// <summary>
        /// Key字节数组
        /// </summary>
        private readonly byte[] _Key;

        /// <summary>
        /// IV字节数组
        /// </summary>
        private readonly byte[] _IV;

        /// <summary>
        /// 加密(字节数组)
        /// </summary>
        /// <param name="encryptBytes">待加密的字节数组</param>
        /// <returns>加密后的字节数组</returns>
        public byte[] Encrypt(byte[] encryptBytes)
        {
            using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
            {
                des.IV = _IV;
                des.Key = _Key;

                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
                cs.Write(encryptBytes, 0, encryptBytes.Length);
                cs.FlushFinalBlock();
                return ms.ToArray();
            }
        }


        /// <summary>
        /// 解密(字节数组)
        /// </summary>
        /// <param name="decryptBytes">待解密的字节数组</param>
        /// <returns>解密后的字节数组</returns>
        public byte[] Decrypt(byte[] decryptBytes)
        {
            using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
            {
                des.IV = _IV;
                des.Key = _Key;

                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
                cs.Write(decryptBytes, 0, decryptBytes.Length);
                cs.FlushFinalBlock();
                return ms.ToArray();
            }
        }

        /// <summary>
        /// 加密(字符串)
        /// </summary>
        /// <param name="encryptString">待加密字符串</param>
        /// <returns>加密后的字符串</returns>
        public string EncryptString(string encryptString)
        {
            byte[] data = Encoding.UTF8.GetBytes(encryptString);
            return Convert.ToBase64String(Encrypt(data));
        }

        /// <summary>
        /// 解密(字符串)
        /// </summary>
        /// <param name="decryptString">待解密字符串</param>
        /// <returns>解密后的字符串</returns>
        public string DecryptString(string decryptString)
        {
            byte[] data = Convert.FromBase64String(decryptString);
            return Encoding.UTF8.GetString(Decrypt(data));
        }
    }
}

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

namespace CommonLib.EncryptUtils.BaseEncrypt
{
    /// <summary>
    /// HmacSHA256加密帮助类
    /// </summary>
    public class HMACSHA256Helper
    {
        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="keyBytes">Key字节数组</param>
        public HMACSHA256Helper(byte[] keyBytes)
        {
            _KeyBytes = keyBytes;
        }

        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="keyStr">Key字符串</param>
        public HMACSHA256Helper(string keyStr)
        {
            _KeyBytes = Encoding.UTF8.GetBytes(keyStr);
        }

        /// <summary>
        /// Key字节数组
        /// </summary>
        private readonly byte[] _KeyBytes;

        /// <summary>
        /// 加密(字节数组)
        /// </summary>
        /// <param name="encryptBytes">待加密的字节数组</param>
        /// <returns>加密后的字节数组</returns>
        public byte[] Encrypt(byte[] encryptBytes)
        {
            using (var hmacsha256 = new HMACSHA256(_KeyBytes))
            {
                return hmacsha256.ComputeHash(encryptBytes);
            }
        }

        /// <summary>
        /// 加密(字符串)
        /// </summary>
        /// <param name="encryptString">待加密字符串</param>
        /// <returns>加密后的Base64字符串</returns>
        public string EncryptBase64String(string encryptString)
        {
            byte[] data = Encoding.UTF8.GetBytes(encryptString);
            return Convert.ToBase64String(Encrypt(data));
        }

        /// <summary>
        /// 加密(字符串)
        /// </summary>
        /// <param name="encryptString">待加密字符串</param>
        /// <returns>加密后的Hex字符串</returns>
        public string EncryptHexString(string encryptString)
        {
            byte[] data = Encoding.UTF8.GetBytes(encryptString);
            return string.Join("", Encrypt(data).Select(t => t.ToString("x2")));
        }
    }
}

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

namespace CommonLib.EncryptUtils.BaseEncrypt
{
    /// <summary>
    /// MD5加密帮助类
    /// </summary>
    public class MD5Helper
    {
        /// <summary>
        /// 构造
        /// </summary>
        public MD5Helper() { }

        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="customKey">自定义加盐Key</param>
        public MD5Helper(string customKey)
        {
            SetCustomKeyData(customKey);
        }

        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="customKeyData">自定义加盐字节数组</param>
        public MD5Helper(byte[] customKeyData)
        {
            SetCustomKeyData(customKeyData);
        }

        /// <summary>
        /// 自定义加盐Key
        /// </summary>
        private byte[] _CustomKeyData = new byte[0];

        /// <summary>
        /// 设置自定义加盐Key
        /// </summary>
        /// <param name="customKey">自定义加盐Key</param>
        public void SetCustomKeyData(string customKey)
        {
            if (string.IsNullOrWhiteSpace(customKey)) return;
            _CustomKeyData = Encoding.UTF8.GetBytes(customKey);
        }

        /// <summary>
        /// 设置自定义加盐字节数组
        /// </summary>
        /// <param name="customKeyData">自定义加盐字节数组</param>
        public void SetCustomKeyData(byte[] customKeyData)
        {
            if (customKeyData == null || customKeyData.Length == 0) return;
            _CustomKeyData = customKeyData;
        }

        /// <summary>
        /// 加密(字节数组)
        /// </summary>
        /// <param name="encryptBytes">待加密的字节数组</param>
        /// <returns>加密后的字节数组</returns>
        public byte[] Encrypt(byte[] encryptBytes)
        {
            using (MD5 md5 = MD5.Create())
            {
                return md5.ComputeHash(encryptBytes);
            }
        }

        /// <summary>
        /// 三重加密(字节数组)
        /// </summary>
        /// <param name="encryptBytes">待加密的字节数组</param>
        /// <returns>三重加密后的字节数组</returns>
        public byte[] Encrypt3(byte[] encryptBytes)
        {
            using (MD5 md5 = MD5.Create())
            {
                return md5.ComputeHash(md5.ComputeHash(md5.ComputeHash(encryptBytes)));
            }
        }

        /// <summary>
        /// 自定义加盐加密(字节数组)
        /// </summary>
        /// <param name="encryptBytes">待加密的字节数组</param>
        /// <returns>自定义加盐加密后的字节数组</returns>
        public byte[] EncryptCustom(byte[] encryptBytes)
        {
            byte[] data = new byte[encryptBytes.Length + _CustomKeyData.Length];
            Array.Copy(encryptBytes, 0, data, 0, encryptBytes.Length);
            Array.Copy(_CustomKeyData, 0, data, encryptBytes.Length, _CustomKeyData.Length);
            return Encrypt(data);
        }

        /// <summary>
        /// 自定义加盐三重加密(字节数组)
        /// </summary>
        /// <param name="encryptBytes">待加密的字节数组</param>
        /// <returns>自定义加盐三重加密后的字节数组</returns>
        public byte[] Encrypt3Custom(byte[] encryptBytes)
        {
            return EncryptCustom(EncryptCustom(EncryptCustom(encryptBytes)));
        }

        /// <summary>
        /// 加密(字符串)
        /// </summary>
        /// <param name="encryptString">待加密字符串</param>
        /// <param name="sFormat">十六进制大小写占位符</param>
        /// <returns>加密后的字符串</returns>
        public string EncryptString(string encryptString, string sFormat = "X")
        {
            byte[] data = Encoding.UTF8.GetBytes(encryptString);
            byte[] md5Data = Encrypt(data);
            return string.Join("", md5Data.Select(t => t.ToString(sFormat)));
        }
        /// <summary>
        /// 三重加密(字符串)
        /// </summary>
        /// <param name="encryptString">待加密字符串</param>
        /// <param name="sFormat">十六进制大小写占位符</param>
        /// <returns>三重加密后的字符串</returns>
        public string EncryptString3(string encryptString, string sFormat = "X")
        {
            byte[] data = Encoding.UTF8.GetBytes(encryptString);
            byte[] md5Data = Encrypt3(data);
            return string.Join("", md5Data.Select(t => t.ToString(sFormat)));
        }

        /// <summary>
        /// 自定义加盐加密(字符串)
        /// </summary>
        /// <param name="encryptString">待加密字符串</param>
        /// <param name="sFormat">十六进制大小写占位符</param>
        /// <returns>自定义加盐加密后的字符串</returns>
        public string EncryptStringCustom(string encryptString, string sFormat = "X")
        {
            byte[] data = Encoding.UTF8.GetBytes(encryptString);
            byte[] md5Data = EncryptCustom(data);
            return string.Join("", md5Data.Select(t => t.ToString(sFormat)));
        }

        /// <summary>
        /// 自定义加盐三重加密(字符串)
        /// </summary>
        /// <param name="encryptString">待加密字符串</param>
        /// <param name="sFormat">十六进制大小写占位符</param>
        /// <returns>自定义加盐三重加密后的字符串</returns>
        public string EncryptString3Custom(string encryptString, string sFormat = "X")
        {
            byte[] data = Encoding.UTF8.GetBytes(encryptString);
            byte[] md5Data = Encrypt3Custom(data);
            return string.Join("", md5Data.Select(t => t.ToString(sFormat)));
        }
    }
}

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

namespace CommonLib.EncryptUtils.BaseEncrypt
{
    /// <summary>
    /// RSA加密解密帮助类
    /// </summary>
    public class RSAHelper
    {
        /// <summary>
        /// 获取RSA私钥和公钥(xml格式)
        /// </summary>
        /// <returns>xml格式的(私钥、公钥)字符串数组</returns>
        public static string[] GetKeys()
        {
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(4096))
            {
                return new string[]
                {
                    rsa.ToXmlString(true),
                    rsa.ToXmlString(false),
                };
            }
        }


        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="privateKey">xml格式私钥(解密Key),如果没有可以为空。</param>
        /// <param name="publicKey">xml格式公钥(加密Key)</param>
        public RSAHelper(string privateKey, string publicKey)
        {
            _PrivateKey = privateKey;
            _PublicKey = publicKey;
        }

        /// <summary>
        /// xml格式私钥(解密Key)
        /// </summary>
        private readonly string _PrivateKey;

        /// <summary>
        /// xml格式公钥(加密Key)
        /// </summary>
        private readonly string _PublicKey;

        /// <summary>
        /// 加密(字节数组)
        /// </summary>
        /// <param name="encryptBytes">加密的字节数组</param>
        /// <returns>加密后的字节数组</returns>
        public byte[] Encrypt(byte[] encryptBytes)
        {
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(4096))
            {
                rsa.FromXmlString(_PublicKey);
                return rsa.Encrypt(encryptBytes, false);
            }
        }

        /// <summary>
        /// 解密(字节数组)
        /// </summary>
        /// <param name="decryptBytes">待解密的字节数组</param>
        /// <returns>解密后的字节数组</returns>
        public byte[] Decrypt(byte[] decryptBytes)
        {

            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(4096))
            {
                rsa.FromXmlString(_PrivateKey);
                return rsa.Decrypt(decryptBytes, false);
            }
        }

        /// <summary>
        /// 加密(字符串)
        /// </summary>
        /// <param name="encryptString">待加密字符串</param>
        /// <returns>加密后的字符串</returns>
        public string EncryptString(string encryptString)
        {
            byte[] data = Encoding.UTF8.GetBytes(encryptString);
            return Convert.ToBase64String(Encrypt(data));
        }

        /// <summary>
        /// 解密(字符串)
        /// </summary>
        /// <param name="decryptString">待解密字符串</param>
        /// <returns>解密后的字符串</returns>
        public string DecryptString(string decryptString)
        {
            byte[] data = Convert.FromBase64String(decryptString);
            return Encoding.UTF8.GetString(Decrypt(data));
        }

        /// <summary>
        /// 签名(字节数组)
        /// </summary>
        /// <param name="signBytes">待签名的字节数组</param>
        /// <returns>签名后的字节数组</returns>
        public byte[] Sign(byte[] signBytes)
        {
            using (SHA256 sha256 = SHA256.Create())
            {
                byte[] hashBytes = sha256.ComputeHash(signBytes);
                using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(4096))
                {
                    rsa.FromXmlString(_PrivateKey);
                    RSAPKCS1SignatureFormatter formatter = new RSAPKCS1SignatureFormatter(rsa);
                    formatter.SetHashAlgorithm("SHA256");
                    return formatter.CreateSignature(hashBytes);
                }
            }
        }

        /// <summary>
        /// 签名验证(字节数组)
        /// </summary>
        /// <param name="bytes">未签名前的字节数组</param>
        /// <param name="signBytes">签名后的字节数组</param>
        /// <returns>布尔值</returns>
        public bool SignCheck(byte[] bytes, byte[] signBytes)
        {
            using (SHA256 sha256 = SHA256.Create())
            {
                byte[] hashBytes = sha256.ComputeHash(bytes);
                using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(4096))
                {
                    rsa.FromXmlString(_PublicKey);
                    RSAPKCS1SignatureDeformatter formatter = new RSAPKCS1SignatureDeformatter(rsa);
                    formatter.SetHashAlgorithm("SHA256");
                    return formatter.VerifySignature(hashBytes, signBytes);

                }
            }
        }

        /// <summary>
        /// 签名(字符串)
        /// </summary>
        /// <param name="signString">待签名的字符串</param>
        /// <returns>签名后的字符串</returns>
        public string SignString(string signString)
        {
            byte[] data = Encoding.UTF8.GetBytes(signString);
            return Convert.ToBase64String(Sign(data));
        }

        /// <summary>
        /// 签名验证(字符串)
        /// </summary>
        /// <param name="sourString">源字符串</param>
        /// <param name="signString">签名后的字符串</param>
        /// <returns>布尔值</returns>
        public bool SignCheck(string sourString, string signString)
        {
            byte[] sourData = Encoding.UTF8.GetBytes(sourString);
            byte[] signData = Convert.FromBase64String(signString);
            return SignCheck(sourData, signData);
        }

    }
}

StringEncrypt

using CommonLib.EncryptUtils.BaseEncrypt;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CommonLib.EncryptUtils.StringEncrypt
{
    /// <summary>
    /// AES字符串加密解密实现类
    /// </summary>
    public class AESStringEncrypt : IStringEncrypt
    {
        public AESStringEncrypt()
        {
            this.aes = new AESHelper(this.key, this.iv);

        }

        private readonly string key = "taHcbdTXJsJ6Bo2vQ7CPCp9dytGzWndMSyC2QdeRJAk=";
        private readonly string iv = "E3/hvnRRwUwHmix7F5U18w==";
        private readonly AESHelper aes = null;

        public string Decrypt(string str)
        {
            return this.aes.EncryptString(str);

        }

        public string Encrypt(string str)
        {
            return this.aes.DecryptString(str);
        }
    }
}

using CommonLib.EncryptUtils.BaseEncrypt;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CommonLib.EncryptUtils.StringEncrypt
{
    /// <summary>
    /// DES字符串加密解密实现类
    /// </summary>
    public class DESStringEncrypt : IStringEncrypt
    {
        public DESStringEncrypt()
        {
            this.des = new DESHelper(this.key, this.iv);
        }
        private readonly string key = "DzsvZnubCmc=";
        private readonly string iv = "tNEDCvmu9uc=";
        private readonly DESHelper des = null;

        public string Encrypt(string str)
        {
            return this.des.EncryptString(str);
        }

        public string Decrypt(string str)
        {
            return this.des.DecryptString(str);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CommonLib.EncryptUtils.StringEncrypt
{
    /// <summary>
    /// 字符串加密解密接口
    /// </summary>
    public interface IStringEncrypt
    {
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="str">明文字符串</param>
        /// <returns>密文字符串</returns>
        string Encrypt(string str);

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="str">密文字符串</param>
        /// <returns>明文字符串</returns>
        string Decrypt(string str);
    }
}

using CommonLib.EncryptUtils.BaseEncrypt;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CommonLib.EncryptUtils.StringEncrypt
{
    /// <summary>
    /// MD5字符串加密解密实现类
    /// </summary>
    public class MD5StringEncrypt : IStringEncrypt
    {
        public MD5StringEncrypt()
        {
            md5 = new MD5Helper(key);
        }
        private readonly string key = "f5JdgfH23dsf=";
        private readonly MD5Helper md5 = null;

        public string Decrypt(string str)
        {
            throw new Exception("MD5不支持解密!");
        }

        public string Encrypt(string str)
        {
            return md5.EncryptString3Custom(str);
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值