首页 > 其他分享 >加解密EncryptHelpers

加解密EncryptHelpers

时间:2022-10-28 18:23:31浏览次数:42  
标签:return string keys 加解密 content EncryptHelpers encode new

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

namespace EncryptTools
{
    /// <summary>
    /// 加解密帮助类
    /// </summary>
    public class EncryptHelpers
    {
        //定义一个用于保存静态变量的实例
        private static EncryptHelpers instance = null;
        //定义一个保证线程同步的标识
        private static readonly object locker = new object();
        //构造函数为私有,使外界不能创建该类的实例
        private EncryptHelpers() { }
        public static EncryptHelpers Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (locker)
                    {
                        if (instance == null) instance = new EncryptHelpers();
                    }
                }
                return instance;
            }
        }

        private byte[] Keys = new byte[]
		{
			18, 
			66, 
			88, 
			99, 
			119, 
			121, 
			212, 
			239
		};
        /// <summary>
        /// 秘钥
        /// </summary>
        private string EncryptKey = "SWGSUNWG";

        #region MD5加密
        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="content">需要加密的字符串</param>
        /// <param name="encode">字符的编码,默认null=UTF8Encoding</param>
        /// <returns></returns>
        public string MD5Encrypt(string content, Encoding encode = null)
        {
            if (string.IsNullOrEmpty(content)) return string.Empty;
            if (encode == null) encode = new UTF8Encoding();

            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] t = md5.ComputeHash(encode.GetBytes(content));
            StringBuilder sb = new StringBuilder(32);
            for (int i = 0; i < t.Length; i++)
                sb.Append(t[i].ToString("x").PadLeft(2, '0'));
            return sb.ToString();
        }

        /// <summary>
        /// MD5加密(返回16位加密串)
        /// </summary>
        /// <param name="content">需要加密的字符串</param>
        /// <param name="encode">字符的编码,默认null=UTF8Encoding</param>
        /// <returns></returns>
        public string MD5Encrypt16(string content, Encoding encode = null)
        {
            if (string.IsNullOrEmpty(content)) return string.Empty;
            if (encode == null) encode = new UTF8Encoding();
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            string result = BitConverter.ToString(md5.ComputeHash(encode.GetBytes(content)), 4, 8);
            result = result.Replace("-", "");
            return result;
        }
        #endregion

        #region Des 加密、解密
        /// <summary> 
        /// 加密数据 
        /// 如秘钥为空 则返回原文
        /// </summary> 
        /// <param name="content">加密前文本</param> 
        /// <param name="desKey">密匙</param> 
        /// <returns></returns> 
        public string DesEncrypt(string content, string desKey)
        {
            try
            {
                if (string.IsNullOrEmpty(desKey)) return content;

                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                des.Mode = CipherMode.ECB;
                var keys = new byte[8];
                if (desKey.Length < 8)
                {
                    var tmpkeys = System.Text.Encoding.UTF8.GetBytes(desKey);
                    for (int i = 0; i < keys.Length; i++)
                    {
                        if (tmpkeys.Length > i)
                            keys[i] = tmpkeys[i];
                        else
                            keys[i] = 0;
                    }
                }
                else keys = System.Text.Encoding.UTF8.GetBytes(desKey.Substring(0, 8));

                des.Key = keys;
                des.IV = des.Key;
                byte[] inputByteArray = System.Text.Encoding.UTF8.GetBytes(content);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                StringBuilder sb = new StringBuilder();
                foreach (var item in ms.ToArray())
                {
                    sb.Append(item.ToString());
                    sb.Append("_");
                }

                if (sb.Length > 0) sb = sb.Remove(sb.Length - 1, 1);
                return sb.ToString();
            }
            catch (System.Exception e)
            {
                return content;
            }
        }

        /// <summary> 
        /// 解密数据 
        /// 如秘钥为空 则返回原文
        /// </summary> 
        /// <param name="content">密文</param> 
        /// <param name="desKey">密匙</param> 
        /// <returns>解密失败返回空字符串</returns> 
        public string DesDecrypt(string content, string desKey)
        {
            try
            {
                if (string.IsNullOrEmpty(desKey)) return content;

                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                des.Mode = CipherMode.ECB;
                var keys = new byte[8];
                if (desKey.Length < 8)
                {
                    var tmpkeys = System.Text.Encoding.UTF8.GetBytes(desKey);
                    for (int i = 0; i < keys.Length; i++)
                    {
                        if (tmpkeys.Length > i)
                            keys[i] = tmpkeys[i];
                        else
                            keys[i] = 0;
                    }
                }
                else keys = System.Text.Encoding.UTF8.GetBytes(desKey.Substring(0, 8));

                des.Key = keys;
                des.IV = des.Key;
                var data = content.Split('_');
                byte[] inputByteArray = new byte[data.Length]; ;
                for (int i = 0; i < data.Length; i++)
                {
                    inputByteArray[i] = Convert.ToByte(data[i]);
                }
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                System.Text.Encoding encoding = new System.Text.UTF8Encoding();
                return encoding.GetString(ms.ToArray());
            }
            catch (System.Exception e)
            {
                return "";
            }
        }

        /// <summary> 
        /// 加密数据 
        /// </summary> 
        /// <param name="encryptString">加密前文本</param> 
        /// <returns></returns> 
        public string DesEncrypt(string encryptString)
        {
            string result;
            try
            {
                byte[] bytes = Encoding.UTF8.GetBytes(EncryptKey.Substring(0, 8));
                byte[] keys = Keys;
                byte[] bytes2 = Encoding.UTF8.GetBytes(encryptString);
                DESCryptoServiceProvider dESCryptoServiceProvider = new DESCryptoServiceProvider();
                MemoryStream memoryStream = new MemoryStream();
                CryptoStream cryptoStream = new CryptoStream(memoryStream,
                    dESCryptoServiceProvider.CreateEncryptor(bytes, keys), CryptoStreamMode.Write);
                cryptoStream.Write(bytes2, 0, bytes2.Length);
                cryptoStream.FlushFinalBlock();
                result = Convert.ToBase64String(memoryStream.ToArray());
            }
            catch
            {
                result = encryptString;
            }
            return result;
        }

        /// <summary> 
        /// 解密数据 
        /// </summary> 
        /// <param name="decryptString">密文</param> 
        /// <returns>解密失败返回空字符串</returns> 
        public string DesDecrypt(string decryptString)
        {
            string result;
            try
            {
                byte[] bytes = Encoding.UTF8.GetBytes(EncryptKey);
                byte[] keys = Keys;
                byte[] array = Convert.FromBase64String(decryptString);
                DESCryptoServiceProvider dESCryptoServiceProvider = new DESCryptoServiceProvider();
                MemoryStream memoryStream = new MemoryStream();
                CryptoStream cryptoStream = new CryptoStream(memoryStream,
                    dESCryptoServiceProvider.CreateDecryptor(bytes, keys), CryptoStreamMode.Write);
                cryptoStream.Write(array, 0, array.Length);
                cryptoStream.FlushFinalBlock();
                result = Encoding.UTF8.GetString(memoryStream.ToArray());
            }
            catch
            {
                result = decryptString;
            }
            return result;
        }

        #endregion

        #region Base64加密解密
        /// <summary>
        /// Base64加密
        /// </summary>
        /// <param name="content">需要加密的字符串</param>
        /// <param name="encode">字符的编码,默认null=UTF8Encoding</param>
        /// <returns></returns>
        public string Base64Encrypt(string content, Encoding encode = null)
        {
            if (encode == null) encode = new UTF8Encoding();

            return Convert.ToBase64String(encode.GetBytes(content));
        }

        /// <summary>
        /// Base64解密
        /// </summary>
        /// <param name="content">需要解密的字符串</param>
        /// <param name="encode">字符的编码,默认null=UTF8Encoding</param>
        /// <returns></returns>
        public string Base64Decrypt(string content, Encoding encode = null)
        {
            if (encode == null) encode = new UTF8Encoding();

            return encode.GetString(Convert.FromBase64String(content));
        }
        #endregion

    }
}

  

标签:return,string,keys,加解密,content,EncryptHelpers,encode,new
From: https://www.cnblogs.com/YYkun/p/16837005.html

相关文章

  • 加解密EncryptUtils
    usingSystem;usingSystem.Collections.Generic;usingSystem.IO;usingSystem.Linq;usingSystem.Security.Cryptography;usingSystem.Text;namespaceZB.Queue......
  • RSA 加解密
    依赖<dependency><groupId>commons-codec</groupId><artifactId>commons-codec</artifactId></dependency>代码importorg.ap......
  • AES 加解密
    依赖<dependency><groupId>commons-codec</groupId><artifactId>commons-codec</artifactId></dependency>代码importorg.apa......
  • 基于Spring AOP切面实现请求入参出参加解密
    1.Mavne导入加密解密所需的依赖<dependency><groupId>org.apache.commons</groupId><artifactId>commons-io</artifactId><version>1.3.2</version></dep......
  • springboot使用自定义注解实现加解密及脱敏
    原文链接: https://www.yisu.com/zixun/622633.html这篇文章主要介绍springboot中如何使用自定义注解实现加解密及脱敏方式,文中介绍的非常详细,具有一定的参考价值,感兴趣......
  • OS进程取样器调用python3脚本处理jmeter接口加解密,sign鉴权
    1、jmeter脚本编写添加登录请求提取token    通过json提取器提取登录后token值,并设置为全局【方便后续夸线程调用token】    2、在需要sign鉴权,加解......
  • Java加解密-SM4国密算法
    SM4国密算法简介SM4依赖包SM4类SM4_Context类SecuritySM4类=================================== SM4国密算法简介与DES和AES算法相似,国密SM4算法是一种分组加密......
  • 加解密模式之CBC模式和ECB模式解读
    1.CBC模式CBC模式的全称:CipherBlockChaining模式(密文分组链接模式),之所以叫这个名字,是因为密文分组像链条一样互相连接在一起。在CBC模式中,首先将明文分组和一个密文......
  • SpringCloud Gateway API接口加解密
    接口范围所有GET请求白名单除外body体是application_json和application_json_utf8的POST请求白名单除外POSTurl传参也支持白名单除外启用禁用/版本后端提......
  • 【Springboot之切面编程】注解实现敏感字段加解密
    当你的项目如果不允许明文存储敏感数据(例如身份证号、银行卡号,手机号等),那么每次存之前都要先将相关敏感字段数据加密、读取出来都要将相应敏感字段的数据解密,这种方式低效......