1.首先封装MD5工具类如下;
/**
* MD5英文全称“Message-Digest Algorithm 5”,翻译过来是“消息摘要算法5”,由MD2、MD3、MD4演变过来的,是一种单向加密算法,是不可逆的一种的加密方式。
* <p>
* MD5应用场景:
* 1.一致性验证
* 2.数字签名
* 3.安全访问认证
*/
public class Md5Util {
/**
* 计算字符串MD5值
*/
public static String encrypt(String string) {
if (TextUtils.isEmpty(string)) {
return "";
}
MessageDigest md5 = null;
try {
//获得MD5摘要算法的 MessageDigest 对象
md5 = MessageDigest.getInstance("MD5");
//获得密文
byte[] bytes = md5.digest(string.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 "";
}
/**
* 计算文件的MD5值(nio方法)
*/
public static String encrypt(File file) {
String result = "";
FileInputStream in = null;
try {
in = new FileInputStream(file);
MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(byteBuffer);
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加密
*
* @param times 加密次数
*/
public static String encrypt(String string, int times) {
if (TextUtils.isEmpty(string)) {
return "";
}
String md5 = encrypt(string);
for (int i = 0; i < times - 1; i++) {
md5 = encrypt(md5);
}
return encrypt(md5);
}
/**
* MD5加盐
* 加盐的方式:
* 1.string+key(盐值key)然后进行MD5加密
* 2.用string明文的hashcode作为盐,然后进行MD5加密
* 3.随机生成一串字符串作为盐,然后进行MD5加密
*/
public static String encrypt(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 "";
}
}
2.调用的参数形式为String
//假设参数为 "name","黄家驹";"age","18";"sex","男"
String encrypt = Md5Util.encrypt("name" + "黄家驹" + "&age" + "18" + "&sex" + "男");
Log.e("MD5",encrypt);
输出;1f04400727db71ae4041796fa3fb4dda
//想多次循环假如循环五次
String encrypt1 = Md5Util.encrypt(encrypt, 5);
Log.e("5次加密",encrypt1);
输出; bc6efcea3c522b596ecadfc301e3d367