# Common encryption methods

Posted by Nuggit on Sun, 10 Oct 2021 04:36:01 +0200

# Common encryption methods

## MD5 encryption

concept

MD5 message digest algorithm (English: MD5 message digest algorithm), a widely used algorithm Cryptographic hash function , a 128 bit (16 bit) can be generated byte )The hash value of is used to ensure the integrity and consistency of information transmission. MD5 by American Cryptologist Ron Rivest (Ronald Linn Rivest) design, published in 1992, to replace MD4 Algorithm. The program of this algorithm is standardized in RFC 1321 standard. After 1996, the algorithm was proved to have weaknesses and can be cracked. For data requiring high security, experts generally recommend to use other algorithms, such as SHA-2 . In 2004, it was confirmed that MD5 algorithm could not prevent collision, so it was not suitable for security authentication, such as SSL Public key authentication or digital signature And other purposes.

Core code

```package com.inspur.his.common;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Utils {
/**
* md5 encrypt plaintext strings
* @param source Incoming string
* @return Encrypted results
*/
public static String md5(String source) {
String en_pass = "";//Encrypted password
// 1. Judge whether the source is valid
if (source != null && source.length() > 0) {
// 2. Throw an exception if it is not a valid string
try {
// 3. Get MessageDigest object
String algorithm = "md5";
MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
// 4. Get the byte array corresponding to the plaintext string
byte[] input = source.getBytes();
// 5. Perform encryption
byte[] output = messageDigest.digest(input);
// 6. Create BigInteger object
int signum = 1;
BigInteger bigInteger = new BigInteger(signum, output);
// 7. Convert the value of bigInteger into a string in hexadecimal
int radix = 16;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
return en_pass;
}

public static void main(String[] args) {
//666666:F379EAF3C831B04DE153469D1BEC345E
}
}
```

## DES encryption

concept

DES algorithm is Cryptosystem The symmetric cryptosystem in is also known as the United States Data encryption standard It is a symmetric cryptosystem developed by IBM in 1972 encryption algorithm . Plaintext Grouped by 64 bits, secret key It is 64 bits long, and the key is actually 56 bits to participate in DES operation (bits 8, 16, 24, 32, 40, 48, 56 and 64 are Check bit So that each key has Odd number 1) plaintext group after grouping and 56 bit key by bit replace Or exchange method to form ciphertext group encryption method.

DES algorithm has high security, in addition to using exhaustive search Besides attacking DES algorithm, no more effective method has been found. And 56 long secret key The exhaustive space is 2 ^ 56, which means that if the speed of a computer is to detect one million keys per second, it will take nearly 2285 years to search all the keys. It can be seen that this is difficult to achieve. However, this does not mean that DES is unbreakable. In fact, with the development of hardware technology and Internet, it is more and more likely to crack, and it takes less and less time. Parallel processing with specially designed hardware takes several hours.

Core code

```package com.inspur.his.common;

import javax.crypto.Cipher;
import java.security.Key;

public class EncrypDES {
// String default key value
private static String strDefaultKey = "inventec2020@#\$%^&";
// encryption tool
private Cipher encryptCipher = null;
// Decryption tool
private Cipher decryptCipher = null;

/**
* Default construction method, using default key
*/
public EncrypDES() throws Exception {
this(strDefaultKey);
}

/**
* Specify key construction method
*
* @param strKey
*            Specified key
* @throws Exception
*/

public EncrypDES(String strKey) throws Exception {
Key key = getKey(strKey.getBytes());
encryptCipher = Cipher.getInstance("DES");
encryptCipher.init(Cipher.ENCRYPT_MODE, key);
decryptCipher = Cipher.getInstance("DES");
decryptCipher.init(Cipher.DECRYPT_MODE, key);
}

/**
* Convert the byte array to a string representing hexadecimal values, such as: byte[]{8,18} to: 0813, and public static byte []
*
* hexStr2ByteArr(String strIn) Mutually reversible conversion process
*
* @param arrB
*            byte array to be converted
* @return Converted String
* @throws Exception
*             This method does not handle any exceptions, and all exceptions are thrown
*/
public static String byteArr2HexStr(byte[] arrB) throws Exception {
int iLen = arrB.length;
// Each byte can only be represented by 2 characters, so the length of the string is twice the length of the array
StringBuffer sb = new StringBuffer(iLen * 2);
for (int i = 0; i < iLen; i++) {
int intTmp = arrB[i];
// Convert negative numbers to positive numbers
while (intTmp < 0) {
intTmp = intTmp + 256;
}
// Numbers less than 0F need to be preceded by 0
if (intTmp < 16) {
sb.append("0");
}
sb.append(Integer.toString(intTmp, 16));
}
return sb.toString();
}

/**
* Convert the string representing hexadecimal value into byte array and public static String byteArr2HexStr(byte[] arrB)
* Mutually reversible conversion process
*
* @param strIn
*            String to convert
* @return Converted byte array
*/
public static byte[] hexStr2ByteArr(String strIn) throws Exception {
byte[] arrB = strIn.getBytes();
int iLen = arrB.length;
// Two characters represent a byte, so the byte array length is the string length divided by 2
byte[] arrOut = new byte[iLen / 2];
for (int i = 0; i < iLen; i = i + 2) {
String strTmp = new String(arrB, i, 2);
arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);
}
return arrOut;
}

/**
*
* Encrypted byte array
*
* @param arrB
*            Byte array to be encrypted
* @return Encrypted byte array
*/
public byte[] encrypt(byte[] arrB) throws Exception {
return encryptCipher.doFinal(arrB);
}

/**
* Encrypted string
*
* @param strIn
*            String to encrypt
* @return Encrypted string
*/
public String encrypt(String strIn) throws Exception {
return byteArr2HexStr(encrypt(strIn.getBytes()));
}

/**
* Decrypt byte array
*
* @param arrB
*            Byte array to decrypt
* @return Decrypted byte array
*/
public byte[] decrypt(byte[] arrB) throws Exception {
return decryptCipher.doFinal(arrB);
}

/**
* Decrypt string
*
* @param strIn
*            String to decrypt
* @return Decrypted string
*/
public String decrypt(String strIn) throws Exception {
return new String(decrypt(hexStr2ByteArr(strIn)));
}

/**
* The key is generated from the specified string. The length of the byte array required for the key is 8 bits. If it is less than 8 bits, it is supplemented with 0. If it exceeds 8 bits, only the first 8 bits are taken
*
* @param arrBTmp
*            An array of bytes that make up the string
* @return Generated key
*/
private Key getKey(byte[] arrBTmp) throws Exception {
// Create an empty 8-bit byte array (the default is 0)
byte[] arrB = new byte[8];
// Converts the original byte array to 8 bits
for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {
arrB[i] = arrBTmp[i];
}
// Generate key
Key key = new javax.crypto.spec.SecretKeySpec(arrB, "DES");
return key;
}

public static void main(String[] args) {
try {

String msg = "123456";
EncrypDES des = new EncrypDES();// Use default key
System.out.println("Characters before encryption:" + msg);
System.out.println("Encrypted characters:" + des.encrypt(msg));
System.out.println("Decrypted characters:" + des.decrypt(des.encrypt(msg)));
System.out.println("--------Graceful separator------");

String msg2 = "666666";
String key = "2020@#\$2020";
EncrypDES des2 = new EncrypDES(key);// Custom key
System.out.println("Characters before encryption:" + msg2);
System.out.println("Encrypted characters:" + des2.encrypt(msg2));
System.out.println("Decrypted characters:" + des2.decrypt(des2.encrypt(msg2)));

} catch (Exception e) {
e.printStackTrace();
}

}

}
```

Topics: Java Algorithm