通常在登录或者文件上传这些个功能中会用到要给密码啊文件加密,一般会用到的就是MD5了
这里我就是简单记录下,也方便自己以后使用
private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
/**
* 字节数组To16进制字符串
*
* @param b 字节数组
* @return 16进制字符串
*/
private static String convertToHexString(byte[] b) {
StringBuilder sb = new StringBuilder(b.length * 2);
for (byte a : b) {
sb.append(HEX_DIGITS[(a & 0xf0) >>> 4]);
sb.append(HEX_DIGITS[a & 0x0f]);
}
return sb.toString();
}
/**
* 获取字符串的HashCode值
*
* @param str String
* @return HashCode
*/
public static String getMD5String(String str) {
MessageDigest md5;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
return null;
}
md5.update(str.getBytes());
return convertToHexString(md5.digest());
}
/**
* 获取文件的HashCode值
*
* @param file File
* @return HashCode
*/
public static String getMD5String(File file) {
// 创建 md5
MessageDigest md5;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
return null;
}
InputStream in = null;
byte[] buffer = new byte[1024];
int numRead;
// 读取文件内容
try {
in = new FileInputStream(file);
while ((numRead = in.read(buffer)) > 0) {
md5.update(buffer, 0, numRead);
}
return convertToHexString(md5.digest());
} catch (Exception e) {
return null;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* MD5解密
*
* @param inStr HashCode值
* @return 字符串
*/
public static String convertMD5(String inStr) {
char[] a = inStr.toCharArray();
for (int i = 0; i < a.length; i++) {
a[i] = (char) (a[i] ^ 't');
}
return new String(a);
}
日常记录