最近工作需要用到关于MD5的加密,遂自己脑补了一番;
MD5呢主要用于保护消息的完整性,它是一种经典的哈希算法,所以一般咱们用来加密数据.
那么 在安卓端如何使用MD5呢. 其实java.security .中有一个MessageDigest 类能够直接帮我们生成MD5码
例如:
public class MD5Util {
/**
* 将字符串转成MD5值
*
* @param string
* @return
*/
public static String stringToMD5(String string) {
byte[] hash;
try {
hash = MessageDigest.getInstance("MD5").digest(
string.getBytes("UTF-8"));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
StringBuilder hex = new StringBuilder(hash.length * 2);
for (byte b : hash) {
if ((b & 0xFF) < 0x10)
hex.append("0");
hex.append(Integer.toHexString(b & 0xFF));
}
return hex.toString();
}
}
测试结果图:
验证图: