java中用MessageDigest类,可以用来加密MD5。
首先创建一个MessageDigest对象
MessageDigest digest = MessageDigest.getInstance("MD5");
调用digest.digest(psd.getBytes());会返回一个16位的字符串,然后使用规定的模板转换为32位即可。
for (byte b : bs) { String hexString = Integer.toHexString(b & 0xff); if (hexString.length() < 2) { hexString = "0" + hexString; } stringBuffer.append(hexString); }
完整的代码:
1 import java.security.MessageDigest; 2 import java.security.NoSuchAlgorithmException; 3 4 public class Md5Util { 5 6 /** 7 * @param args 8 */ 9 public static void main(String[] args) {10 String psd = "123";11 encoder(psd);12 }13 14 private static void encoder(String psd) {15 try {16 MessageDigest digest = MessageDigest.getInstance("MD5");17 byte[] bs = digest.digest(psd.getBytes());18 System.out.println(bs.length);19 StringBuffer stringBuffer = new StringBuffer();20 for (byte b : bs) {21 String hexString = Integer.toHexString(b & 0xff);22 if (hexString.length() < 2) {23 hexString = "0" + hexString;24 }25 stringBuffer.append(hexString);26 }27 System.out.println(stringBuffer.toString());28 } catch (NoSuchAlgorithmException e) {29 e.printStackTrace();30 }31 32 }33 34 }