加解密总结(附助手类)

对称加密算法:DES、AES、IDEA、RC2、RC4、SKIPJACK……
加解密使用相同密钥,这个是对称加密。对称加密优点是速度快

非对称加密算法:RSA、DSA、DH、ECC、EL GAMAL……
公钥加密数据,然后私钥解密的情况被称为加密解密;
因为公钥加密的数据只有它相对应的私钥可以解开,所以你可以把公钥给人和人,让他加密他想要传送给你的数据,这个数据只有到了有私钥的你这里,才可以解开成有用的数据,其他人就是得到了,也看懂内容
实际应用中,一般都是和对方交换公钥,然后你要发给对方的数据,用他的公钥加密,他得到后用他的私钥解密,他要发给你的数据,用你的公钥加密,你得到后用你的私钥解密,这样最大程度保证了安全性.

缺点速度慢

Hash算法:MD5、SHA1、SHA256……
无论消息有多长,计算出的摘要长度都是固定的,MD5没有SHA算法安全

数字签名:
私钥签名和公钥验证签名;RSA可以用来做签名、验签
如果你用你的私钥对数据进行签名,那这个数据就只有配对的公钥可以解开,有这个私钥的只有你,所以如果配对的公钥解开了数据,就说明这数据是你发的,相反,则不是.这个被称为签名。数字签名的意义就是这些数据与原文数据比对是否修改过。

CA证书如何保证网站数据安全:

网站向CA机构申请证书,网站方提供网站信息及公钥给CA机构,CA机构使用自己的私钥对公钥签名,以防篡改。

网站服务器安装CA证书

浏览器发起请求,先请求CA证书,浏览器端保存了CA机构的公钥,对证书验签,验证通过,取出证书中的公钥

使用公钥对http请求信息加密,发起http请求

网站服务器接收到http请求后使用私钥解密。这样就可以防止http请求中的重要信息被拦截者看到,如密码等信息

如果网站没有安装CA证书,也可以在客户端使用RSA加密,公钥保存在浏览器端就可以,我有一篇文章对此有介绍。

DES助手类:

/// <summary>
    /// 可逆对称加密  密钥长度8
    /// </summary>
    public class DesEncrypt
    {
        private static string _key = "fanfanfanfanfan";
        private static byte[] _rgbKey = ASCIIEncoding.ASCII.GetBytes(_key.Substring(0, 8));
        private static byte[] _rgbIV = ASCIIEncoding.ASCII.GetBytes(_key.Insert(0, "w").Substring(0, 8));

        /// <summary>
        /// DES 加密
        /// </summary>
        /// <param name="text">需要加密的值</param>
        /// <returns>加密后的结果</returns>
        public static string Encrypt(string text)
        {
            DESCryptoServiceProvider dsp = new DESCryptoServiceProvider();
            using (MemoryStream memStream = new MemoryStream())
            {
                CryptoStream crypStream = new CryptoStream(memStream, dsp.CreateEncryptor(_rgbKey, _rgbIV), CryptoStreamMode.Write);
                StreamWriter sWriter = new StreamWriter(crypStream);
                sWriter.Write(text);
                sWriter.Flush();
                crypStream.FlushFinalBlock();
                memStream.Flush();
                return Convert.ToBase64String(memStream.GetBuffer(), 0, (int)memStream.Length);
            }
        }

        /// <summary>
        /// DES 解密
        /// </summary>
        /// <param name="encryptText"></param>
        /// <returns>解密后的结果</returns>
        public static string Decrypt(string encryptText)
        {
            DESCryptoServiceProvider dsp = new DESCryptoServiceProvider();
            byte[] buffer = Convert.FromBase64String(encryptText);

            using (MemoryStream memStream = new MemoryStream())
            {
                CryptoStream crypStream = new CryptoStream(memStream, dsp.CreateDecryptor(_rgbKey, _rgbIV), CryptoStreamMode.Write);
                crypStream.Write(buffer, 0, buffer.Length);
                crypStream.FlushFinalBlock();
                return ASCIIEncoding.UTF8.GetString(memStream.ToArray());
            }
        }
    }

AES助手类:

/// <summary>
    /// AES加密解密
    /// 密码必须是16位,否则会报错哈
    /// </summary>
    public class AESCryptoHelper
    {
        /// <summary>
        /// APP默认加密Key
        /// </summary>
        public static string Default_AESKey = "1111111111111111";//必须是十六位

        /// <summary>
        ///  AES 加密
        /// </summary>
        /// <param name="plainText">明文</param>
        /// <param name="key">密码必须是16位,否则会报错哈</param>
        /// <returns>密文</returns>
        public static string Encrypt(string plainText, string key)
        {
            string result = null;
            if (string.IsNullOrEmpty(plainText))
            {
                return result;
            }
            byte[] plainTextArray = Encoding.UTF8.GetBytes(plainText);
            using (RijndaelManaged rijndaelManaged = new RijndaelManaged
            {
                Key = Encoding.UTF8.GetBytes(key),
                Mode = CipherMode.ECB,
                Padding = PaddingMode.PKCS7
            })
            {
                using (ICryptoTransform cryptoTransform = rijndaelManaged.CreateEncryptor())
                {
                    byte[] resultArray = cryptoTransform.TransformFinalBlock(plainTextArray, 0, plainTextArray.Length);
                    result = Convert.ToBase64String(resultArray, 0, resultArray.Length);
                    Array.Clear(resultArray, 0, resultArray.Length);
                    resultArray = null;
                }
            }
            Array.Clear(plainTextArray, 0, plainTextArray.Length);
            plainTextArray = null;
            return result;
        }

        /// <summary>
        ///  AES 解密
        /// </summary>
        /// <param name="encryptText">密文</param>
        /// <param name="key">密码必须是16位,否则会报错哈</param>
        /// <returns>明文</returns>
        public static string Decrypt(string encryptText, string key)
        {
            string result = null;
            if (string.IsNullOrEmpty(encryptText))
            {
                return result;
            }
            byte[] encryptTextArray = Convert.FromBase64String(encryptText);
            using (RijndaelManaged rijndaelManaged = new RijndaelManaged
            {
                Key = Encoding.UTF8.GetBytes(key),
                Mode = CipherMode.ECB,
                Padding = PaddingMode.PKCS7
            })
            {
                using (ICryptoTransform cryptoTransform = rijndaelManaged.CreateDecryptor())
                {
                    byte[] resultArray = cryptoTransform.TransformFinalBlock(encryptTextArray, 0, encryptTextArray.Length);
                    result = Encoding.UTF8.GetString(resultArray);
                    Array.Clear(resultArray, 0, resultArray.Length);
                    resultArray = null;
                }
            }
            Array.Clear(encryptTextArray, 0, encryptTextArray.Length);
            encryptTextArray = null;
            return result;
        }

        /// <summary>
        /// AES 加密(URL传参数加密)
        /// </summary>
        /// <param name="plainText">明文</param>
        /// <param name="key"></param>
        /// <returns>加密之后URL编码</returns>
        public static string UrlEncrypt(string plainText, string key)
        {
            string encryptText = Encrypt(plainText, key);
            return HttpUtilityHelper.UrlEncode(encryptText);
        }

        /// <summary>
        /// AES 解密(URL传参数解密)
        /// </summary>
        /// <param name="encodeEncryptText">URL编码之后的密文</param>
        /// <param name="key"></param>
        /// <returns>明文</returns>
        public static string UrlDecrypt(string encodeEncryptText, string key)
        {
            if (!string.IsNullOrEmpty(encodeEncryptText))
            {
                string encodeText = HttpUtilityHelper.UrlDecode(encodeEncryptText);
                return Decrypt(encodeText, key);
            }
            return "";
        }
    }

MD5助手类:

/// <summary>
    /// MD5
    /// </summary>
    public class MD5Encrypt
    {
        #region MD5
        /// <summary>
        /// MD5加密,和动网上的16/32位MD5加密结果相同,
        /// 使用的UTF8编码
        /// </summary>
        /// <param name="source">待加密字串</param>
        /// <param name="length">16或32值之一,其它则采用.net默认MD5加密算法</param>
        /// <returns>加密后的字串</returns>
        public static string Encrypt(string source, int length = 32)//默认参数
        {
            if (string.IsNullOrEmpty(source)) return string.Empty;
            HashAlgorithm provider = CryptoConfig.CreateFromName("MD5") as HashAlgorithm;
            byte[] bytes = Encoding.UTF8.GetBytes(source);//这里需要区别编码的
            byte[] hashValue = provider.ComputeHash(bytes);
            StringBuilder sb = new StringBuilder();
            switch (length)
            {
                case 16://16位密文是32位密文的9到24位字符
                    for (int i = 4; i < 12; i++)
                    {
                        sb.Append(hashValue[i].ToString("x2"));
                    }
                    break;
                case 32:
                    for (int i = 0; i < 16; i++)
                    {
                        sb.Append(hashValue[i].ToString("x2"));
                    }
                    break;
                default:
                    for (int i = 0; i < hashValue.Length; i++)
                    {
                        sb.Append(hashValue[i].ToString("x2"));
                    }
                    break;
            }
            return sb.ToString();
        }
        #endregion MD5

        #region MD5摘要
        /// <summary>
        /// 获取文件的MD5摘要
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static string AbstractFile(string fileName)
        {
            using (FileStream file = new FileStream(fileName, FileMode.Open))
            {
                return AbstractFile(file);
            }
        }

        /// <summary>
        /// 根据stream获取文件摘要
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static string AbstractFile(Stream stream)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] retVal = md5.ComputeHash(stream);

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < retVal.Length; i++)
            {
                sb.Append(retVal[i].ToString("x2"));
            }
            return sb.ToString();
        }
        #endregion
    }

RSA助手类:

/// <summary>
    /// RSA
    /// </summary>
    public class RsaEncrypt
    {
        /// <summary>
        /// 生成公钥、私钥
        /// </summary>
        /// <returns>Encrypt   Decrypt</returns>
        public static KeyValuePair<string, string> GetKeyPair()
        {
            RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
            string publicKey = RSA.ToXmlString(false);
            string privateKey = RSA.ToXmlString(true);
            return new KeyValuePair<string, string>(publicKey, privateKey);
        }

        /// <summary>
        /// 加密:内容+加密key
        /// </summary>
        /// <param name="content"></param>
        /// <param name="publicKey">加密key</param>
        /// <returns></returns>
        public static string Encrypt(string content, string publicKey)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(publicKey);
            UnicodeEncoding ByteConverter = new UnicodeEncoding();
            byte[] DataToEncrypt = ByteConverter.GetBytes(content);
            byte[] resultBytes = rsa.Encrypt(DataToEncrypt, false);
            return Convert.ToBase64String(resultBytes);
        }

        /// <summary>
        /// 解密  内容+解密key
        /// </summary>
        /// <param name="content"></param>
        /// <param name="privateKey">解密key</param>
        /// <returns></returns>
        public static string Decrypt(string content, string privateKey)
        {
            byte[] dataToDecrypt = Convert.FromBase64String(content);
            RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
            RSA.FromXmlString(privateKey);
            byte[] resultBytes = RSA.Decrypt(dataToDecrypt, false);
            UnicodeEncoding ByteConverter = new UnicodeEncoding();
            return ByteConverter.GetString(resultBytes);
        }


        /// <summary>
        /// 可以合并在一起的,,每次产生一组新的密钥
        /// </summary>
        /// <param name="content"></param>
        /// <param name="encryptKey">加密key</param>
        /// <param name="decryptKey">解密key</param>
        /// <returns>加密后结果</returns>
        private static string Encrypt(string content, out string publicKey, out string privateKey)
        {
            RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider();
            publicKey = rsaProvider.ToXmlString(false);
            privateKey = rsaProvider.ToXmlString(true);

            UnicodeEncoding ByteConverter = new UnicodeEncoding();
            byte[] DataToEncrypt = ByteConverter.GetBytes(content);
            byte[] resultBytes = rsaProvider.Encrypt(DataToEncrypt, false);
            return Convert.ToBase64String(resultBytes);
        }
    }

相关推荐