1.什么是MD5加密
MD5的全称是Message-Digest Algorithm 5(信息-摘要算法),经MD2、MD3和MD4发展而来。不可逆的加密算法
2.MD5加密的特点
- 任意长度的数据,算出的MD5值长度都是固定的
- 从原数据计算出MD5值很容易
- 对原数据进行任何改动,所得到的MD5值都有很大区别
- 有加密结果很难算出源数据
3.加密实现
1. 字符串MD5加密分别分为16位和32位,以及大写和小写
private static char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
public static String getBytesMD5(byte[] bytes) {
try {
// 获得MD5摘要算法的 MessageDigest 对象
MessageDigest mdInst = MessageDigest.getInstance("MD5");
// 使用指定的字节更新摘要
mdInst.update(bytes);
// 获得密文
byte[] md = mdInst.digest();
// 把密文转换成十六进制的字符串形式
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
//返回大写加密值
// return new String(str).toUpperCase();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 返回字符串的32位MD5值
*
* @param s
* 字符串
* @return str MD5值
*/
public final static String getStringMD5(String s) {
return getBytesMD5(s.getBytes());
}
/**
* 返回字符串的16位MD5值
*
* @param s
* 字符串
* @return str MD5值
*/
public final static String getStringMD5_16(String s) {
return getStringMD5(s).substring(8, 24);
}
2.文件加密
public static String md5(File file) {
if (file == null || !file.isFile() || !file.exists()) {
return "";
}
FileInputStream in = null;
String result = "";
byte buffer[] = new byte[8192];
int len;
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
in = new FileInputStream(file);
while ((len = in.read(buffer)) != -1) {
md5.update(buffer, 0, len);
}
byte[] bytes = md5.digest();
for (byte b : bytes) {
String temp = Integer.toHexString(b & 0xff);
if (temp.length() == 1) {
temp = "0" + temp;
}
result += temp;
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if(null!=in){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
3.图片加密
/**
* bitmap 加密32
*/
public final static String getBitmapMD5(Bitmap bm) {
return getBytesMD5(bitmapToBytes(bm));
}
/**
* bitmap 加密16
*/
public final static String getBitmapMD5_16(Bitmap bm) {
return getBytesMD5(bitmapToBytes(bm)).substring(8, 24);
}
public static byte[] bitmapToBytes(Bitmap bm) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}
普通的md5加密很好破解,那么有什么方法可以加大破解难度呢?
- 对源数据多次进行加密
- 采用MD5加盐的方式
所谓的加盐就是要加密的数据+key值之后进行md5加密
key值可以是 数据的hash值,随机数字
public static String md5(String string, String slat) {
if (TextUtils.isEmpty(string)) {
return "";
}
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
byte[] bytes = md5.digest((string + slat).getBytes());
String result = "";
for (byte b : bytes) {
String temp = Integer.toHexString(b & 0xff);
if (temp.length() == 1) {
temp = "0" + temp;
}
result += temp;
}
return result;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}