# Encryption and Decryption Techniques of asp. net

- 2021-07-07 06:59:30
- OfStack

For encryption and decryption, we all know. The following mainly introduces encryption and decryption in ASP. NET.

1. List of data encryption/encoding algorithms

Common encryption or coding algorithms used to ensure security are as follows:

1. Common key algorithms

Key algorithms are used to encrypt sensitive data, digest, signature and other information. Common key algorithms include:

DES (Data Encryption Standard): Data encryption standard, fast, suitable for encrypting large amounts of data occasions;

3DES (Triple DES): Based on DES, one piece of data is encrypted three times with three different keys, which has higher strength;

RC2 and RC4: Encrypt a large amount of data with variable length keys, which is faster than DES;

IDEA (International Data Encryption Algorithm) international data encryption algorithm, which uses 128-bit key to provide very strong security;

RSA: Invented by RSA Company, it is a public key algorithm that supports variable-length keys, and the fast length of files that need to be encrypted is also variable;

DSA (Digital Signature Algorithm): Digital signature algorithm, which is a standard DSS (Digital Signature Standard);

AES (Advanced Encryption Standard): Advanced encryption standard, which is the next generation encryption algorithm standard with high speed and high security level. At present, one implementation of AES standard is Rijndael algorithm;

BLOWFISH, which uses a variable length key, the length can reach 448 bits, and the running speed is very fast;

Other algorithms, such as ElGamal, Deffie-Hellman, new elliptic curve algorithm ECC and so on.

2. One-way hash algorithm

One-way hash function 1 is generally used to generate message digest, key encryption, etc. Common ones are:

MD5 (Message Digest Algorithm 5): It is a one-way hashing algorithm developed by RSA Data Security Company. MD5 is widely used and can be used to code data blocks with different lengths into a 128-bit value;

SHA (Secure Hash Algorithm) This is a relatively new hashing algorithm, which can generate a 160-bit value for any length of data operation;

MAC (Message Authentication Code): Message authentication code, a one-way function that uses keys to authenticate files or messages on the system or between users. HMAC (Key Hashing for Message Authentication) is an example of this function.

CRC (Cyclic Redundancy Check): Cyclic redundancy check code. CRC check is widely used in various data check applications because of its simple implementation and strong error detection ability. It occupies less system resources and can be realized by both software and hardware. It is a good means to detect data transmission errors (CRC is not a hash algorithm in strict sense, but its function is roughly the same as hash algorithm, so it belongs to this category).

3. Other data algorithms

Other data algorithms include some common encoding algorithms and their conversion to plaintext (ASCII, Unicode, etc.), such as Base 64, Quoted, Printable, EBCDIC, etc.

2. NET implementation of the algorithm

Common encryption and encoding algorithms have been implemented in. NET Framework, which provides great convenience for encoders. The namespaces for implementing these algorithms are: System. Security. Cryptography.

The System. Security. Cryptography namespace provides cryptographic services, including secure data encoding and decoding, and many other operations, such as hashing, random number generation, and message authentication.

System. Security. Cryptography is organized as follows:

1. Private key encryption

Private key encryption is also called symmetric encryption because the same 1 key is used for both encryption and decryption. Private-key encryption algorithms are very fast (compared to public-key algorithms) and are especially suitable for performing cryptographic transformations on large data streams.

. NET Framework provides the following classes that implement private key encryption algorithms:

DES: DESCryptoServiceProvider

RC2: RC2CryptoServiceProvider

Rijndael (AES): RijndaelManaged

3DES: TripleDESCryptoServiceProvider

2. Public Key Encryption and Digital Signature

Public key encryption uses a private key that must be kept secret from unauthorized users and a public key that can be made public to anyone. Data encrypted with the public key can only be decrypted with the private key, while data signed with the private key can only be validated with the public key. The public key can be used by anyone; This key is used to encrypt data to be sent to the private key holder. Both keys are uniquely 1 for the communication session. Public key encryption algorithms are also called asymmetric algorithms because one key is required to encrypt the data and another key is required to decrypt the data.

. NET Framework provides the following classes that implement public key cryptography algorithms:

DSA: DSACryptoServiceProvider

RSA: RSACryptoServiceProvider

3. Hash (Hash) value

The hash algorithm maps a binary value of any length to a smaller binary value of a fixed length, which is called a hash value. Hash value is a 1-only and extremely compact numerical representation of 1 piece of data. If you hash a paragraph of plaintext and change even one letter of that paragraph, subsequent hashes will produce different values. It is computationally impossible to find two different inputs with the same hash value, so the hash value of the data can verify the integrity of the data.

. NET Framework provides the following classes that implement digital signature algorithms:

HMAC: HMACSHA1 (HMAC is an Hash algorithm that uses a key)

MAC: MACTripleDES

MD5: MD5CryptoServiceProvider

SHA 1: SHA1Managed, SHA256Managed, SHA384Managed, SH7747.net12Managed

4. Random number generation

Encryption keys need to be as random as possible in order to make the generated keys difficult to reproduce, so random number generation is an integral part of many encryption operations.

In. NET Framework, RNGCryptoServiceProvider is the implementation of random number generator algorithm, while for data algorithm,. NET Framework is implemented in other namespaces, such as Convert class implementing Base 64 encoding, System. Text implementing encoding mode conversion, etc.

From the above, . NET Framework for data encryption/encoding or better support, greatly convenient for developers, but the fly in the ointment is that. NET Framework data encryption algorithm is still not complete, such as IDEA, BLOWFISH, other algorithms, such as ElGamal, Deffie-Hellman, ECC, etc., for a number of other data verification algorithm support is not enough, such as CRC, SFV, developers can only do from the early code transplantation or look for third-party vendor implementation.

The following is a brief introduction to the encryption and decryption methods commonly used in the project

1. MD5 encryption algorithm

[The algorithm MD5 included in the. NET class library is an irreversible algorithm without decryption]

In fact, data is encrypted in ASP. Net programming. There are its own classes in DotNet:

```
System.Web.Security.HashPasswordForStoringInConfigFile()
public string md5(string str,int code)
{
if(code==16) //16 Bit MD5 Encryption (take 32 Bit encrypted 9~25 Character)
{
return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str,"MD5")
.ToLower().Substring(8,16) ;
}
if(code==32) //32 Bit encryption
{
return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str,"MD5")
.ToLower();
}
return "00000000000000000000000000000000";
}
```

Simple use:

//--Import required packages

using System.IO;

using System.Text;

using System.Security.Cryptography;

(1) MD5 General Encryption

//Get the field to encrypt and convert it to an Byte [] array

byte[] data = System.Text.Encoding.Unicode

.GetBytes(TextBox1.Text.ToCharArray());

//Establish cryptographic services

System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();

//Encrypt Byte [] Array

byte[] result = md5.ComputeHash(data);

Label1.Text = "MD5 General Encryption:" + System. Text. Encoding. Unicode. GetString (result);

(2) MD5 cipher encryption [commonly used]

Label1.Text = "MD5 Password Encryption:" + System. Web. Security. FormsAuthentication

.HashPasswordForStoringInConfigFile(TextBox1.Text, "MD5");

(3) Encryption and Decryption of QueryString in ASP. NET [Commonly Used]

//Encryption

Response.Redirect("DetailInfo.aspx?id=" + Convert.ToBase64String

(System.Text.Encoding.Default.GetBytes("whaben")).Replace("+","%2B"));

//Decryption

string ID = System.Text.Encoding.Default.GetString

(Convert.FromBase64String(Request.QueryString["id"].ToString().Replace("%2B","+")));

2. DES encryption and decryption algorithm [common key algorithm

Simple use:

```
//-- Import required packages
using System.IO;
using System.Text;
using System.Security.Cryptography;
public static string Key = "DKMAB5DE";// The encryption key must be 8 Bit
// Encryption algorithm
public static string MD5Encrypt(string pToEncrypt)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);
des.Key = ASCIIEncoding.ASCII.GetBytes(Key);
des.IV = ASCIIEncoding.ASCII.GetBytes(Key);
MemoryStream ms = new 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);
}
ret.ToString();
return ret.ToString();
}
// Decryption algorithm
public static string MD5Decrypt(string pToDecrypt)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
for (int x = 0; x < pToDecrypt.Length / 2; x++)
{
int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
inputByteArray[x] = (byte)i;
}
des.Key = ASCIIEncoding.ASCII.GetBytes(Key);
des.IV = ASCIIEncoding.ASCII.GetBytes(Key);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
StringBuilder ret = new StringBuilder();
return System.Text.Encoding.ASCII.GetString(ms.ToArray());
}
```

3. RSA encryption and decryption algorithm [common key algorithm

Simple use:

```
//-- Import required packages
using System.Text;
using System.Security.Cryptography;
// Encryption algorithm
public string RSAEncrypt(string encryptString)
{
CspParameters csp = new CspParameters();
csp.KeyContainerName = "whaben";
RSACryptoServiceProvider RSAProvider = new RSACryptoServiceProvider(csp);
byte[] encryptBytes = RSAProvider.Encrypt(ASCIIEncoding.ASCII.GetBytes(encryptString), true);
string str = "";
foreach (byte b in encryptBytes)
{
str = str + string.Format("{0:x2}", b);
}
return str;
}
// Decryption algorithm
public string RSADecrypt(string decryptString)
{
CspParameters csp = new CspParameters();
csp.KeyContainerName = "whaben";
RSACryptoServiceProvider RSAProvider = new RSACryptoServiceProvider(csp);
int length = (decryptString.Length / 2);
byte[] decryptBytes = new byte[length];
for (int index = 0; index < length; index++)
{
string substring = decryptString.Substring(index * 2, 2);
decryptBytes[index] = Convert.ToByte(substring, 16);
}
decryptBytes = RSAProvider.Decrypt(decryptBytes, true);
return ASCIIEncoding.ASCII.GetString(decryptBytes);
}
```