Common encryption methods in java

Keywords: encoding codec Apache Maven

First, import the jar package, commons-codec.jar. You can use maven or go to the maven official website to download the jar

https://mvnrepository.com/artifact/commons-codec/commons-codec/1.12

<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.12</version>
</dependency>
  1. MD5 encryption

MD5 (message digest algorithm encryption is an irreversible encryption algorithm with high security. There are some websites on the network that provide MD5 cracking, and their principles are database collision. Okay, let's start a little bit more
MD5 encryption can be used in java. Of course, it is not needed here. We use commons-codec.jar under apache
DigestUtils.md5Hex is a method that can pass in three types of parameters for different scenarios,

  1. Character string

    The encrypted 32-bit hexadecimal string will be returned after passing in the string

  2. byte array

    The encrypted 32-bit hexadecimal string will also be returned after passing in the byte array

  3. Input stream

    Ditto,

package encoding;

import org.apache.commons.codec.digest.DigestUtils;

public class MD5Encrypt {
    public static void main(String[] args) {
        String encoding = encoding("I love you!");
        System.out.println(encoding);
    }

    /**
     *
     * @param data Passing in the data to be encrypted can be passed into byte array, string, and input stream to see what you want (md5Hex method)
     * @return
     */
    public static String encoding(String data) {
        String getEncoding = DigestUtils.md5Hex(data);
        return getEncoding;
    }
}

The result of the operation is

4f2016c6b934d55bd7120e5d0e62cce3

As for MD5, you can use the official one if you are interested.

  1. SHA256 encryption

    Using SHA256 encryption is similar to MD5 encryption, which is also irreversible encryption

    package encoding;
    
    import org.apache.commons.codec.digest.DigestUtils;
    
    public class MD5Encrypt {
        public static void main(String[] args) {
            String encoding = SHA256encoding("I love you!");
            System.out.println(encoding);
        }
    
        /**
         *
         * @param data Passing in the data to be encrypted can be passed into byte array, string, and input stream to see what you want (sha256Hex method)
         * @return
         */
        public static String SHA256encoding(String data) {
            String getEncoding = DigestUtils.sha256Hex(data);
            return getEncoding;
        }
    }
    

    The result is

    c0ad5411b19cfcba9d674d21411a970159f6ae4e180831ddd6a91797be547752
    

    The rest of Base64 will be encrypted and added later. In the future, an official and saved lower jar package will be produced.

Posted by candy2126 on Tue, 19 Nov 2019 09:54:28 -0800