W3Schools Learner's Blog

W3Schools Programming knowledge summary website

div

11/30/2017

java md5 encrypt string example

md5 encrypt string is simple in java, we can use the native MD5 encryption method, and we can use third party encryption tools, but third party encryption tools need to lead the jar package.
for example commons-codec maven:
<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.11</version>
</dependency>

how to md5 encrypt string? as follows.
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.apache.commons.codec.digest.DigestUtils;

public class ArrayDemo {
    public static void main(String[] args) throws NoSuchAlgorithmException {    
        String str = "hello world";

        //java MD5 native encryption method 
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] arr = md.digest(str.getBytes());
        String md5Str = md5ToString(arr);
        System.out.println(md5Str);
        
        //the third party encryption method
        byte[] md5 = DigestUtils.md5(str);
        String md5Str2 =  md5ToString(md5);
        System.out.println(md5Str2);
        
        //the third party encryption method that returns the MD5 hex string
        String md5Str3 = DigestUtils.md5Hex(str.getBytes());
        System.out.println(md5Str3);
    }
    
    //将md5数组转化为16进制字符串
    public static String md5ToString(byte[] md5){
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < md5.length; i++) {
               int temp = md5[i] & 0Xff;
               String hexString = Integer.toHexString(temp);
               if (hexString.length() < 2) {
                sb.append("0").append(hexString);
               } else {
                sb.append(hexString);
               }
        }
        return sb.toString();
    }
}

note: the md5 native encryption method in java.security jar package, the third party encryption method in org.apache.commons.codec.digest jar package.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.