开发者论坛

 找回密码
 注册 (请使用非IE浏览器)
查看: 3778|回复: 1

分享一个自己总结的数据加密类

[复制链接]

0

精华

10

贡献

38

赞扬

实习版主

帖子
18
软币
158
在线时间
10 小时
注册时间
2013-9-30
发表于 2014-5-12 14:02:10 | 显示全部楼层 |阅读模式
[C#] 纯文本查看 复制代码
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Web.Security;

namespace OIFrameWork.Common
{
    public class EncryptString
    {
        private static EncryptString _instance;
        private  static  readonly  object EncryptLock=new object();

        public static EncryptString GetInstance()
        {
            if (_instance != null) return _instance;
            lock (EncryptLock)
            {
                return _instance ?? (_instance = new EncryptString());
            }
        }

        #region "方法主体"

        /// <summary>
        ///  加密字符,防止敏感信息外泄.
        /// </summary>
        /// <param name="str">加密字符串</param>
        /// <returns></returns>
        public string StringEncodeBase(string str)
        {
            var strResult = "";
            if (!string.IsNullOrEmpty(str))
            {
                strResult = Convert.ToBase64String(Encoding.Default.GetBytes(str));
            }
            return strResult;
        }

        /// <summary>
        /// 解密字符,防止敏感信息外泄.
        /// </summary>
        /// <param name="str">解密字符串</param>
        /// <returns></returns>
        public string StringDecodeBase(string str)
        {
            var strResult = "";
            if (!string.IsNullOrEmpty(str))
            {
                strResult = Encoding.Default.GetString(Convert.FromBase64String(str));
            }
            return strResult;
        }

        /// <summary>
        /// 用到了GenerateSalt和EncodePassword方法,这两个方法用于完成salt值的生成和密码的加salt散列
        /// </summary>
        /// <param name="password"></param>
        /// <param name="salt"></param>
        /// <returns></returns>
        public string EncodeString(string password, string salt)
        {
            var src = Encoding.Unicode.GetBytes(password);
            var saltbuf = Convert.FromBase64String(salt);
            var dst = new byte[saltbuf.Length + src.Length];
            byte[] inArray = null;
            Buffer.BlockCopy(saltbuf, 0, dst, 0, saltbuf.Length);
            Buffer.BlockCopy(src, 0, dst, saltbuf.Length, src.Length);
            var algorithm = HashAlgorithm.Create("SHA1");
            if (algorithm != null) inArray = algorithm.ComputeHash(dst);
            return inArray == null ? string.Empty : Convert.ToBase64String(inArray);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public string GenerateSalt()
        {
            var data = new byte[0x10];
            new RNGCryptoServiceProvider().GetBytes(data);
            return Convert.ToBase64String(data);
        }

        /// <summary>
        /// MD5加密字符串,返回8\16位和32位两种
        /// </summary>
        /// <param name="str">需要加密的字符串</param>
        /// <param name="mType">加密返回的长度类型 8,16,32</param>
        /// <returns>返回加密后的字符串</returns>
        public string Md5String(string str, EncryptType  mType)
        {
            var encyString = string.Empty;
            switch (mType)
            {
                case EncryptType.Eight:
                    var hashPasswordForStoringInConfigFile = FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5");
                    if (hashPasswordForStoringInConfigFile != null)
                        encyString = hashPasswordForStoringInConfigFile.Substring(8, 8);
                    break;
                case EncryptType.Sixteen:
                    var passwordForStoringInConfigFile = FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5");
                    if (passwordForStoringInConfigFile != null)
                        encyString = passwordForStoringInConfigFile.Substring(8, 16);
                    break;
                case EncryptType.ThrityTwo:
                    encyString = FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5");
                    break;
            }
            return encyString;
        }

        /// <summary>
        /// 3des加密函数(ECB加密模式,PaddingMode.PKCS7,无IV)
        /// </summary>
        /// <param name="encryptValue">加密字符</param>
        /// <param name="key">加密key(24字符)</param>
        /// <returns>加密后Base64字符</returns>
        public string DesEncrypt(string encryptValue, string key)
        {
            var des3 = SymmetricAlgorithm.Create("OpenIdearDes");
            des3.Mode = CipherMode.ECB;
            des3.Key = Encoding.UTF8.GetBytes(StringFunction.GetInstance().SplitStringLen(key, 24, '0'));
            des3.Padding = PaddingMode.PKCS7;

            var ct = des3.CreateEncryptor();

            var byt = Encoding.UTF8.GetBytes(encryptValue);

            var ms = new MemoryStream();
            var cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
            try
            {
                cs.Write(byt, 0, byt.Length);
                cs.FlushFinalBlock();
                return Convert.ToBase64String(ms.ToArray());
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
            finally
            {
                cs.Close();
                cs.Dispose();
                ms.Close();
                ms.Dispose();
                des3.Clear();
                ct.Dispose();
            }
        }

        #region "3des解密字符串"
        /// <summary>
        /// 3des解密函数(ECB加密模式,PaddingMode.PKCS7,无IV)
        /// </summary>
        /// <param name="decryptString">解密字符</param>
        /// <param name="key">解密key(24字符)</param>
        /// <returns>解密后字符</returns>
        public string DecryptString(string decryptString, string key)
        {
            var des3 = SymmetricAlgorithm.Create("OpenIdearDes");
            des3.Mode = CipherMode.ECB;
            des3.Key = Encoding.UTF8.GetBytes(StringFunction.GetInstance().SplitStringLen(key, 24, '0'));
            des3.Padding = PaddingMode.PKCS7;
            var ct = des3.CreateDecryptor();
            var byt = Convert.FromBase64String(decryptString);
            var ms = new MemoryStream();
            var cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
            try
            {
                cs.Write(byt, 0, byt.Length);
                cs.FlushFinalBlock();
                return Encoding.UTF8.GetString(ms.ToArray());
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
            finally
            {
                ms.Close();
                cs.Close();
                ms.Dispose();
                cs.Dispose();
                ct.Dispose();
                des3.Clear();
            }
        }
        #endregion
        #endregion

        public enum EncryptType
        {
            /// <summary>
            /// 8位密码
            /// </summary>
            Eight,

            /// <summary>
            /// 16位加密
            /// </summary>
            Sixteen,

            /// <summary>
            /// 32位加密
            /// </summary>
            ThrityTwo
        }
    }
}

评分

参与人数 2赞扬 +2 收起 理由
maple + 1 感谢分享
seamone + 1 很给力

查看全部评分

回复

使用道具 举报

Archiver|手机版|小黑屋|开发者网 ( 苏ICP备08004430号-2 )
版权所有:南京韵文教育信息咨询有限公司

GMT+8, 2024-12-22 15:14

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表