Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the common encryption and decryption algorithms in .NET?

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "what are the common encryption and decryption algorithms in .NET". The content of the explanation in this article is simple and clear, and it is easy to learn and understand. let's study and learn "what are the common encryption and decryption algorithms in .NET"?

1. MD5 irreversible encryption

Irreversible encryption means that after encrypting the original text into ciphertext, the ciphertext cannot be decrypted into the original text.

MD5's algorithm is public, no matter which language, as long as the string that needs to be encrypted is the same, then the result after MD5 encryption is the same.

MD5 encryption has been implemented for us in the .NET Framework. Take a look at the following example:

Using System;using System.Collections.Generic;using System.Linq;using System.Security.Cryptography;using System.Text;using System.Threading.Tasks Namespace MyEncriptDemo {public class MD5Encrypt {# region MD5 / MD5 encryption, which is the same as the 16-bit MD5 encryption on Mobile Network. / / one of the UTF8 codes / string / 16 or 32 values to be encrypted Others use .net default MD5 encryption algorithm / / encrypted string public static string Encrypt (string source, int length = 32) / / default parameter {if (string.IsNullOrEmpty (source)) return string.Empty HashAlgorithm provider = CryptoConfig.CreateFromName ("MD5") as HashAlgorithm; byte [] bytes = Encoding.UTF8.GetBytes (source); / / differentially encoded byte [] hashValue = provider.ComputeHash (bytes); StringBuilder sb = new StringBuilder () Switch (length) {case 16-bit ciphertext is the 9-to 24-bit character for (int I = 4; I) of 32-bit ciphertext

< 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 }} Main()方法调用: using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace MyEncriptDemo{ class Program { static void Main(string[] args) { // MD5 Console.WriteLine(MD5Encrypt.Encrypt("1")); Console.WriteLine(MD5Encrypt.Encrypt("1")); Console.WriteLine(MD5Encrypt.Encrypt("123456孙悟空")); Console.WriteLine(MD5Encrypt.Encrypt("113456孙悟空")); Console.WriteLine(MD5Encrypt.Encrypt("113456孙悟空113456孙悟空113456孙悟空113456孙悟空113456孙悟空113456孙悟空113456孙悟空")); Console.ReadKey(); } }} 结果:

Application:

1. Verify the password

As can be seen from the above example, as long as the string is the same, then the result after encryption is the same. Using this feature of MD5, it can be used for password verification. When registering, encrypt the password with MD5 and save it to the database, where the ciphertext is saved and cannot be seen by others. When logging in, the password is encrypted by MD5, and then the encrypted ciphertext is compared with the ciphertext stored in the database. If it is the same, it proves that the password is the same; if different, it proves that the password is wrong.

Note: MD5 can not be decrypted, online decryption is based on the principle of collision database: that is, the original text and ciphertext are saved in the database, and each time the ciphertext is compared with the ciphertext stored in the database. If the comparison is successful, it is decrypted. To prevent hitting the library, you can make the password more complex, such as adding salt: add a suffix to the password and then encrypt it and save it to the database. When logging in, add the same suffix to the password, and then compare it with the password saved in the database after encryption.

2. Tamper proof

For example, download VS installation files, the official website download files are authoritative, but sometimes go to the system House, such as the website to download, how to ensure that the installation files downloaded in the system House and the official website released the same files? At this point, you can use MD5 to make a judgment. The official release of the VS installation file at the same time, will also release a MD5 code generated according to the file, after downloading the installation file in the system home, you can encrypt the installation file once MD5, and then compare the official release of MD5 code and the generated MD5 code, if the same, then prove that the downloaded file is officially convenient. So how do you MD5 a file? Take a look at the following example:

Using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Security.Cryptography;using System.Text;using System.Threading.Tasks Namespace MyEncriptDemo {public class MD5Encrypt {# region MD5 / MD5 encryption, which is the same as the 16-bit MD5 encryption on Mobile Network. / / one of the UTF8 codes / string / 16 or 32 values to be encrypted Others use .net default MD5 encryption algorithm / / encrypted string public static string Encrypt (string source, int length = 32) / / default parameter {if (string.IsNullOrEmpty (source)) return string.Empty HashAlgorithm provider = CryptoConfig.CreateFromName ("MD5") as HashAlgorithm; byte [] bytes = Encoding.UTF8.GetBytes (source); / / differentially encoded byte [] hashValue = provider.ComputeHash (bytes); StringBuilder sb = new StringBuilder () Switch (length) {case 16-bit ciphertext is the 9-to 24-bit character for (int I = 4; I) of 32-bit ciphertext

< 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摘要 /// /// 获取文件的MD5摘要 /// /// /// public static string AbstractFile(string fileName) { using (FileStream file = new FileStream(fileName, FileMode.Open)) { return AbstractFile(file); } } /// /// 根据stream获取文件摘要 /// /// /// 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 }} Main()方法里面调用: using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace MyEncriptDemo{ class Program { static void Main(string[] args) { // MD5 //Console.WriteLine(MD5Encrypt.Encrypt("1")); //Console.WriteLine(MD5Encrypt.Encrypt("1")); //Console.WriteLine(MD5Encrypt.Encrypt("123456孙悟空")); //Console.WriteLine(MD5Encrypt.Encrypt("113456孙悟空")); //Console.WriteLine(MD5Encrypt.Encrypt("113456孙悟空113456孙悟空113456孙悟空113456孙悟空113456孙悟空113456孙悟空113456孙悟空")); // 对文件进行MD5 string md5Abstract1 = MD5Encrypt.AbstractFile(@"E:\EF一对多.txt"); Console.WriteLine(md5Abstract1); string md5Abstract2 = MD5Encrypt.AbstractFile(@"E:\EF一对多 - 副本.txt"); Console.WriteLine(md5Abstract2); Console.ReadKey(); } }} 结果:

As you can see, although the name of the file is different, the generated MD5 code is the same as long as the contents of the file are the same.

3. Rapid second pass

Take Baidu Cloud as an example: if you download a file from Baidu Cloud, and then upload this file to Baidu Cloud, it will be quickly transferred in seconds. Because when uploading for the first time, Baidu Cloud will encrypt the uploaded file with MD5, and then save the encrypted MD5 code. After downloading and uploading, Baidu Cloud client will first calculate the MD5 of the file, and then compare the calculated MD5 with the MD5 saved by the server. If it is consistent, you do not need to upload it. You only need to modify the name of the file on the server to be the same as the name of the uploaded file. Because the uploaded file already exists on the server. (even if the file name is changed, the generated MD5 is still the same.)

4. Source code control tools

The source code control tool implements to determine whether the file is modified or not, and it is also compared according to MD5.

Second, symmetrical reversible encryption

Symmetric reversible encryption: reversible means that encryption and decryption are reversible, that is, the ciphertext can be obtained according to the original text, and the original text can also be obtained according to the ciphertext. Symmetry means that the keys of encryption and decryption are the same. Take DES encryption as an example.

In the sample program, the key length is 8 bits, written in the configuration file.

The code to read the configuration file to get the key is as follows:

Using System;using System.Collections.Generic;using System.Configuration;using System.Linq;using System.Text;using System.Threading.Tasks;namespace MyEncriptDemo {public static class Constant {public static string DesKey = AppSettings ("DesKey", "DesEncript"); private static T AppSettings (string key, T defaultValue) {var v = ConfigurationManager.AppSettings [key]; return String.IsNullOrEmpty (v)? DefaultValue: (t) Convert.ChangeType (v, typeof (T));}}

The code for encryption and decryption is as follows:

The advantage of using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Security.Cryptography;using System.Text;using System.Threading.Tasks;namespace MyEncriptDemo {/ DES AES Blowfish / symmetric encryption algorithm is its high speed, and / its disadvantage is that it is not convenient to manage the key and requires sharing the key. / reversible symmetric encryption key length 8 / public class DesEncrypt {/ / encrypt according to an 8-bit key private static byte [] _ rgbKey = ASCIIEncoding.ASCII.GetBytes (Constant.DesKey.Substring (0,8)) / / initialization vector of symmetric algorithm private static byte [] _ rgbIV = ASCIIEncoding.ASCII.GetBytes (Constant.DesKey.Insert (0, "w") .Substring (0,8)) / DES encryption / the value to be encrypted / the encrypted result 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);} / DES decrypted / decrypted result 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 ()) }

The Main () method call:

String strDes = "Zhang San Li Si"; string desEn1 = DesEncrypt.Encrypt (strDes); string desDe1 = DesEncrypt.Decrypt (desEn1); Console.WriteLine (strDes.Equals (desDe1))

Results:

Note: the algorithm of symmetric reversible encryption is public.

3. Asymmetric reversible encryption

Asymmetric reversible encryption: reversible means that encryption and decryption are the same, that is, the ciphertext can be obtained according to the original text, and the original text can also be obtained according to the ciphertext. Asymmetry means that the keys of encryption and decryption are different. Take RSA encryption as an example:

Using System;using System.Collections.Generic;using System.Linq;using System.Security.Cryptography;using System.Text;using System.Threading.Tasks;namespace MyEncriptDemo {/ RSA ECC / / reversible asymmetric encryption algorithm has the advantages of convenient key management and slow speed. / public class RsaEncrypt {/ get encryption / decryption pair / give you one, it is impossible to calculate the other one's / Encrypt Decrypt / Encrypt Decrypt public static KeyValuePair GetKeyPair () {RSACryptoServiceProvider RSA = new RSACryptoServiceProvider () String publicKey = RSA.ToXmlString (false); string privateKey = RSA.ToXmlString (true); return new KeyValuePair (publicKey, privateKey) Encryption: content + encryption key / encryption key / 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) } / decrypted content + decrypted key / / decrypted key / 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) } / can be merged together, generate a new set of keys each time / / encrypt key / decrypt key / encrypt the result 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);}

The Main () method call:

/ / get encryption and decryption keys KeyValuePair encryptDecrypt = RsaEncrypt.GetKeyPair (); string strValue = "RsaDemo"; string rsaEn1 = RsaEncrypt.Encrypt (strValue, encryptDecrypt.Key); / / key is encrypted string rsaDe1 = RsaEncrypt.Decrypt (rsaEn1, encryptDecrypt.Value); / / Console.WriteLine (strValue.Equals (rsaDe1) that cannot be used in reverse for value decryption)

Results:

Note:

1. The encryption key and the settlement key are divided according to the function.

2. The private key and the public key are divided according to the public degree of the key, and the encryption key can be used as the public key or private key, and the decryption key can also be used as the public key or private key.

Thank you for your reading, the above is the content of "what are the common encryption and decryption algorithms in .NET". After the study of this article, I believe you have a deeper understanding of what are the common encryption and decryption algorithms in .NET. Specific use also needs to be verified by practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report