.net commonly used encryption and decryption algorithms

MD5 encryption: (irreversible encryption)

Encapsulation method: 

 public class Encrypt
    {
        /// <summary>
        /// md5加密后返回密文
        /// </summary>
        /// <param name="source">要加密的明文</param>
        /// <returns></returns>
        public static string MD5Encrypt(string source)
        {
            try
            {
                MD5 md5 = MD5.Create();
                byte[] data = md5.ComputeHash(Encoding.Default.GetBytes(source));
                StringBuilder sBuilder = new StringBuilder();
                for (int i = 0; i < data.Length; i++)
                {
                    sBuilder.Append(data[i].ToString("x2"));
                }
                return sBuilder.ToString();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 获取文件的md5摘要
        /// </summary>
        /// <param name="fileName">文件名称</param>
        /// <returns>文件摘要</returns>
        public static string AbstractFile(string fileName)
        {
            using (FileStream stream = new FileStream(fileName, FileMode.Open))
            {
                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();
            }
        }

    }

Examples:

Console.WriteLine(Encrypt.MD5Encrypt("123456"));     
Console.WriteLine(Encrypt.AbstractFile(@"C:\Users\Administrator\Desktop\test\jquery.js"));

result:

 

md5 encryption features:

1. The encrypted result of the same original text is the same

2. The length of the encrypted content of different lengths is the same

3. Encryption is irreversible, and the original text cannot be decrypted through ciphertext

4. The original text is very different, but the encrypted result is very different

5. Documents can also be encrypted to generate abstracts

 

md5 encryption application:

1. The password for system login is encrypted by md5 and the ciphertext is stored in the database. When the user logs in, the password entered by the user is encrypted with md5 and compared with the database. (Save the password to prevent you from seeing the plain text)

2. The source code manager, such as svn, when the file is changed, the file will be marked as changed. (Tamper proof)

3. Fast upload in seconds, scan the md5 of the file, and compare it with the existing file md5. If the match indicates that the file already exists, it will no longer be uploaded.

4. Digital signature, summarize some content, and protect it by an authoritative third party. In the future, this document will be made by you and cannot be denied.

 

 

 

DES encryption: (symmetric reversible encryption)

add a configuration type to app.config for storing encrypted keys

 <appSettings>
    <add key="DesKey" value="hello666"/>
 </appSettings>

Encryption and decryption method package:  

public class Encrypt
    {
        public static string DesKey = ConfigurationManager.AppSettings["DesKey"];
        private static byte[] _rgbKey = ASCIIEncoding.ASCII.GetBytes(DesKey.Substring(0, 8));
        private static byte[] _rgbIV = ASCIIEncoding.ASCII.GetBytes(DesKey.Insert(0, "w").Substring(0, 8));

        /// <summary>
        /// DES加密
        /// </summary>
        /// <param name="text">需要加密的值</param>
        /// <returns>加密后的结果</returns>
        public static string DesEncrypt(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 DesDecrypt(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();
                memStream.Flush();
                return ASCIIEncoding.UTF8.GetString(memStream.ToArray());
            }
        }
    }

Examples:

string strDes = Encrypt.DesEncrypt("张三");
Console.WriteLine(strDes);
Console.WriteLine(Encrypt.DesDecrypt(strDes));

result:

 

DES encryption features:

1. It can be decrypted back to the original text after encryption, and the encryption key and decryption key are the same.

2. The speed of encryption and decryption is fast, and the problem is the security of the key.

 

 

RSA encryption: (asymmetric reversible encryption)

Encryption and decryption method package:  

 public class Encrypt
    {
        /// <summary>
        /// RSA随机生成一对密钥
        /// </summary>
        /// <returns>一对密钥值</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>
        /// RSA加密(内容+加密key)
        /// </summary>
        /// <param name="content">内容</param>
        /// <param name="encryptKey">加密key</param>
        /// <returns>加密后的信息</returns>
        public static string RSAEncrypt(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>
        /// RSA解密(内容+解密key)
        /// </summary>
        /// <param name="content">内容</param>
        /// <param name="descryptKey">解密key</param>
        /// <returns></returns>
        public static string RSADecrypt(string content, string descryptKey)
        {
            byte[] dataToDecrypt = Convert.FromBase64String(content);
            RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
            RSA.FromXmlString(descryptKey);
            byte[] resultBytes = RSA.Decrypt(dataToDecrypt, false);
            UnicodeEncoding ByteConverter = new UnicodeEncoding();
            return ByteConverter.GetString(resultBytes);
        }

    }

Examples:

KeyValuePair<string, string> encryptDescypt = Encrypt.GetKeyPair();
string rsaEn = Encrypt.RSAEncrypt("123456",encryptDescypt.Key);
string rsaDe = Encrypt.RSADecrypt(rsaEn, encryptDescypt.Value);
Console.WriteLine(rsaEn);
Console.WriteLine(rsaDe);

result:

 

RSA encryption features:

1. It can be decrypted back to the original text after encryption, the encryption key and decryption key are not the same.

2. The encryption and decryption speed is not fast, but the security is good.

3. Publicly encrypt the key to ensure the safe transmission of data.

4. Open the decryption key to ensure the non-repudiation of the data.

Guess you like

Origin blog.csdn.net/liangmengbk/article/details/114228947