BCrypt, MD5, AES, HS256 and other encryption algorithms and their uses – encryption algorithm essentials

BCrypt is said to be better than MD5? What reversible encryption algorithm, symmetric encryption algorithm, asymmetric encryption algorithm, irreversible encryption algorithm! Want to master it? Just read this one!

guidance

In the process of development, large system architectures will often involve the use of encryption algorithms. Many students just use something like Base64, MD5, digital signature or BCrypt for encryption. But the nature of the encryption is less clear as to why. Why is more important than how!

Or that sentence: there must be a demand, just spawned technology!

The use of technology [code] is simple, but how to use [cash] is difficult.

Revenue + demand +deadline is the first productivity of the siege lion

Based on the confusion of small partners, male elder brother here to do illiteracy, simple sorting out the encryption algorithm, focus on the demand scene! Take us an article, take down the encryption algorithm

What is the encryption algorithm

An encryption algorithm is basically a function that locks data.

The basic process of data encryption:

  1. The processing of a file or data originally in plaintext by an algorithm
  2. Encrypted data is unreadable and is ciphertext.
  3. The original image can only be displayed after the corresponding key is entered

** Goal: ** through the way of encryption algorithm to achieve, protect the data is not stolen by the unlegal person, the purpose of reading!

The reverse of this process is decryption.

Two, the type of encryption algorithm

  • Reversible encryption algorithm, features: encryption, but also can decrypt the algorithm
    • Symmetric encryption
    • Asymmetric encryption
  • Irreversible encryption algorithm, features: encryption, can never decrypt the algorithm. Not even to the end of the universe
  • Base64 coding: many students feel Base64 is not encryption algorithm, but strictly speaking really calculate encryption algorithm!

Three, reversible encryption algorithm

Explanation: After encryption, the ciphertext can be decrypted to get the original password.

3.1 Symmetric Encryption

[File encryption and decryption use the same key, that is, the encryption key can also be used as the decryption key]

Explanation: in the symmetric encryption algorithm, data transmitting will definitely with the encryption key after dealing with the special encryption algorithm, make it into a complex encryption cipher sent out, the receiving party, after receipt of the ciphertext to decipher the text, you need to use encrypted with the key and the inverse algorithm of the same encryption algorithm to decrypt the ciphertext to, to make it back into a readable plaintext. In a symmetric encryption algorithm, only one key is used. Both the sender and the receiver use this key, so the decryptor needs to know the encryption key in advance.

Advantages: The symmetric encryption algorithm has the advantages of open algorithm, small computation, fast encryption speed, and high encryption efficiency.

Cons: No asymmetric encryption security.

Purpose: Generally used to save users’ mobile phone number, ID card and other sensitive but decrypted information.

Common symmetric encryption algorithms are AES, DES, 3DES, Blowfish, IDEA, RC4, RC5, RC6, and HS256

3.2 Asymmetric encryption

[two keys: publickey and private key, publickey encryption, private key decryption]

** Generates two keys at the same time: the private key and the public key. The private key is stored secretly, and the public key can be sent to the trusted client.

Encryption and decryption:

  • Private key encryption, can be decrypted only with a private key or public key

  • Public key encryption, private key can be decrypted

Signature:

  • Private key signature, holding the public key to verify whether tampering.

** Advantages: ** Asymmetric encryption compared with symmetric encryption, better security;

Disadvantages: Asymmetric encryption takes a long time to encrypt and decrypt, and is slow. It is only suitable for encrypting a small amount of data. Purpose: Used for signing and authentication. The private key is held by the server for encryption, and the public key is held by the client for decryption or verification of the token or signature.

Common asymmetric encryption algorithms include RSA, DSA (for digital signature), ECC (for mobile devices), and RS256 (for SHA-256 RSA signature).

4. Irreversible encryption algorithm

Explanation: Once encrypted, you cannot reverse decrypt the original password.

Categories: Hash encryption algorithm, Hash algorithm, digest algorithm, etc

** Uses: ** Generally used to verify the correctness of download files, generally download files on the website can be seen; Store sensitive user information, such as passwords and card numbers, that cannot be decrypted.

Common irreversible encryption algorithms include MD5, SHA, and HMAC

Fifth, Base64 encoding

Base64 is one of the most common encoding methods for transmitting 8Bit byte code on the network. Base64 encoding can be used to pass longer identity information in HTTP environments. Base64Base64 encoding and decoding is not readable, that is, the encoded data will not be directly seen by the naked eye. Note: Base64 is only an encoding method, not an encryption method.

Online coding tool: www.jsons.cn/img2base64/

Six, BCrypt quickly master

In the system architecture, the protection of user passwords is usually encrypted. We usually encrypt the password and store it in the database. When a user logs in, the password is encrypted and compared with the ciphertext stored in the database to verify whether the user’s password is correct. At present, MD5 and BCrypt are popular. BCrypt is relatively more secure than MD5.

BCrypt website www.mindrot.org/projects/jB…

(1) We download the source code from the official website

(2) New project, copy the source code class BCrypt to the project

(3) Create a test class, write code in the main method to achieve the encryption of the password

String gensalt = BCrypt.gensalt();// This is salt 29 characters, randomly generated
System.out.println(gensalt);
String password = BCrypt.hashpw("The male elder brother 666", gensalt);  // Encrypt the password based on salt
System.out.println(password);// The first 29 bits of the encrypted string are salt
Copy the code

(4) Create a test class and write code in the main method to verify the password. BCrypt does not support reverse computing, only password verification.

boolean checkpw = BCrypt.checkpw("The male elder brother 666"."$2a$10$61ogZY7EXsMDWeVGQpDq3OBF1.phaUu7.xrwLyWFTOu8woE08zMIW");
System.out.println(checkpw);
Copy the code

How to use BCrypt in your own projects

7.1 Adding User Account Password Encryption

Add user account information and use BCrypt to encrypt the password

Code implementation

(1) Copy the source code of BCrypt to its own project utils package

(2) Modify the project UserServiceImpl

/** * add *@param User
     */
@Override
public void add(User user){
    String password = BCrypt.hashpw(User.getPassword(), BCrypt.gensalt());
    user.setPassword(password);   
    userMapper.insert(user);
}
Copy the code

7.2 Verifying user Login Passwords

Demand analysis

System users need to log in to the background system and enter the user name and password to log in.

Ideas:

  1. The user sends the request and enters the user name and password
  2. The microservice controller of the background system receives the parameters and verifies whether the user name and password are correct. If they are correct, the system returns a successful login result

Code implementation

(1) UserService added method definition

    /** * Login authentication password *@param User
     * @return* /
    boolean login(User user);
Copy the code

UserServiceImpl implements this method

    @Override
    public boolean login(User user) {
        // Query the administrator based on the login name
        User u1=new User();
        u1.setLoginName(User.getLoginName());
        u1.setStatus("1");
        User u2 = UserMapper.selectOne(u1);// Database query object
        if(u2==null) {return false;
        }else{
            // Verify the password, Bcrypt is the spring package, the first parameter is plain password, the second parameter is ciphertext password
            returnBCrypt.checkpw(u1.getPassword(),u2.getPassword()); }}Copy the code

(3) UserController new method

    /** * login *@param User
     * @return* /
    @PostMapping("/login")
    public Result login(@RequestBody User user){
        boolean login = UserService.login(user);
        if(login){
            return new Result();
        }else{
            return new Result(false,StatusCode.LOGINERROR,"Wrong username or password"); }}Copy the code

conclusion

This article nuggets first, do not forward to other platforms without permission! Please respect the original, thank you