C# .Net学习笔记—— 加密和解密算法

发布时间:2023年12月22日

一、四种加密方式

1、MD5不可逆加密

2、Des对称可逆加密

3、RSA非对称可逆加密

4、数字证书SSL

二、详解

1、MD5加密

 public class MD5Encrypt
    {
        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:
                    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();
        }

        
        public static string AbstractFile(string filePath)
        {
            using (FileStream file = new FileStream(filePath, FileMode.Open)) 
            {
                return AbstractFile(file);
            }
        }

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

调用

//字符串MD5
Console.WriteLine(MD5Encrypt.Encrypt("1"));
Console.WriteLine(MD5Encrypt.Encrypt("1"));
Console.WriteLine(MD5Encrypt.Encrypt("12"));
Console.WriteLine(MD5Encrypt.Encrypt("1fsdfasd"));
Console.WriteLine(MD5Encrypt.Encrypt("晚上发范德萨飞洒登封市大锅饭大锅饭电话"));

//文件MD5
Console.WriteLine(MD5Encrypt.AbstractFile("C:\\Users\\Daschow\\Desktop\\01.txt"));
Console.WriteLine(MD5Encrypt.AbstractFile("C:\\Users\\Daschow\\Desktop\\01 - 副本.txt"));

得出结果

* 通过上面结果可以得出规律

MD5可以得到一串定长的随机编码

传入的字符串或者文件相同,得到的编码是相同的

只要稍微有一点不同得到的MD5都是不同的

用处:

1、账号登陆,数据库内防止看到密码明文
(1)注册密码
(2)MD5一下,保存
(3)登陆的时候,输入的密码也md5一下,比对

2、疑问:

md5不能解密?

不能解密 网上的解密都是基于样本比对,只能解密简单的密码
密码最好设置复杂点,也加盐(密码+后缀 再MD5)(双MD5)

2、Des加密(可逆对称加密)

1、可逆对称加密

2、数据传输 加密速度快。

3、因为要把密钥发给别人,密钥的安全是问题

4、公开算法,即使拿到密文,也推算不了密钥,也推算不了原文


    public class DesEncrypt
    {
        private static byte[] _rgbKey = ASCIIEncoding.ASCII.GetBytes(Constant.DesKey.Substring(0, 8));
        private static byte[] _rgbIV = ASCIIEncoding.ASCII.GetBytes(Constant.DesKey.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());
            }
        }
    }

?3、Rsa加密(可逆非对称加密)

1、如图,任何人都可以随意获取公钥,并且可以在拿到私钥后解析Eleven说的话。

但是这种方式保证了消息一定是来自于Eleven。

2、加密钥作为私钥,解密钥作为公钥。别人只能解密由Eleven加密的东西

3、如果反过来,加密钥作为公钥,解密钥作为私钥。那东西只有Eleven能看

4、如果合起来准备两套,一套保证签名安全,一套保证信息安全(即只有Elevent能加密并且只有Elevent能看)

public class RsaEncrypt
    {
        /// <summary>
        /// 获取加密/解密对
        /// 给你一个,是无法推算出另外一个的
        /// 
        /// Encrypt   Decrypt
        /// </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="encryptKey">加密key</param>
        /// <returns></returns>
        public static string Encrypt(string content, string encryptKey)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(encryptKey);
            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="decryptKey">解密key</param>
        /// <returns></returns>
        public static string Decrypt(string content, string decryptKey)
        {
            byte[] dataToDecrypt = Convert.FromBase64String(content);
            RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
            RSA.FromXmlString(decryptKey);
            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);
        }
    }
	KeyValuePair<string, string> encryptDecrypt = RsaEncrypt.GetKeyPair();
		string rsaEn1 = RsaEncrypt.Encrypt("net", encryptDecrypt.Key); //key加密
		string rsaDel = RsaEncrypt.Decrypt(rsaEn1, encryptDecrypt.Value);  //value解密

?

文章来源:https://blog.csdn.net/weixin_46711336/article/details/135149193
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。