Java MD5生成器
这是使用Java Swing写的一个MD5生成器。
项目名:create_md5
项目语言:Java swing;
构建工具:maven;
使用IDE:eclipse
程序运行界面如下:
功能:
(1)获取指定文件的MD5值;
(2)获取指定一段文本的MD5值
说明:本文中,MD5值使用十六进制位串表示。
如何获取文件的MD5值呢?
/**
* Get MD5 of one file:hex string,test OK!
*
* @param file
* @return : hex string
*/
public static String getFileMD5(File file) {
if (!file.exists() || !file.isFile()) {
return null;
}
MessageDigest digest = null;
FileInputStream in = null;
byte buffer[] = new byte[1024];
int len;
try {
digest = MessageDigest.getInstance("MD5");
in = new FileInputStream(file);
while ((len = in.read(buffer, 0, 1024)) != -1) {
digest.update(buffer, 0, len);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
BigInteger bigInt = new BigInteger(1, digest.digest());
return bigInt.toString(16);
}
/***
* Get MD5 of one file!test ok!
*
* @param filepath
* @return
*/
public static String getFileMD5(String filepath) {
File file = new File(filepath);
return getFileMD5(file);
}
如何获取一段文本的MD5值呢?
public static final char[] HEXCHAR = { '0', '1', '2', '3', '4', '5', '6',
'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
public static byte[] digest(byte srcBytes[], String algorithm)
throws NoSuchAlgorithmException {
MessageDigest digest = MessageDigest.getInstance(algorithm);
digest.update(srcBytes);
byte digestBytes[] = digest.digest();
return digestBytes;
}
public static String getMD5(String source) throws NoSuchAlgorithmException {
byte bytes[] = digest(source.getBytes(), "MD5");
return toHexString(bytes);
}
/***
* convert byte array to hex(16) bit string
*
* @param byte[]
* @return hex(16) bit string
*/
public static String toHexString(byte[] b) {
StringBuilder sb = new StringBuilder(b.length * 2);
for (int i = 0; i < b.length; i++) {
sb.append(HEXCHAR[(b[i] & 0xf0) >>> 4]);
sb.append(HEXCHAR[b[i] & 0x0f]);
}
return sb.toString();
}
项目结构如下:
项目源码见附件