MessageDigest类提供MD5或SHA等加密算法
MessageDigest可使用的加密方法有MD2\MD5\SHA-1\SHA-256\SHA-384\SHA-512,使用时候只替换相应参数值即可
MessageDigest md5 = MessageDigest.getInstance("MD5");
MessageDigest md5 = MessageDigest.getInstance("MD2");
MessageDigest md5 = MessageDigest.getInstance("SHA-1");
````````````````````````````````````````````````
以MD5加密为例的代码,代码中使用两种方式转换为十六进制格式数据输出
@Test public void test() throws NoSuchAlgorithmException, UnsupportedEncodingException { String str = "a"; MessageDigest md5 = MessageDigest.getInstance("MD5"); byte[] bytes = md5.digest(str.getBytes("utf-8")); StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < bytes.length; i++) { //0x表示十六进制,使用&0xff是在byte转int时,做补码处理,保证二进制数据一致性,计算机存储的是补码 //整数转十六进制使用Integer的toHexString方法 String tempStr = Integer.toHexString(bytes[i] & 0xff); if (tempStr.length() == 1) //如果长度为1补0 stringBuilder.append("0").append(tempStr); else stringBuilder.append(tempStr); //分割符如:0c:c1:75:b9:c0:f1:b6:a8:31:c3:99:e2:69:77:26:61 if (i < bytes.length - 1) stringBuilder.append(":"); } System.out.println(stringBuilder.toString()); stringBuilder=new StringBuilder(); for (int i = 0; i < bytes.length; i++) { int chartIndex = bytes[i] & 0xff; //整数转十六进制,小于16的为0~F,要补0输出 if (chartIndex < 16) { stringBuilder.append("0"); } stringBuilder.append(Integer.toHexString(chartIndex)); if (i < bytes.length - 1) stringBuilder.append(":"); } System.out.println(stringBuilder.toString()); }