package com.tiesheng.util.config; import cn.hutool.core.codec.Base64; import cn.hutool.core.util.NumberUtil; import cn.hutool.core.util.RandomUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.crypto.SecureUtil; import cn.hutool.crypto.SmUtil; import cn.hutool.crypto.symmetric.SM4; import com.tiesheng.util.ServletKit; import com.tiesheng.util.TimedCacheHelper; import com.tiesheng.util.exception.ApiException; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; /** * @author hao */ @Configuration @ConfigurationProperties(prefix = "tiesheng.encrypt") public class EncryptConfig { /** * 加解密对象 */ private final SM4 sm4; /** * 加密密钥 */ private String key = "WmdUzPJXbngVNiaSsQrihg=="; private Integer saltSize = 8; private boolean body = false; public EncryptConfig() { sm4 = SmUtil.sm4(Base64.decode(getKey())); } /** * 加密 * * @param content * @return */ public String encrypt(String content) { if (StrUtil.isEmpty(content)) { return ""; } return sm4.encryptBase64(content); } /** * 解密 * * @param base64 * @return */ public String decrypt(String base64) { try { return sm4.decryptStr(base64); } catch (Exception ignore) { } return base64; } /** * 创建密码 * * @param inputPasswd * @param salt 盐,不存将自动生成 * @return */ public String passwdCreate(String inputPasswd, String salt) { if (StrUtil.isEmpty(salt) || StrUtil.length(salt) != getSaltSize()) { salt = RandomUtil.randomString(saltSize); } if (!passwdComplexity(inputPasswd)) { throw new ApiException("需要包含数字、大小写字母、特殊符号,且长度不低于8位"); } return encrypt(salt + SecureUtil.sha1(salt + inputPasswd)); } /** * 复杂度校验 * * @param inputPasswd * @return */ public boolean passwdComplexity(String inputPasswd) { String password = "^(?![A-Za-z0-9]+$)(?![a-z0-9\\W]+$)(?![A-Za-z\\W]+$)(?![A-Z0-9\\W]+$)[a-zA-Z0-9\\W]{8,}$"; return inputPasswd.matches(password); } /** * 密码校验 * * @param inputPasswd */ public void passwdVerify(String inputPasswd, String encrypted) { String salt = decrypt(encrypted).substring(0, saltSize); String inputEncrypted = passwdCreate(inputPasswd, salt); if (!StrUtil.equals(inputEncrypted, encrypted)) { String clientIp = ServletKit.getClientIP(); int num = NumberUtil.parseInt(TimedCacheHelper.getTimedCache().get(clientIp, false)); if (num > 5) { throw new ApiException("登录失败已达6次,请10分钟后再试"); } TimedCacheHelper.getTimedCache().put(clientIp, String.valueOf(num + 1), 10 * 60 * 1000); throw new ApiException("账号或密码错误"); } } /////////////////////////////////////////////////////////////////////////// // setter\getter /////////////////////////////////////////////////////////////////////////// public String getKey() { return key; } public void setKey(String key) { this.key = key; } public Integer getSaltSize() { return saltSize; } public void setSaltSize(Integer saltSize) { this.saltSize = saltSize; } public boolean isBody() { return body; } public void setBody(boolean body) { this.body = body; } }