Java中MD5算法为什么要&FF

463 阅读1分钟

java 中 Md5 常规写法 :

1.  public static String md5Encode(String inputStr) {  
2.          MessageDigest md5 = null;  
3.          try {  
4.              md5 = MessageDigest.getInstance("MD5");  
5.              byte[] bytes = inputStr.getBytes("UTF-8");  
6.              byte[] md5Bytes = md5.digest(bytes);  
7.              StringBuffer hexValue = new StringBuffer();  
8.              for (int i = 0; i < md5Bytes.length; i++) {  
9.                    
10.                  int value = ((int) md5Bytes[i]) & 0xff;  //问题所在
11.                    
12.                  if (value < 16) {  
13.                      hexValue.append("0");  
14.                  }  
15.                  hexValue.append(Integer.toHexString(value));  //关键位置
16.                    
17.              }  
18.              return hexValue.toString();  
19.                
20.          } catch (Exception e) {  
21.              return "";  
22.          }  
23.            
24.      }
int value = ((int) md5Bytes[i]) & 0xff;  这里的&0xff是为什么?

因为Integer.toHexString(int) 其参数是int,大小为4个字节->32位,而byte类型大小是1个字节->8位。

这就导致byte转化为int时,可能造成一个问题:byte前24位中可能存在数据。

所以应该将byte前24位置零:byte & 0xff

  例如:0x3 & 0xff 
  (前24位未知)0000 0011 & (前24位都是0)1111 1111 = (24位0) 0000 0011

总结: 在处理byte转int时,需要&0xff,做前24位赋零操作,防止转化出现问题。