常用加密與解密算法示例代碼

一.System.Security.Cryptography 命名空間

System.Security.Cryptography 命名空間提供加密服務,包括安全編碼和解碼的數據,以及許多其他操作,如哈希、 隨機數字生成和消息身份驗證。

Microsoft官方網址:https://msdn.microsoft.com/zh-cn/library/system.security.cryptography(v=vs.110).aspx

其中提供了des加密解密算法、HMAC、HMACSHA1、MD5、RSA 、SHA1等算法基礎類。

二.部分算法代碼介紹

1.單向加密--只有加密,沒有解密。

1.1.MD5加密

參考代碼:

    private string GetMD5(string text)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] data = md5.ComputeHash(Encoding.UTF8.GetBytes(text));
            md5.Clear();
            StringBuilder str = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                str.Append(data[i].ToString("X").PadLeft(2, '0'));
            }
            return str.ToString();
        }

2.雙向加密--既有加密又可以解密

2.1.對稱性加密算法--使用提前商定好的密鑰進行加密以及解密

2.1.1.DES加密

方法一:

        /// <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();
        }

方法二:

        /// <summary>
        /// DES ECB模式加密
        /// </summary>
        /// <param name="key">密鑰</param>
        /// <param name="iv">IV(當模式爲ECB時,IV無用)</param>
        /// <param name="str">明文的byte數組</param>
        /// <returns>密文的byte數組</returns>
        private  string DesEncodeECB(string skey, string sdata)
        {
            try
            {
                string encryptKey = "";
                if (skey.Length >= 8)
                {
                    encryptKey = skey.Substring(0, 8);
                }
                else
                {
                    encryptKey = skey;
                }
                byte[] key = Encoding.Default.GetBytes(encryptKey);

                byte[] data = Encoding.Default.GetBytes(sdata);
                // Create a MemoryStream.
                MemoryStream mStream = new MemoryStream();

                DESCryptoServiceProvider tdsp = new DESCryptoServiceProvider();

                tdsp.Mode = CipherMode.ECB;
                tdsp.Padding = PaddingMode.PKCS7;
                CryptoStream cStream = new CryptoStream(mStream,
                    tdsp.CreateEncryptor(key, key),
                    CryptoStreamMode.Write);


                cStream.Write(data, 0, data.Length);
                cStream.FlushFinalBlock();
                StringBuilder ret = new StringBuilder();
                foreach (byte b in mStream.ToArray())
                {
                    ret.AppendFormat("{0:X2}", b);
                }
                cStream.Close();
                mStream.Close();
                return ret.ToString();
            }
            catch (CryptographicException e)
            {
                stCommon.Errors.Logs("皇包車接口中,des加密出現異常!----" + e.StackTrace + e.Message);
                return null;
            }

        }


2.1.2.DES解密

方法一:

        /// <summary>
        /// 解密數據
        /// </summary>
        /// <param name="Text"></param>
        /// <param name="sKey"></param>
        /// <returns></returns>
        public static string Decrypt(string Text, string sKey)
        {
            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());
        }

方法二:

        /// <summary>
        /// DES ECB模式解密
        /// </summary>
        /// <param name="key">密鑰</param>
        /// <param name="iv">IV(當模式爲ECB時,IV無用)</param>
        /// <param name="str">密文的byte數組</param>
        /// <returns>明文的byte數組</returns>
        private  string DesDecodeECB(string skey, string sdata)
        {
            try
            {
                string encryptKey = skey.Substring(0, 8);
                byte[] key = Encoding.Default.GetBytes(encryptKey);
                byte[] data = Encoding.Default.GetBytes(sdata);

                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                int len;
                len = sdata.Length / 2;
                byte[] inputByteArray = new byte[len];
                int x, i;
                for (x = 0; x < len; x++)
                {
                    i = Convert.ToInt32(sdata.Substring(x * 2, 2), 16);
                    inputByteArray[x] = (byte)i;
                }
                des.Mode = CipherMode.ECB;
                des.Padding = PaddingMode.PKCS7;

                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(key, key), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();

                return Encoding.Default.GetString(ms.ToArray());

            }
            catch (CryptographicException e)
            {
                stCommon.Errors.Logs("皇包車接口中,des解密出現異常!----" + e.StackTrace + e.Message);
                return null;
            }
        }

2.2非對稱性加密算法

發送雙方A,B事先均生成一堆密匙,然後A將自己的公有密匙發送給B,B將自己的公有密匙發送給A,如果A要給B發送消 息,則先需要用B的公有密匙進行消息加密,然後發送給B端,此時B端再用自己的私有密匙進行消息解密,B向A發送消息時爲同樣的道理。

加密算法有RSA,DSA,ECC


注:自己見解,如有錯誤請指出。如有補充,請寫在評論區,謝謝!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章