加密解密大汇总

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了加密解密大汇总相关的知识,希望对你有一定的参考价值。

 在项目开发中,出于系统安全考虑,我们总会想到使用加密解密进行处理。首先保证的一点就是数据被窃取后,不能使其正常阅读。其次,就是防止接口随意调用。 (PS:鄙人目前就想到了这两点好处,如果还有什么优点,欢迎给位补充o(^▽^)o)

 接下来就说几个常用的加密算法:DES加密算法,AES加密算法,RSA加密算法,Base64加密算法,MD5加密算法,SHA1加密算法

1.DES加密算法

加密方式---- 使用异或,置换,代换,移位四种基本运算进行16轮循环加密而成。

共分为一般加密和三重加密>>

DES一般加密解密代码实现:

技术分享
  #region ========加密========

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="Text"></param>
        /// <returns></returns>
        public static string Encrypt(string Text)
        {
            return Encrypt(Text, "DTcms");
        }
        /// <summary> 
        /// 加密数据 
        /// </summary> 
        /// <param name="Text"></param> 
        /// <param name="sKey"></param> 
        /// <returns></returns> 
        public static string Encrypt(string Text, string sKey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray;
            inputByteArray = Encoding.Default.GetBytes(Text);
            des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            StringBuilder ret = new StringBuilder();
            foreach (byte b in ms.ToArray())
            {
                ret.AppendFormat("{0:X2}", b);
            }
            return ret.ToString();
        }

        #endregion

        #region ========解密========

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="Text"></param>
        /// <returns></returns>
        public static string Decrypt(string Text)
        {
            return Decrypt(Text, "DTcms");
        }
        /// <summary> 
        /// 解密数据 
        /// </summary> 
        /// <param name="Text"></param> 
        /// <param name="sKey"></param> 
        /// <returns></returns> 
        public static string Decrypt(string Text, string sKey)
        {
            try
            {
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                int len;
                len = Text.Length / 2;
                byte[] inputByteArray = new byte[len];
                int x, i;
                for (x = 0; x < len; x++)
                {
                    i = Convert.ToInt32(Text.Substring(x * 2, 2), 16);
                    inputByteArray[x] = (byte)i;
                }
                des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
                des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").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();
                return Encoding.Default.GetString(ms.ToArray());
            }
            catch
            {
                return "";
            }

        }

        #endregion
View Code

3DES(三重DES加密)实现

技术分享
    #region======加密==========
        public static string DES3Encrypt(string Text)
        {
            return DES3Encrypt(Text, "DTcms");
        }

        public static string DES3Encrypt(string strString, string strKey)
        {
            TripleDESCryptoServiceProvider DES = new TripleDESCryptoServiceProvider();
            MD5CryptoServiceProvider hashMD5 = new MD5CryptoServiceProvider();
            DES.Key = hashMD5.ComputeHash(Encoding.Default.GetBytes(strKey));
            DES.Mode = CipherMode.ECB; ICryptoTransform DESEncrypt = DES.CreateEncryptor();
            byte[] Buffer = Encoding.Default.GetBytes(strString);
            return Convert.ToBase64String(DESEncrypt.TransformFinalBlock(Buffer, 0, Buffer.Length));
        }

        #endregion
        #region======解密===========
        public static string DES3Decrypt(string Text)
        {
            return DES3Decrypt(Text, "DTcms");
        }

        public static string DES3Decrypt(string strString, string strKey)
        {
            TripleDESCryptoServiceProvider DES = new TripleDESCryptoServiceProvider();
            MD5CryptoServiceProvider hashMD5 = new MD5CryptoServiceProvider();
            DES.Key = hashMD5.ComputeHash(Encoding.Default.GetBytes(strKey));

            DES.Mode = CipherMode.ECB; ICryptoTransform DESDecrypt = DES.CreateDecryptor();

            string result = "";
            try
            {
                byte[] Buffer = Convert.FromBase64String(strString);
                result = Encoding.Default.GetString(DESDecrypt.TransformFinalBlock(Buffer, 0, Buffer.Length));
            }
            catch (System.Exception e)
            {
                throw (new System.Exception("null", e));
            }
            return result;

        }
        #endregion
View Code

2.AES加密实现

这个代替了上面的DES,称为高级加密标准

加密方式---1、密钥扩展(KeyExpansion),2、初始轮(Initial Round),3、重复轮(Rounds),每一轮又包括:SubBytes、ShiftRows、MixColumns、AddRoundKey,4、最终轮(Final Round),最终轮没有MixColumns。

根据参数分为三种>>

参数是byte[]类型的:

技术分享
#region  
  
       /// <summary>  
       /// AES加密  
       /// </summary>  
       /// <param name="Data">被加密的明文</param>  
       /// <param name="Key">密钥</param>  
       /// <param name="Vector">向量</param>  
       /// <returns>密文</returns>  
       public static Byte[] AESEncrypt(Byte[] Data, String Key, String Vector)  
       {  
           Byte[] bKey = new Byte[32];  
           Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length);  
           Byte[] bVector = new Byte[16];  
           Array.Copy(Encoding.UTF8.GetBytes(Vector.PadRight(bVector.Length)), bVector, bVector.Length);  
           Byte[] Cryptograph = null; // 加密后的密文  
           Rijndael Aes = Rijndael.Create();  
           try  
           {  
               // 开辟一块内存流  
               using (MemoryStream Memory = new MemoryStream())  
               {  
                   // 把内存流对象包装成加密流对象  
                   using (CryptoStream Encryptor = new CryptoStream(Memory,  
                    Aes.CreateEncryptor(bKey, bVector),  
                    CryptoStreamMode.Write))  
                   {  
                       // 明文数据写入加密流  
                       Encryptor.Write(Data, 0, Data.Length);  
                       Encryptor.FlushFinalBlock();  
  
                       Cryptograph = Memory.ToArray();  
                   }  
               }  
           }  
           catch  
           {  
               Cryptograph = null;  
           }  
           return Cryptograph;  
       }  
  
       /// <summary>  
       /// AES解密  
       /// </summary>  
       /// <param name="Data">被解密的密文</param>  
       /// <param name="Key">密钥</param>  
       /// <param name="Vector">向量</param>  
       /// <returns>明文</returns>  
       public static Byte[] AESDecrypt(Byte[] Data, String Key, String Vector)  
       {  
           Byte[] bKey = new Byte[32];  
           Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length);  
           Byte[] bVector = new Byte[16];  
           Array.Copy(Encoding.UTF8.GetBytes(Vector.PadRight(bVector.Length)), bVector, bVector.Length);  
  
           Byte[] original = null; // 解密后的明文  
  
           Rijndael Aes = Rijndael.Create();  
           try  
           {  
               // 开辟一块内存流,存储密文  
               using (MemoryStream Memory = new MemoryStream(Data))  
               {  
                   // 把内存流对象包装成加密流对象  
                   using (CryptoStream Decryptor = new CryptoStream(Memory,  
                   Aes.CreateDecryptor(bKey, bVector),  
                   CryptoStreamMode.Read))  
                   {  
                       // 明文存储区  
                       using (MemoryStream originalMemory = new MemoryStream())  
                       {  
                           Byte[] Buffer = new Byte[1024];  
                           Int32 readBytes = 0;  
                           while ((readBytes = Decryptor.Read(Buffer, 0, Buffer.Length)) > 0)  
                           {  
                               originalMemory.Write(Buffer, 0, readBytes);  
                           }  
  
                           original = originalMemory.ToArray();  
                       }  
                   }  
               }  
           }  
           catch  
           {  
               original = null;  
           }  
           return original;  
       }  
 
       #endregion   
View Code

参数是string类型的:

技术分享
#region  
  
       /// <summary>  
       /// 获取密钥  
       /// </summary>  
       private static string Key  
       {  
           get { return @")O[NB]6,YF}+efcaj{+oESb9d8>Z‘e9M"; }  
       }  
  
       /// <summary>  
       /// 获取向量  
       /// </summary>  
       private static string IV  
       {  
           get { return @"L+\~f4,Ir)b$=pkf"; }  
       }  
  
       /// <summary>  
       /// AES加密  
       /// </summary>  
       /// <param name="plainStr">明文字符串</param>  
       /// <returns>密文</returns>  
       public static string AESEncrypt(string plainStr)  
       {  
           byte[] bKey = Encoding.UTF8.GetBytes(Key);  
           byte[] bIV = Encoding.UTF8.GetBytes(IV);  
           byte[] byteArray = Encoding.UTF8.GetBytes(plainStr);  
  
           string encrypt = null;  
           Rijndael aes = Rijndael.Create();  
           using (MemoryStream mStream = new MemoryStream())  
           {  
               using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateEncryptor(bKey, bIV), CryptoStreamMode.Write))  
               {  
                   cStream.Write(byteArray, 0, byteArray.Length);  
                   cStream.FlushFinalBlock();  
                   encrypt = Convert.ToBase64String(mStream.ToArray());  
               }  
           }  
           aes.Clear();  
           return encrypt;  
       }  
  
       /// <summary>  
       /// AES加密  
       /// </summary>  
       /// <param name="plainStr">明文字符串</param>  
       /// <param name="returnNull">加密失败时是否返回 null,false 返回 String.Empty</param>  
       /// <returns>密文</returns>  
       public static string AESEncrypt(string plainStr, bool returnNull)  
       {  
           string encrypt = AESEncrypt(plainStr);  
           return returnNull ? encrypt : (encrypt == null ? String.Empty : encrypt);  
       }  
  
       /// <summary>  
       /// AES解密  
       /// </summary>  
       /// <param name="encryptStr">密文字符串</param>  
       /// <returns>明文</returns>  
       public static string AESDecrypt(string encryptStr)  
       {  
           byte[] bKey = Encoding.UTF8.GetBytes(Key);  
           byte[] bIV = Encoding.UTF8.GetBytes(IV);  
           byte[] byteArray = Convert.FromBase64String(encryptStr);  
  
           string decrypt = null;  
           Rijndael aes = Rijndael.Create();  
           using (MemoryStream mStream = new MemoryStream())  
           {  
               using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateDecryptor(bKey, bIV), CryptoStreamMode.Write))  
               {  
                   cStream.Write(byteArray, 0, byteArray.Length);  
                   cStream.FlushFinalBlock();  
                   decrypt = Encoding.UTF8.GetString(mStream.ToArray());  
               }  
           }  
           aes.Clear();  
           return decrypt;  
       }  
  
       /// <summary>  
       /// AES解密  
       /// </summary>  
       /// <param name="encryptStr">密文字符串</param>  
       /// <param name="returnNull">解密失败时是否返回 null,false 返回 String.Empty</param>  
       /// <returns>明文</returns>  
       public static string AESDecrypt(string encryptStr, bool returnNull)  
       {  
           string decrypt = AESDecrypt(encryptStr);  
           return returnNull ? decrypt : (decrypt == null ? String.Empty : decrypt);  
       }  
 
 
       #endregion  
View Code

256位AES加密算法,参数是string类型的:

技术分享
#region  
  
       /// <summary>  
       /// 256位AES加密  
       /// </summary>  
       /// <param name="toEncrypt"></param>  
       /// <returns></returns>  
       public static string Encrypt(string toEncrypt)  
       {  
           // 256-AES key      
           byte[] keyArray = UTF8Encoding.UTF8.GetBytes("12345678901234567890123456789012");  
           byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);  
  
           RijndaelManaged rDel = new RijndaelManaged();  
           rDel.Key = keyArray;  
           rDel.Mode = CipherMode.ECB;  
           rDel.Padding = PaddingMode.PKCS7;  
  
           ICryptoTransform cTransform = rDel.CreateEncryptor();  
           byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);  
  
           return Convert.ToBase64String(resultArray, 0, resultArray.Length);  
       }  
  
       /// <summary>  
       /// 256位AES解密  
       /// </summary>  
       /// <param name="toDecrypt"></param>  
       /// <returns></returns>  
       public static string Decrypt(string toDecrypt)  
       {  
           // 256-AES key      
           byte[] keyArray = UTF8Encoding.UTF8.GetBytes("12345678901234567890123456789012");  
           byte[] toEncryptArray = Convert.FromBase64String(toDecrypt);  
  
           RijndaelManaged rDel = new RijndaelManaged();  
           rDel.Key = keyArray;  
           rDel.Mode = CipherMode.ECB;  
           rDel.Padding = PaddingMode.PKCS7;  
  
           ICryptoTransform cTransform = rDel.CreateDecryptor();  
           byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);  
  
           return UTF8Encoding.UTF8.GetString(resultArray);  
       }  
 
       #endregion  
View Code

 3.RSA加密实现

RSA是种非对称加密算法,它比同样级别的对称密码算法要慢1000倍左右。所以一般只用于少量数据加密。

 

以上是关于加密解密大汇总的主要内容,如果未能解决你的问题,请参考以下文章

CDH大数据集群安全风险汇总

VSCode自定义代码片段13——Vue的状态大管家

VSCode自定义代码片段13——Vue的状态大管家

VSCode自定义代码片段13——Vue的状态大管家

解密体育背后AI黑科技:花样滑冰动作识别多模视频分类和精彩片段剪辑

解密双十一618电商大促数据大屏指标实现原理