java MD5 加密實現

Away_D發表於2017-08-03


public static void main(String[] args){

System.out.println(Md5("aa",32));

System.out.println(Md5("aa",16));

}

//md5加密  32/16

private static String Md5(String plainText ,int length) { 

String re = null;


try

MessageDigest md = MessageDigest.getInstance("MD5"); 

md.update(plainText.getBytes()); 

byte b[] = md.digest(); 


int i


StringBuffer buf = new StringBuffer(""); 

for (int offset = 0; offset < b.length; offset++) { 

i = b[offset]; 

if(i<0) i+= 256; 

if(i<16) 

buf.append("0"); 

buf.append(Integer.toHexString(i)); 

switch(length){

case 32:

re= buf.toString();

break;

case 16:

re=buf.toString().substring(8,24);

break;

default:

break;

}

return re.toUpperCase();

} catch (NoSuchAlgorithmException e) { 

// TODO Auto-generated catch block 

e.printStackTrace(); 

}

return "failed"


相關文章