Android传输数据时MD5加密详解
MD5加密算法
一、特点
1. 长度固定:不管多长的字符串,加密后长度都是一样长。方便信息的统计和管理。
2. 易计算:字符串和文件加密的过程容易。开发者很容易理解和做出加密工具。
3. 抗修改:对原数据哪怕只有一个字节的修改,得到的MD5值都有很大区别
4. 不可逆:知道密文和加密方式,却无法反向计算出原密码。
注:
v md5加密无法找回密码,只能修改密码;
v 在使用过成中,对比密码是否正确,只能把密码md5加密后对照加密后的数据是否相同。
v 在使用过成中,也可以建立一个大型的数据库,把日常各个语句,通过MD5加密成密文,不断积累大量的句子,放在一个庞大的数据库里,就可以拿着密文去数据库查询密码。
二、MD5加密算法实现
1. 计算字符串MD5值
思路过程:
v str.getBytes():将字符串转化为字节数组。字符串中每个字符转换为对应的ASCII值作为字节数组中的一个元素。
v 将字节数组通过固定算法转换为16个元素的有符号哈希值字节数组
v 将哈希字节数组的每个元素通过0xff与运算转换为两位无符号16进制的字符串
v 将不足两位的无符号16进制的字符串前面加0
v 通过StringBuffer.append()或者StringBundle.append()将16个长度为2的无符号进制字符串合并为一个32位String类型的MD5码
|
public static String md5(String str) {
if (TextUtils.isEmpty(str)) {
return "";
}
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
byte[] bytes = md5.digest(str.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 "";
}
|
2. 计算文件的MD5值
|
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;
}
|
三、MD5加大破解难度
虽说MD5是不可逆的,但并不是不可破译的,网上有很多MD5解密的网站,不过破解机制采用穷举法。就是我们平时所说的跑字典,如特点中所说的在一个大型的数据库中查找对应的MD解密值。那么,如何加大MD5破解难度?
1. 对字符串多次MD5加密
|
public static String md5(String str, int times) {
if (TextUtils.isEmpty(str)) {
return "";
}
String md5 = md5(str);
for (int i = 0; i < times - 1; i++) {
md5 = md5(md5);
}
return md5(md5);
}
|
2. MD5“加盐”
v string+key(盐值key)然后进行MD5加密
v 用string明文的hashcode作为盐,然后进行MD5加密
v 随机生成一串字符串作为盐,然后进行MD5加密
|
public static String md5(String str, String key) {
if (TextUtils.isEmpty(str)) {
return "";
}
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
byte[] bytes = md5.digest((str + key).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 "";
}
|