Java 关于原生的MD5加密的使用及进制转换代码2014-11-19 10:13:43
( 3人已投票,[高质量] )
Java 关于原生的MD5加密的使用方法,下面直接上代码了
package test.demo001; import java.security.MessageDigest; public class MD5Util { public final static String MD5(String s) { char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; try { byte[] btInput = s.getBytes(); // MD5摘要 MessageDigest mdInst = MessageDigest.getInstance("MD5"); // 指定的字节更新摘要 mdInst.update(btInput); // 密文 byte[] md = mdInst.digest(); // 将密文转换成十六进制的字符串 int j = md.length; char str[] = new char[j * 2]; int k = 0; for (int i = 0; i < j; i++) { byte byte0 = md[i]; str[k++] = hexDigits[byte0 >>> 4 & 0xf]; str[k++] = hexDigits[byte0 & 0xf]; } return new String(str); } catch (Exception e) { e.printStackTrace(); return null; } } public static void main(String[] args) { System.out.println(testClass.MD5("20121220")); //486B54009AC2BA6BDE21ACA441BE9BB2 System.out.println(testClass.MD5("Encrypt")); //611D29C748A7931C825A247FCF3F290E } }
下面是关于进制转换,方便调试(非常有用):
1:string to hex
//String to byte private byte[] StringToHex(String s){ int n = s.length()/2; byte[] r = new byte[n]; for (int i = 0; i < n; i ++) { char a = s.charAt(i*2); char b = s.charAt(i*2 + 1); r[i]=(byte) ((CharToInt(a) << 4) | CharToInt(b)); } return r; }
2:char to int
private static int CharToInt(char ch) { if ('a' <= ch && ch <= 'f') { return ch - 'a' + 10; } if ('A' <= ch && ch <= 'F') { return ch - 'A' + 10; } if ('0' <= ch && ch <= '9') { return ch - '0'; } throw new IllegalArgumentException(String.valueOf(ch)); }
3:hex to string
//print hex to string private String HexToString(byte[] byBuf, int len){ String res =""; for (int i = 0; i < len; i++) {//byBuf.length String hex = Integer.toHexString(byBuf[i] & 0xFF); if (hex.length() == 1) { hex = '0' + hex; } res +=hex.toUpperCase(); } return res; }