需要用到MD5加密时在网上找到了这么一段代码,简洁有效,所以备份到这里。
需要传入明文密码字符串。
返回值为加密的MD5字符串。
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class PasswordToMD5 {
/**
* MD5加密
* @param password 密码
* @return String 加密后用16进制表示的字符串(MD5字符串)
*/
public String encodePassdigiest(String password) {
byte[] enclyptedHash = null;
// 通过MD5加密的Byte数组
MessageDigest md5;
try {
md5 = MessageDigest.getInstance("MD5");
md5.update(password.getBytes());
enclyptedHash = md5.digest();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return bytesToHexString(enclyptedHash);
}
/**
* 暗号化されたByte型配列を、16進数表記文字列に変換する
* @param fromByte 加密了的byte数组
* @return String 16进制字符串
*/
private String bytesToHexString(byte[] fromByte) {
StringBuilder hexStrBuilder = new StringBuilder();
for (int i = 0; i < fromByte.length; i++) {
// 用16进制表示只有一位的情况下,第二位补零
if ((fromByte[i] & 0xff) < 0x10) {
hexStrBuilder.append("0");
}
hexStrBuilder.append(Integer.toHexString(0xff & fromByte[i]));
}
return hexStrBuilder.toString();
}
}