数据(密码)加密
1.报错加密的交易密码
/**
* 保存用户交易密码
*
* @param user
* @param payPassword
*/
public boolean setPayPassword(User user, @NotNull String payPassword) {
if (user == null) {
log.error("user is null. do not save payPassword!");
return false;
}
// 生成交易密码盐
String payPasswordSalt = getSalt();
// 保存交易密码
user.setPayPassword(getEncryptedPassword(payPassword, payPasswordSalt));
user.setPayPasswordSalt(payPasswordSalt);
return this.updateByPrimaryKey(user) > 0;
}
/**
* 盐函数
* @return
*/
private String getSalt() {
//生成随机[a-z]字符串,包含大小写
return RandomStringUtils.randomAlphanumeric(6);
}
/**
* 生产密文
* @param password
* @param salt
* @return
*/
private String getEncryptedPassword(String password, String salt) {
return EncryptUtils.md5(password + salt);
}
/**
* 校验用户的交易密码
* @param user
* @param payPassword
*/
public boolean checkPayPassword(User user, @NotNull String payPassword) {
if (user == null) {
log.error("user is null by user {}", JSON.toJSONString(user));
return false;
}
String payPasswordMD5 = null;
// 如果有交易密码盐,需要添加交易密码盐加密
if (StringUtils.isNotBlank(user.getPayPasswordSalt())) {
payPasswordMD5 = getEncryptedPassword(payPassword, user.getPayPasswordSalt());
} else {
payPasswordMD5 = EncryptUtils.md5(payPassword);
}
return payPasswordMD5.equals(user.getPayPassword());
}
/**
* 生成MD5
*
* @param message
* @return
*/
public static String md5(String message) {
String md5 = "";
try {
// 创建一个md5算法对象
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] messageByte = message.getBytes("UTF-8");
// 获得MD5字节数组,16*8=128位
byte[] md5Byte = md.digest(messageByte);
// 转换为16进制字符串
md5 = bytesToHex(md5Byte);
} catch (Exception e) {
log.error(String.format("md5 error %s", e.getMessage()));
}
return md5;
}
// 二进制转十六进制
protected static String bytesToHex(byte[] bytes) {
StringBuffer hexStr = new StringBuffer();
int num;
for (int i = 0; i < bytes.length; i++) {
num = bytes[i];
if (num < 0) {
num += 256;
}
if (num < 16) {
hexStr.append("0");
}
hexStr.append(Integer.toHexString(num));
}
return hexStr.toString().toUpperCase();
}