哈希md5加密

72 阅读1分钟

md5加密不太安全,一些场景下也可以使用下,下面例举下在java中如何实现md5的实现

代码实现

package org.example.test;
import java.security.MessageDigest;
public class Md5Test {

    public static void main(String[] args) {

        String s = md5("你好呀,md5");

        System.out.println(s);
    }

        public static String md5(String input) {
            try {
                MessageDigest md = MessageDigest.getInstance("MD5");
                byte[] digest = md.digest(input.getBytes());
                return bytesToHex(digest);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        private static String bytesToHex(byte[] bytes) {
            StringBuilder hex = new StringBuilder();
            for (byte b : bytes) {
                String hexChar = Integer.toHexString(0xff & b);
                if (hexChar.length() == 1) hex.append('0');
                hex.append(hexChar);
            }
            return hex.toString();
        }

}