/**
* 这里只是调用JDK自带的MD5算法
* @param data
* @return
*/
public static final String getMD5String(byte[] data) {
MessageDigest digest = null;
try {
digest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
if (digest == null) {
return null;
}
digest.update(data);
return encodeHex(digest.digest());
}
/**
* 字节数组转16进制字符串
*
* @param bytes
* @return
*/
public static final String encodeHex(byte[] bytes) {
StringBuffer buf = new StringBuffer(bytes.length * 2);
int i;
for (i = 0; i < bytes.length; i++) {
if ((bytes[i] & 0xff) < 0x10) {
buf.append("0");
}
buf.append(Long.toString(bytes[i] & 0xff, 16));
}
return buf.toString();
}
JDK自带有MD5省的自己算了,,,怎么计算文件的MD5值呢,将文件转化为byte数组,然后再计算就可以了
/**
* 将文件转化为字节数组
*
* @param filePath
* @return
*/
public static byte[] getBytes(String filePath) {
byte[] buffer = null;
try {
File file = new File(filePath);
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
byte[] b = new byte[1000];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
bos.close();
buffer = bos.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return buffer;
}
MD5用来验证数据完整性,写过的项目中就是使用MD5计算过后将用户密码保存到数据库中的,除了用户自己,连管理员都不知道用户的密码是什么可以提高数据安全哦
还有MD5是不可逆的,所以只能从原数据得到MD5,而不能从MD5得到原数据。
看了下网上所谓的MD5解密,不过时记录了大量字符串的MD5值,然后遍历查询罢了,很笨很耗时的方法,文件的是破解不了的。。
嗯哼,就这么多,,,end
2016/09/21 16:24
还有上文中将getInstance传入的参数改为
SHA-1
SHA-256
SHA-384
SHA-512
就可以变声相应的sha消息摘要算法了