W3Schools Learner's Blog

W3Schools Programming knowledge summary website



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:

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);
        //the third party encryption method
        byte[] md5 = DigestUtils.md5(str);
        String md5Str2 =  md5ToString(md5);
        //the third party encryption method that returns the MD5 hex string
        String md5Str3 = DigestUtils.md5Hex(str.getBytes());
    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) {
               } else {
        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.