Java encryption algorithm

There are three encryption algorithms in Java:

1. One-way encryption algorithm

2. Right and wrong encryption algorithm

3. Asymmetric encryption algorithm 

One-way encryption algorithm

One-way encryption is an irreversible encryption algorithm. The encrypted ciphertext cannot be decrypted. Common algorithms include MD5, SHA, and HMAC.

MD5 (Message Digest Algorithm)

No matter how long the data is, it is finally encoded into 128-bit data, and the same data is always consistent.

Purpose: It can be used for file verification, password encryption, and hashing data.

Code:

public static String getMD5Str(String s) {
    try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] bytes = md.digest(s.getBytes("utf-8"));
        return toHex(bytes);
    }
    catch (Exception e) {
        throw new RuntimeException(e);
    }
}
public static String toHex(byte[] bytes) {
    final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray();
    StringBuilder ret = new StringBuilder(bytes.length * 2);
    for (int i=0; i<bytes.length; i++) {
        ret.append(HEX_DIGITS[(bytes[i] >> 4) & 0x0f]);
        ret.append(HEX_DIGITS[bytes[i] & 0x0f]);
    }
    return ret.toString();
}

public static void main(String[] args) {
    System.out.println(getMD5Str("123456")); //输出E10ADC3949BA59ABBE56E057F20F883E
}
View Code

Notice:

1. The calculated string length is 32, each character is a hexadecimal number, and a hexadecimal number converted into binary is four bits, that is, a 32-length string is converted into bits 32 * 4 = 128 bits.

2. The calculated value must be 32 characters, 16 of which are part of the intercepted result.

SHA (Secure Hash Algorithm)

The security is higher than MD5, and the encrypted results are all 160-bit data, and the use is similar to MD5.

The five algorithms of the SHA family are SHA-1, SHA-224, SHA-256, SHA-384, and SHA-512, the latter four are sometimes referred to together as SHA-2.

HMAC (Hash Message Authentication Code)

Purpose: It is often used for request verification of API parameters.

Symmetric encryption algorithm

The same key can be encrypted or decrypted, common algorithms DES, AES, PBE.

DES (Data Encryption Standard)

There are three entry parameters of the DES algorithm: Key, Data, and Mode. Among them, Key is 7 bytes with a total of 56 bits, which is the working key of DES algorithm; Data is 8 bytes and 64 bits, which is the data to be encrypted or decrypted; Mode is the working mode of DES, there are two kinds: encryption or decrypt.

AES (an upgraded version of DES)

PBE (Password Based Encryption)

Asymmetric encryption algorithm

Two keys are required. The public key encrypts data, and the private key decrypts the data; the private key is used to sign, and the public key verifies the signature; common algorithms RSA, DH. 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324977805&siteId=291194637