import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* @author anyone
* @version 1.0.0.0/2011-8-8
*/
public class MD5 {
private static final byte RESULT_32 = 32;
private static final byte RESULT_16 = 16;
public static String encode32(String text){
return encodeText(text, RESULT_32);
}
public static String encode16(String text){
return encodeText(text, RESULT_16);
}
public static String encode32(byte[] bytes){
return encodeBytes(bytes, RESULT_32);
}
public static String encode16(byte[] bytes){
return encodeBytes(bytes, RESULT_16);
}
private static String encode(byte[] bytes, byte result){
String resultStr = encode(bytes);
if(RESULT_32 == result){
return resultStr;
}
return resultStr.substring(8, 24);
}
private static String encodeBytes(byte[] bytes, byte result) {
byte[] originalBytes = null;
try {
originalBytes = getBytes(bytes);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return encode(originalBytes, result);
}
private static String encodeText(String plainText, byte result) {
byte[] originalBytes = null;
try {
originalBytes = getBytes(plainText);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return encode(originalBytes, result);
}
private static String encode(byte bytes[]){
int i;
StringBuffer buf = new StringBuffer();
for (int offset = 0; offset < bytes.length; offset++) {
i = bytes[offset];
if (i < 0)
i += 256;
if (i < 16)
buf.append("0");
buf.append(Integer.toHexString(i));
}
return buf.toString();
}
private static byte[] getBytes(String plainText) throws NoSuchAlgorithmException{
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(plainText.getBytes());
return md5.digest();
}
private static byte[] getBytes(byte[] bytes) throws NoSuchAlgorithmException{
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(bytes);
return md5.digest();
}
// public static void main(String[] args){
// System.out.println(MD5.encode32("abc")); // 900150983cd24fb0d6963f7d28e17f72
// System.out.println(MD5.encode32("abc".getBytes())); // 900150983cd24fb0d6963f7d28e17f72
// System.out.println(MD5.encode32("")); // d41d8cd98f00b204e9800998ecf8427e
// System.out.println(MD5.encode32("".getBytes())); // d41d8cd98f00b204e9800998ecf8427e
// System.out.println(MD5.encode32("abcdefghijklmnopqrstuvwxyz")); // c3fcd3d76192e4007dfb496cca67e13b
// System.out.println(MD5.encode32("abcdefghijklmnopqrstuvwxyz".getBytes())); // c3fcd3d76192e4007dfb496cca67e13b
// System.out.println(MD5.encode32("message digest"));// f96b697d7cb7938d525a2f31aaf161d0
// System.out.println(MD5.encode32("message digest".getBytes()));// f96b697d7cb7938d525a2f31aaf161d0
// }
}
java实现生成MD5码
最新推荐文章于 2021-04-08 15:32:13 发布