1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| package com.utils;
import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Scanner;
public class MD5Util {
public static String stringMD5(String input) {
try {
MessageDigest messageDigest =MessageDigest.getInstance("MD5");
byte[] inputByteArray = input.getBytes();
messageDigest.update(inputByteArray);
byte[] resultByteArray = messageDigest.digest();
return byteArrayToHex(resultByteArray); } catch (NoSuchAlgorithmException e) { return null; } }
public static String byteArrayToHex(byte[] byteArray) {
char[] hexDigits = {'0','1','2','3','4','5','6','7','8','9', 'A','B','C','D','E','F' };
char[] resultCharArray =new char[byteArray.length * 2];
int index = 0;
for (byte b : byteArray) { resultCharArray[index++] = hexDigits[b>>> 4 & 0xf]; resultCharArray[index++] = hexDigits[b& 0xf]; }
return new String(resultCharArray); }
public static void main(String[] args) { MD5Util md5Util = new MD5Util(); Scanner input = new Scanner(System.in); while (true) { System.out.println("请输入:"); String in = input.nextLine(); String value = md5Util.stringMD5(in); System.out.println("加密前:" + in); System.out.println("加密后:" + value + ",长度:" + value.length()); } } }
|
效果图:
代码出自https://www.cnblogs.com/hihtml5/p/6064999.html