Go DES, RSA, MD5, SHA, randomly generated encryption and decryption

Source: Internet
Author: User
Tags hmac

First, the data encryption / encoding algorithm list
 
Common encryption or encoding algorithms used to ensure security are as follows:
 
1. Common key algorithm
 
The key algorithm is used to encrypt sensitive data, digests, signatures, etc. Common key algorithms include:
 
DES (Data Encryption Standard): A data encryption standard that is fast and suitable for encrypting large amounts of data.
 
3DES (Triple DES): Based on DES, it encrypts a piece of data three times with three different keys, and has higher strength;
 
RC2 and RC4: Encrypt large amounts of data with variable length keys, faster than DES;
 
IDEA (International Data Encryption Algorithm) international data encryption algorithm, using 128-bit key to provide very strong security;
 
RSA: Invented by RSA, it is a public key algorithm that supports variable length keys. The length of files that need to be encrypted is also variable;
 
DSA (Digital Signature Algorithm): a digital signature algorithm, which is a standard DSS (Digital Signature Standard);
 
AES (Advanced Encryption Standard): The advanced encryption standard is the next generation encryption algorithm standard. It is fast and has a high security level. One implementation of the current AES standard is the Rijndael algorithm.
 
BLOWFISH, which uses a variable-length key that can be up to 448 bits long and runs fast;
 
Other algorithms, such as ElGamal, Deffie-Hellman, the new elliptic curve algorithm ECC, etc.
 
2. One-way hash algorithm
 
One-way hash functions are generally used to generate message digests, key encryption, etc. Common ones are:
 
MD5 (Message Digest Algorithm 5): is a one-way hash algorithm developed by RSA Data Security. MD5 is widely used and can be used to perform dark code operations on data blocks of different lengths into a 128-bit value.
 
SHA (Secure Hash Algorithm) This is a newer hash algorithm that can generate a 160-bit value for any length of data operation.
 
MAC (Message Authentication Code): A 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 such a function.
 
CRC (Cyclic Redundancy Check): Cyclic Redundancy Check Code, which is widely used in various data verification applications due to its simple implementation and strong error detection capability. It occupies less system resources and can be implemented by both hardware and software. It is a good method for data transmission error detection (CRC is not a hash algorithm in the strict sense, but its role is roughly the same as that of hash algorithm, so it belongs to This class).
 
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.
 
Second, the implementation of the .NET implementation of the algorithm
 
Common encryption and encoding algorithms have been implemented in the .NET Framework, providing great convenience for coders. The namespace for implementing these algorithms is: System.Security.Cryptography.
 
The System.Security.Cryptography namespace provides cryptographic services, including secure data encoding and decoding, as well as 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 known as symmetric encryption because the same key is used for both encryption and decryption. The private key encryption algorithm is very fast (compared to the public key algorithm) and is especially useful for performing cryptographic transformations on large data streams.
 
The .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 cryptography uses a private key that must be kept secret to unauthorized users and a public key that can be made public to anyone. Data encrypted with a public key can only be decrypted with a private key, while data signed with a private key can only be verified with a public key. The public key can be used by anyone; this key is used to encrypt the data to be sent to the private key holder. Both keys are unique to the communication session. The public key encryption algorithm is also called an asymmetric algorithm because it requires a key to encrypt the data and another key to decrypt the data.
 
The .NET Framework provides the following classes that implement public key cryptography:
 
DSA: DSACryptoServiceProvider
RSA: RSACryptoServiceProvider
3, hash (Hash) value
 
The hash algorithm maps binary values of arbitrary length to smaller binary values of fixed length. This small binary value is called a hash value. A hash value is a unique and extremely compact numerical representation of a piece of data. If you hash a plaintext and even change only one letter of the paragraph, subsequent hashes will produce different values. It is computationally impossible to find two different inputs that are hashed to the same value, so the hash of the data can verify the integrity of the data.
 
The .NET Framework provides the following classes that implement digital signature algorithms:
 
HMAC: HMACSHA1 (HMAC is a Hash algorithm using a key)
MAC: MACTripleDES
MD5: MD5CryptoServiceProvider
SHA1: SHA1Managed, SHA256Managed, SHA384Managed, SH7747.net12Managed
4, random number generation
 
The encryption key needs to be as random as possible so that the generated key is difficult to reproduce, so random number generation is an integral part of many encryption operations.
 
In the .NET Framework, RNGCryptoServiceProvider is an implementation of the random number generator algorithm. For data algorithms, the .NET Framework is implemented in other namespaces, such as the Convert class to implement Base 64 encoding, System.Text to implement encoding mode conversion, and so on.
 
From the above point of view, the .NET Framework still supports data encryption/encoding better, which greatly facilitates developers. However, the fly in the ointment is that the data encryption algorithm in the .NET Framework is still not complete enough, such as IDEA, BLOWFISH, and other algorithms. For example, ElGamal, Deffie-Hellman, ECC, etc., for some other data verification algorithms are not enough, such as CRC, SFV, etc., developers can only go from the early code to transplant or find the implementation of third-party manufacturers.
 
Here is a brief introduction to the methods of encryption and decryption commonly used in projects.
 
First, MD5 encryption algorithm
 
[The algorithm that comes with the .NET class library MD5 is an irreversible algorithm. There is no decryption algorithm]
 
In fact, encrypt data in ASP.Net programming. There are classes in DotNet:
 
System.Web.Security.HashPasswordForStoringInConfigFile()
Public string md5(string str, int code)
{
If(code==16) //16-bit MD5 encryption (take 9-25 characters for 32-bit encryption)
{
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 to use:
 
//--Import the required package
Using System.IO;
Using System.Text;
Using System.Security.Cryptography;
(1) MD5 ordinary encryption
 
/ / Get the field to be encrypted, and convert to a Byte[] array
Byte[] data = System.Text.Encoding.Unicode
.GetBytes(TextBox1.Text.ToCharArray());
//Create encryption service
System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
/ / Encrypt Byte[] array
Byte[] result = md5.ComputeHash(data);
Label1.Text = "MD5 Normal Encryption:" + System.Text.Encoding.Unicode.GetString(result);
(2) MD5 password encryption [common]
 
Label1.Text = "MD5 password encryption:" + System.Web.Security.FormsAuthentication
.HashPasswordForStoringInConfigFile(TextBox1.Text, "MD5");
(3) ASP.NET encryption and decryption QueryString method [common]
 
//Encryption
Response.Redirect("DetailInfo.aspx?id=" + Convert.ToBase64String
(System.Text.Encoding.Default.GetBytes("whaben")).Replace("+","+"));
//decrypt
String ID = System.Text.Encoding.Default.GetString
(Convert.FromBase64String(Request.QueryString["id"].ToString().Replace("+","+")));
Second, DES encryption and decryption algorithm [common key algorithm]
 
Simple to use:
 
//--Import the required package
Using System.IO;
Using System.Text;
Using System.Security.Cryptography;
Public static string Key = "DKMAB5DE"; / / encryption key must be 8 bits
//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());
}
Third, RSA encryption and decryption algorithm [common key algorithm]
 
Simple to use:
 
//--Import the required package
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);
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.