md5加密的方法代码,在程序开发中很多重要的信息,密码等都要用md5加密,希望对大家有用,很好玩的,你可以试一试.
public class MD5Encode {
private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
/**
* 转换字节数组为16进制字串
*
* @param b
* 字节数组
* @return 16进制字串
*/
public static String byteArrayToHexString(byte[] b) {
StringBuffer resSb = new StringBuffer();
for (int i = 0; i < b.length; i++) {
resSb.append(byteToHexString(b[i]));
}
return resSb.toString();
}
private static String byteToHexString(byte b) {
int n = b;
if (n < 0)
n = 256 + n;
int d1 = n / 16;
int d2 = n % 16;
return hexDigits[d1] + hexDigits[d2];
}
public static String getMD5Str(String str) {
String resStr = "";
try {
MessageDigest md = MessageDigest.getInstance("MD5");
resStr = byteArrayToHexString(md.digest(str.getBytes()));
} catch (Exception ex) {
// PTK.inst().wWarn(PTK.getExceptionFullStr(ex));
}
return resStr;
}
public static String encodePWD(String userid, String pwd) {
return getMD5Str(userid.toUpperCase() + ":" + pwd);
}
public static String getFileMD5(String fn) {
return getFileMD5(new File(fn));
}
public static String getFileMD5(File file) {
FileInputStream fis = null;
try {
MessageDigest md = MessageDigest.getInstance("MD5");
fis = new FileInputStream(file);
byte[] buffer = new byte[8192];
int length = -1;
while ((length = fis.read(buffer)) != -1) {
md.update(buffer, 0, length);
}
return byteArrayToHexString(md.digest());
} catch (Exception ex) {
return null;
} finally {
// UnZipUtil.closeStream(fis);
}
}
public static void main(String[] args) {
System.out.println("mohwst=" + encodePWD("1", "demo112233"));
}
} |
|