# Encryption algorithm AES MD5 SHA1

Encryption algorithms are usually divided into symmetrical encryption algorithm and asymmetrical encryption algorithm. For symmetrical encryption algorithm, both receivers of information need to know the key and encryption and decryption algorithm beforehand, and the key is the same, then the data is encrypted and decrypted. The asymmetric algorithm is different from the asymmetric algorithm. Both A and B generate a bunch of keys beforehand. Then A sends their public keys to B. B sends their public keys to A. If A wants to send messages to B, it first needs to encrypt the messages with B's public keys, and then send them to B. At this time, B decrypts the messages with its own private keys. When B sends messages to A, the same is true. Reason.

# Several Symmetry Encryption Algorithms: AES,DES,3DES

DES is a kind of block data encryption technology (first dividing the data into small blocks of fixed length, then encrypting). It is fast and suitable for a large number of data encryption. While 3DES is a DES-based encryption algorithm, which uses three different keys to encrypt the same block three times, so as to make the ciphertext stronger.

Compared with DES and 3DES algorithms, AES algorithm has higher speed and resource utilization efficiency, and higher security level. It is called the next generation encryption standard.

# Several Asymmetric Encryption Algorithms: RSA,DSA,ECC

RSA and DSA have similar security and other performance, while ECC has many advantages over them, including processing speed, bandwidth requirements, storage space and so on.

# Several Linear Hash Algorithms (Signature Algorithms): MD5,SHA1,HMAC

These algorithms only generate a series of irreversible ciphertext, often use it to verify whether the data transmission process has been modified, because the same generation algorithm for the same plaintext will only generate a unique ciphertext, if the same algorithm generates different ciphertext, it proves that the transmission data has been modified. Usually, before the data legend process, using MD5 and SHA1 algorithms both need to know the key generation algorithm before data transmission. HMAC is different from HMAC in that it needs to generate a key. The sender uses this key to digest the data (generate ciphertext), and the receiver uses this key to digest the received data and then judge the generation. Is the ciphertext the same?

# For the selection of various encryption algorithms:

Because the key management of symmetric encryption algorithm is a complex process, the key management directly determines its security, so when the amount of data is very small, we can consider using asymmetric encryption algorithm.

In the actual operation process, we usually use asymmetric encryption algorithm to manage the key of symmetric algorithm, and then use symmetric encryption algorithm to encrypt data, so we integrate the advantages of two kinds of encryption algorithm, which not only realizes the advantages of fast encryption speed, but also realizes the advantages of safe and convenient key management.

If the encryption algorithm is selected, how many keys are used?

Generally speaking, the longer the key is, the slower the running speed is. It should be selected according to the security level we need. Generally speaking, RSA recommends 1024 bits, ECC recommends 160 bits and AES 128 bits.

# Implementation of AES

``````import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class AESUtil {
public static byte[] encrypt(String content, String password) {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");// Create a cryptograph
byte[] byteContent = content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE, key);// Initialization
byte[] result = cipher.doFinal(byteContent);
return result; // encryption
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
e.printStackTrace();
}
return null;
}

public static String encryptString(String content, String password) {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");// Create a cryptograph
byte[] byteContent = content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE, key);// Initialization
byte[] result = cipher.doFinal(byteContent);
String encryptResultStr = parseByte2HexStr(result);
return encryptResultStr;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
e.printStackTrace();
}
return null;
}

public static byte[] decrypt(byte[] content, String password) {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");// Create a cryptograph
cipher.init(Cipher.DECRYPT_MODE, key);// Initialization
byte[] result = cipher.doFinal(content);
return result; // encryption
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
e.printStackTrace();
}
return null;
}

public static String decrypt(String content, String password) {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decryptFrom = parseHexStr2Byte(content);
byte[] result = cipher.doFinal(decryptFrom);
return new String(result);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
e.printStackTrace();
}
return null;
}

public static String parseByte2HexStr(byte buf[]) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}

public static byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < 1)
return null;
byte[] result = new byte[hexStr.length() / 2];
for (int i = 0; i < hexStr.length() / 2; i++) {
int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
result[i] = (byte) (high * 16 + low);
}
return result;
}

public static void main(String[] args) {
String content = "test";
// encryption
System.out.println("Before encryption:" + content);
String encryptResultStr = parseByte2HexStr(encryptResult);
System.out.println("After encryption:" + encryptResultStr);
// Decrypt
byte[] decryptFrom = parseHexStr2Byte(encryptResultStr);
System.out.println("After decryption:" + new String(decryptResult));

String enStr = encryptString("123", "@#&^%-\$#@Coupon#\$%^&@*");

System.out.println(enStr);
}
}``````

# Implementation of SHA1 and MD5

``````import java.security.MessageDigest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

public abstract class EncodeUtil {

private static Logger logger = LoggerFactory.getLogger(EncodeUtil.class);

/**
* Define encryption
*/
private final static String KEY_SHA = "SHA";
private final static String MD5 = "MD5";

/**
* SHA encryption
*
* @param data String to be encrypted
* @return Encrypted string
*/
public static String sha(String data) {
// Verify the incoming string
if (StringUtils.isEmpty(data)) {
return "";
}
try {
// Create a digest of information with the specified algorithm name
MessageDigest sha = MessageDigest.getInstance(KEY_SHA);
// Use the specified byte array to last update the digest
sha.update(data.getBytes("utf-8"));
// Complete summary calculation
byte[] bytes = sha.digest();
// Turn the resulting byte array into a string to return
return byteArrayToHexString(bytes);
} catch (Exception e) {
logger.error("String usage SHA Encryption failure", e);
return null;
}
}

/**
* MD5 encryption
*
* @param data String to be encrypted
* @return Encrypted string
*/
public static String md5(String source) {
// Verify the incoming string
if (StringUtils.isEmpty(source)) {
return "";
}

try {
MessageDigest md = MessageDigest.getInstance(MD5);
byte[] bytes = md.digest(source.getBytes("utf-8"));
return byteArrayToHexString(bytes);
} catch (Exception e) {
logger.error("String usage Md5 Encryption failure" + source + "' to MD5!", e);
return null;
}
}

/**
* Convert byte arrays to hexadecimal strings
*
* @param bytes
*            Byte array
*/
private static String byteArrayToHexString(byte[] bytes) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
sb.append(Integer.toHexString((bytes[i] & 0xFF) | 0x100).toUpperCase().substring(1, 3));
}
return sb.toString();
}

/**
* test method
*
* @param args
*/
public static void main(String[] args) throws Exception {
String key = "123";
System.out.println(sha(key));
System.out.println(md5(key));
}
}``````

Reference resources:

http://blog.csdn.net/cws1214/article/details/18604075

http://blog.csdn.net/happylee6688/article/details/43953671

Keywords: Java SHA1

Added by nick314 on Sun, 16 Jun 2019 22:57:04 +0300