文档章节

C# 加密解密类 DES 3DES MD5

ThinkGem
 ThinkGem
发布于 2016/07/17 16:16
字数 1219
阅读 34
收藏 0

这是我写CMIS时用到的一个加密类。

 

using System;
using System.Security.Cryptography; 
using System.IO;
using System.Data;
using System.Web;
using System.Text;
using System.Security;
namespace CMIS.Common
{
    /// <summary>
    /// 加密解密
    /// </summary>
    public class Encrypt
    {
        #region DES密钥
        /// <summary>
        /// DES密钥
        /// </summary>
        public static byte[] DESKey = new byte[] {0x52, 0xBC, 0xA1, 0x6A, 0xD5, 0x87, 0x3B, 0xE6, 0x82, 0x7A, 0x2A, 0x64, 0x3A, 0x7F, 0x32, 0xBB, 0x1B, 0x67, 0xE2, 0x5E, 0x06, 0x19, 0xB9, 0x2D, 0x68, 0xB3, 0x4F, 0xFB, 0xBF, 0xDD, 0x55 ,0xB8 }; 
        #endregion

        #region DES加密解密
        /// <summary>
        /// DES加密
        /// </summary>
        /// <param name="strSource">待加密字串</param>
        /// <param name="key">32位Key值</param>
        /// <returns>加密后的字符串</returns>
        public static string DESEncrypt(string strSource) 
        {
            return DESEncrypt(strSource, DESKey);
        }
        public static string DESEncrypt(string strSource,byte[] key)
        {
            SymmetricAlgorithm sa = Rijndael.Create();
            sa.Key = key;
            sa.Mode= CipherMode.ECB;
            sa.Padding = PaddingMode.Zeros;
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, sa.CreateEncryptor(), CryptoStreamMode.Write);
            byte[] byt = Encoding.Unicode.GetBytes(strSource);
            cs.Write(byt, 0, byt.Length);
            cs.FlushFinalBlock();
            cs.Close();
            return Convert.ToBase64String(ms.ToArray());
        }
        /// <summary>
        /// DES解密
        /// </summary>
        /// <param name="strSource">待解密的字串</param>
        /// <param name="key">32位Key值</param>
        /// <returns>解密后的字符串</returns>
        public static string DESDecrypt(string strSource) 
        {
            return DESDecrypt(strSource, DESKey);
        }
        public static string DESDecrypt(string strSource,byte[] key)
        {
            SymmetricAlgorithm sa = Rijndael.Create();
            sa.Key = key;
            sa.Mode = CipherMode.ECB;
            sa.Padding = PaddingMode.Zeros;
            ICryptoTransform ct = sa.CreateDecryptor();
            byte[] byt = Convert.FromBase64String(strSource);
            MemoryStream ms = new MemoryStream(byt);
            CryptoStream cs = new CryptoStream(ms, ct, CryptoStreamMode.Read);
            StreamReader sr = new StreamReader(cs, Encoding.Unicode);
            return sr.ReadToEnd();
        }
        #endregion

        #region 一个用hash实现的加密解密方法
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="src"></param>
        /// <returns></returns>
        public static string EncryptStrByHash(string src)   
        { 
            if (src.Length==0)
            {
                return   ""; 
            }
            byte[] HaKey=System.Text.Encoding.ASCII.GetBytes((src+"Test").ToCharArray()); 
            byte[] HaData=new byte[20]; 
            HMACSHA1 Hmac=new HMACSHA1(HaKey); 
            CryptoStream cs=new CryptoStream(Stream.Null,Hmac,CryptoStreamMode.Write); 
            try   
            { 
                cs.Write(HaData,0,HaData.Length); 
            }   
            finally   
            { 
                cs.Close(); 
            } 
            string   HaResult   =   System.Convert.ToBase64String(Hmac.Hash).Substring(0,16); 
            byte[]   RiKey   =   System.Text.Encoding.ASCII.GetBytes(HaResult.ToCharArray()); 
            byte[]   RiDataBuf   =   System.Text.Encoding.ASCII.GetBytes(src.ToCharArray()); 
            byte[]   EncodedBytes   =   {}; 
            MemoryStream   ms   =   new   MemoryStream(); 
            RijndaelManaged   rv   =   new   RijndaelManaged(); 
            cs   =   new   CryptoStream(ms,   rv.CreateEncryptor(RiKey,   RiKey),   CryptoStreamMode.Write); 
            try   
            { 
                cs.Write(RiDataBuf,   0,   RiDataBuf.Length); 
                cs.FlushFinalBlock(); 
                EncodedBytes   =   ms.ToArray(); 
            }   
            finally   
            { 
                ms.Close(); 
                cs.Close(); 
            } 
            return   HaResult+System.Convert.ToBase64String(EncodedBytes); 
        } 

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="src"></param>
        /// <returns></returns>
        public static string DecrypStrByHash(string src) 
        { 
            if   (src.Length<40)   return   ""; 
            byte[]   SrcBytes   =   System.Convert.FromBase64String(src.Substring(16)); 
            byte[]   RiKey   =   System.Text.Encoding.ASCII.GetBytes(src.Substring(0,16).ToCharArray()); 
            byte[]   InitialText   =   new   byte[SrcBytes.Length]; 
            RijndaelManaged   rv   =   new   RijndaelManaged(); 
            MemoryStream   ms   =   new   MemoryStream(SrcBytes); 
            CryptoStream   cs   =   new   CryptoStream(ms,   rv.CreateDecryptor(RiKey,   RiKey),   CryptoStreamMode.Read); 
            try   
            { 
                cs.Read(InitialText,   0,   InitialText.Length); 
            }   
            finally   
            { 
                ms.Close(); 
                cs.Close(); 
            } 
            System.Text.StringBuilder   Result   =   new   System.Text.StringBuilder(); 
            for(int   i=0;   i   <   InitialText.Length;   ++i)   if   (InitialText[i]>0)   Result.Append((char)   InitialText[i]); 
            return   Result.ToString(); 
        } 
   
        /// <summary>
        /// 对加密后的密文重新编码,如果密文长>16,则去掉前16个字符,如果长度小于16,返回空字符串
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string ReEncryptStrByHash(string   s)   
        { 
            //string e= (new Encrypt()).EncryptStrByHash(s); 
            string e= EncryptStrByHash(s); 
            return ((e.Length>16)?e.Substring(16):""); 
        }
        #endregion

        #region Md5加密,生成16位或32位,生成的密文都是大写
        /// <summary>
        /// MD5 16位加密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string Md5To16(string str)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            string pwd = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(str)), 4, 8);
            pwd = pwd.Replace("-", "");
            return pwd;
        }
  
        /// <summary>
        /// MD5 32位加密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string Md5To32(string str)
        {
            string pwd = "";
            MD5 md5 = MD5.Create();
            byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(str));
            for (int i = 0; i < s.Length; i++){
                pwd = pwd + s[i].ToString("X2");
            }
            return pwd;
        }
        #endregion

        #region 3DES加密解密
        /// <summary>
        /// 3DES加密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string Encrypt3DES(string str)
        {
            //密钥
            string sKey = "wyw308";
            //    //矢量,可为空
            string sIV = "scf521";
            //    //构造对称算法
            SymmetricAlgorithm mCSP = new TripleDESCryptoServiceProvider();

            ICryptoTransform ct;
            MemoryStream ms;
            CryptoStream cs;
            byte[] byt;
            mCSP.Key = Convert.FromBase64String(sKey);
            mCSP.IV = Convert.FromBase64String(sIV);
            mCSP.Mode = System.Security.Cryptography.CipherMode.ECB;
            mCSP.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
            ct = mCSP.CreateEncryptor(mCSP.Key, mCSP.IV);
            byt = Encoding.UTF8.GetBytes(str);
            ms = new MemoryStream();
            cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
            cs.Write(byt, 0, byt.Length);
            cs.FlushFinalBlock();
            cs.Close();
            return Convert.ToBase64String(ms.ToArray());
        }
        /// <summary>
        /// 带指定密钥和矢量的3DES加密
        /// </summary>
        /// <param name="str"></param>
        /// <param name="sKey"></param>
        /// <param name="sIV"></param>
        /// <returns></returns>
        public static string Encrypt3DES(string str,string sKey,string sIV)
        {
            SymmetricAlgorithm mCSP = new TripleDESCryptoServiceProvider();
            ICryptoTransform ct;
            MemoryStream ms;
            CryptoStream cs;
            byte[] byt;
            mCSP.Key = Convert.FromBase64String(sKey);
            mCSP.IV = Convert.FromBase64String(sIV);
            mCSP.Mode = System.Security.Cryptography.CipherMode.ECB;
            mCSP.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
            ct = mCSP.CreateEncryptor(mCSP.Key, mCSP.IV);
            byt = Encoding.UTF8.GetBytes(str);
            ms = new MemoryStream();
            cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
            cs.Write(byt, 0, byt.Length);
            cs.FlushFinalBlock();
            cs.Close();
            return Convert.ToBase64String(ms.ToArray());
        }

        /// <summary>
        /// 3DES解密
        /// </summary>
        /// <param name="Value"></param>
        /// <returns></returns>
        public static string Decrypt3DES(string Value)
        {
            string sKey = "wyw308";
            string sIV = "scf521";
            SymmetricAlgorithm mCSP = new TripleDESCryptoServiceProvider();
            ICryptoTransform ct;
            MemoryStream ms;
            CryptoStream cs;
            byte[] byt;
            mCSP.Key = Convert.FromBase64String(sKey);
            mCSP.IV = Convert.FromBase64String(sIV);
            mCSP.Mode = System.Security.Cryptography.CipherMode.ECB;
            mCSP.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
            ct = mCSP.CreateDecryptor(mCSP.Key, mCSP.IV);
            byt = Convert.FromBase64String(Value);
            ms = new MemoryStream();
            cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
            cs.Write(byt, 0, byt.Length);
            cs.FlushFinalBlock();
            cs.Close();
            return Encoding.UTF8.GetString(ms.ToArray());
        } 
        /// <summary>
        /// 带指定密钥和矢量的3DES解密
        /// </summary>
        /// <param name="Value"></param>
        /// <param name="sKey"></param>
        /// <param name="sIV"></param>
        /// <returns></returns>
        public static string Decrypt3DES(string str,string sKey,string sIV)
        {
            SymmetricAlgorithm mCSP = new TripleDESCryptoServiceProvider();
            ICryptoTransform ct;
            MemoryStream ms;
            CryptoStream cs;
            byte[] byt;
            mCSP.Key = Convert.FromBase64String(sKey);
            mCSP.IV = Convert.FromBase64String(sIV);
            mCSP.Mode = System.Security.Cryptography.CipherMode.ECB;
            mCSP.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
            ct = mCSP.CreateDecryptor(mCSP.Key, mCSP.IV);
            byt = Convert.FromBase64String(str);
            ms = new MemoryStream();
            cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
            cs.Write(byt, 0, byt.Length);
            cs.FlushFinalBlock();
            cs.Close();
            return Encoding.UTF8.GetString(ms.ToArray());
        } 
        #endregion

        #region 一个简单的加密解密方法,只支持英文
        public static string EnCryptEnStr( string str ) //倒序加1加密
        {
            byte[] by=new byte[str.Length];
            for( int i=0;
                i<=str.Length-1;
                i++ )
            {
                by[i]=( byte )( ( byte )str[i]+1 );
            }
            str="";
            for( int i=by.Length-1;
                i>=0;
                i-- )
            {
                str+=( ( char )by[i] ).ToString( );
            }
            return str;
        }
        public static string DeCryptEnStr( string str ) //顺序减1解码
        {
            byte[] by=new byte[str.Length];
            for( int i=0;
                i<=str.Length-1;
                i++ )
            {
                by[i]=( byte )( ( byte )str[i]-1 );
            }
            str="";
            for( int i=by.Length-1;
                i>=0;
                i-- )
            {
                str+=( ( char )by[i] ).ToString( );
            }
            return str;
        }
        #endregion

        #region 一个简单的加密解密方法,在上一个的基础上支持中文
        public static string EnCryptCnStr(string str)
        {
            string htext = ""; // blank text

            for ( int i = 0; i < str.Length; i++)
            {
                htext = htext + (char) (str[i] + 10 - 1 * 2);
            }
            return htext;
        }

        public static string DeCryptCnStr(string str)
        {
            string dtext = "";

            for ( int i=0; i < str.Length; i++)
            {
                dtext = dtext + (char) (str[i] - 10 + 1*2);
            }
            return dtext;
        }
        #endregion

        #region Discuz论坛Md5加密删除
        /// <summary>
        /// Discuz论坛Md5加密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string Md5(string str)
        {
            MD5 md5Hasher = MD5.Create();
            string re="";
            byte[] data = md5Hasher.ComputeHash(Encoding.UTF8.GetBytes(str+"%$#@!"));//yc
            for (int i = 0; i < data.Length; i++){
                re += data[i].ToString("x2");
            }
            return re;
        }        
        #endregion
    }
}
 

本文转载自:http://thinkgem.iteye.com/blog/724071

共有 人打赏支持
ThinkGem

ThinkGem

粉丝 1139
博文 139
码字总数 25992
作品 2
济南
架构师
私信 提问
AES加解密算法

前言 在很多项目中,对于安全性的要求是很高的,这就涉及到了各种加密,解密算法,常见的算法有MD5加密、DES加解密、字符串加解密、AES加解密等,下面来一起看一下AES加解密算法。 正文 AES(...

zt15732625878
2017/12/24
0
0
Asp.Net Core 2.0 项目实战(7)MD5加密、AES&DES对称加解密

Asp.Net Core 2.0 项目实战(1) NCMVC开源下载了 Asp.Net Core 2.0 项目实战(2)NCMVC一个基于Net Core2.0搭建的角色权限管理开发框架 Asp.Net Core 2.0 项目实战(3)NCMVC角色权限管理前...

郑州-在路上
2018/04/26
0
0
android-crypt-helper

为防止网络传输过程中重要数据被篡改,客户端与服务端都会对发出的数据签名或加密,对收到的数据验签或解密。签名可能用到MD5,SHA1,加解密可能用到3DES,AES,RSA等。加密数据传输一般以字...

panxw
2014/08/19
1K
0
Java中常用的加密方法(JDK) (转)

加密,是以某种特殊的算法改变原有的信息数据,使得未授权的用户即使获得了已加密的信息,但因不知解密的方法,仍然无法了解信息的内容。大体上分为双向加密和单向加密,而双向加密又分为对称...

hulubo
2012/04/08
0
3
网络安全&加密方式的笔记&json序列化

1.网络安全:(1)网络中传输数据都会被监控到(2)本地存储也是不安全的 因为会被越狱破解 2.任何加密解密的操作就是对二进制进行操作 //加密-指定base64编码的方式0 //解密-忽略未知的字...

KevinEmily
2016/02/23
100
0

没有更多内容

加载失败,请刷新页面

加载更多

数据库技术-Mysql主从复制与数据备份

数据库技术-Mysql 主从复制的原理: MySQL中数据复制的基础是二进制日志文件(binary log file)。一台MySQL数据库一旦启用二进制日志后,其作为master,它的数据库中所有操作都会以“事件”...

须臾之余
昨天
12
0
Git远程仓库——GitHub的使用(一)

Git远程仓库——GitHub的使用(一) 一 、 Git远程仓库 由于你的本地仓库和GitHub仓库之间的传输是通过SSH加密的,所以需要一下设置: 步骤一、 创建SSH key 在用户主目录下,看看有没有.ss...

lwenhao
昨天
2
0
SpringBoot 整合

springBoot 整合模板引擎 SpringBoot 整合Mybatis SpringBoot 整合redis SpringBoot 整合定时任务 SpringBoot 整合拦截器...

细节探索者
昨天
0
0
第二个JAVA应用

第二个JAVA应用 方法一:配置文件: # cd /usr/local/tomcat/conf/# vim server.xml</Host> <Host name="www.wangzb.cc" appBase="/data/wwwroot/www.wangzb.cc" //引用所......

wzb88
昨天
0
0
2019年阿里Java面试必问:JVM与性能优化+Redis+设计模式+分布式

前言 一年之计在于春 金三银四已经要到来,2019的新的开始,作为一个开发人员,你是否面上了自己理想的公司,薪资达到心中理想的高度? 面试:如果不准备充分的面试,完全是浪费时间,更是对...

火力全開
昨天
15
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部