使用md5对密码加密
工具类代码:
//md5加密
public static String md5(String source) {
//判断传入的字符串状态
if (source == null || source.length() == 0) {
//传入空的字符串,抛出异常,由全局异常处理器处理
throw new RuntimeException(CrowdConstant.STRING_INVALIDATE.getMsg());
}
//传入的有值,进行md5加密
try {
//声明要使用什么算发加密
String algorithm = "md5";
//创建加密对象
MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
//获取传入的字符串的字节数组
byte[] sourceBytes = source.getBytes();
//加密
byte[] output = messageDigest.digest(sourceBytes);
// 6.创建 BigInteger 对象
int signum = 1;
//参数1:-1代表生成负数 0代表零 1代表整数
//参数2:加密的字节数组
BigInteger bigInteger = new BigInteger(signum, output);
// 7.按照 16 进制将 bigInteger 的值转换为字符串
int radix = 16;
//把转换完成的字节数组转换为16进制的字符串,并把字符变为大写
String encoded = bigInteger.toString(radix).toUpperCase();
//把md5加密后的字符串返回
return encoded;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
测试:
@Test
public void md5(){
String pass="123456";
String s = Md5Util.md5(pass);
System.out.println(s);
}
结果:E10ADC3949BA59ABBE56E057F20F883E