Skip to content
Merged

Dev #303

Show file tree
Hide file tree
Changes from 19 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

<groupId>io.github.talelin</groupId>
<artifactId>latticy</artifactId>
<version>0.2.0-RELEASE</version>
<version>0.2.1-RELEASE</version>
<name>latticy</name>
<description>Demo project for lin cms</description>

Expand Down
17 changes: 17 additions & 0 deletions src/main/java/io/github/talelin/latticy/bo/LoginCaptchaBO.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package io.github.talelin.latticy.bo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
* @author Gadfly
* @since 2021-11-19 15:20
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class LoginCaptchaBO {
private String captcha;
private Long expired;
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import com.baomidou.mybatisplus.core.injector.ISqlInjector;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import io.github.talelin.autoconfigure.bean.PermissionMetaCollector;
import io.github.talelin.latticy.common.interceptor.RequestLogInterceptor;
import io.github.talelin.latticy.module.log.MDCAccessServletFilter;
Expand Down Expand Up @@ -72,7 +72,7 @@ public Jackson2ObjectMapperBuilderCustomizer customJackson() {
return jacksonObjectMapperBuilder -> {
// jacksonObjectMapperBuilder.serializationInclusion(JsonInclude.Include.NON_NULL);
jacksonObjectMapperBuilder.failOnUnknownProperties(false);
jacksonObjectMapperBuilder.propertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
jacksonObjectMapperBuilder.propertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE);
};
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package io.github.talelin.latticy.common.configuration;

import io.github.talelin.latticy.common.util.CaptchaUtil;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
* @author Gadfly
*/
@Slf4j
@Getter
@Setter
@Component
@ConfigurationProperties(prefix = "login-captcha")
public class LoginCaptchaProperties {
/**
* aes 密钥
*/
private String secret = CaptchaUtil.getRandomString(32);
/**
* aes 偏移量
*/
private String iv = CaptchaUtil.getRandomString(16);
/**
* 启用验证码
*/
private Boolean enabled = Boolean.FALSE;

public void setSecret(String secret) {
if (StringUtils.hasText(secret)) {
byte[] bytes = secret.getBytes();
if (bytes.length == 16 || bytes.length == 24 || bytes.length == 32) {
this.secret = secret;
} else {
log.warn("AES密钥必须为128/192/256bit,输入的密钥为{}bit,已启用随机密钥{}", bytes.length * 8, this.secret);
}
}
}

public void setIv(String iv) {
if (StringUtils.hasText(iv)) {
byte[] bytes = iv.getBytes();
if (bytes.length == 16) {
this.iv = iv;
} else {
log.warn("AES初始向量必须为128bit,输入的密钥为{}bit,已启用随机向量{}", bytes.length * 8, this.iv);
}
}
}

}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package io.github.talelin.latticy.common.interceptor;

import io.github.talelin.latticy.common.util.IPUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

Expand Down Expand Up @@ -27,7 +28,7 @@ public void afterCompletion(HttpServletRequest request, HttpServletResponse resp
log.info("[{}] -> [{}] from: {} costs: {}ms",
request.getMethod(),
request.getServletPath(),
request.getRemoteAddr(),
IPUtil.getIPFromRequest(request),
System.currentTimeMillis() - startTime.get()
);
}
Expand Down
195 changes: 195 additions & 0 deletions src/main/java/io/github/talelin/latticy/common/util/CaptchaUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
package io.github.talelin.latticy.common.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.talelin.latticy.bo.LoginCaptchaBO;
import org.springframework.core.io.ClassPathResource;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Base64;
import java.util.Random;

/**
* @author Gadfly
*/
@SuppressWarnings("SpellCheckingInspection")
public class CaptchaUtil {

/**
* 验证码字符个数
*/
public static final int RANDOM_STR_NUM = 4;
private static final Random RANDOM = new Random();
/**
* 验证码的宽
*/
private static final int WIDTH = 80;
/**
* 验证码的高
*/
private static final int HEIGHT = 40;
private static final String RANDOM_STRING = "23456789abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWSYZ";
private static final String AES = "AES";
private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
private static final ObjectMapper MAPPER = new ObjectMapper();

static {
java.security.Security.setProperty("crypto.policy", "unlimited");
}

/**
* 颜色的设置
*/
private static Color getRandomColor(int fc, int bc) {

fc = Math.min(fc, 255);
bc = Math.min(bc, 255);

int r = fc + RANDOM.nextInt(bc - fc - 16);
int g = fc + RANDOM.nextInt(bc - fc - 14);
int b = fc + RANDOM.nextInt(bc - fc - 12);

return new Color(r, g, b);
}

/**
* 字体的设置
*/
private static Font getFont() throws IOException, FontFormatException {
ClassPathResource dejavuSerifBold = new ClassPathResource("DejaVuSerif-Bold.ttf");
return Font.createFont(Font.TRUETYPE_FONT, dejavuSerifBold.getInputStream()).deriveFont(Font.BOLD, 24);
}

/**
* 随机字符的获取
*/
public static String getRandomString(int num) {
num = num > 0 ? num : RANDOM_STRING.length();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < num; i++) {
int number = RANDOM.nextInt(RANDOM_STRING.length());
sb.append(RANDOM_STRING.charAt(number));
}
return sb.toString();
}

/**
* 干扰线的绘制
*/
private static void drawLine(Graphics2D g) {
int x = RANDOM.nextInt(WIDTH);
int y = RANDOM.nextInt(HEIGHT);
int xl = WIDTH;
int yl = HEIGHT;
g.setStroke(new BasicStroke(2.0f));
g.setColor(getRandomColor(98, 200));
g.drawLine(x, y, x + xl, y + yl);
}

/**
* 字符串的绘制
*/
private static void drawString(Graphics2D g, String randomStr, int i) throws IOException, FontFormatException {
g.setFont(getFont());
g.setColor(getRandomColor(28, 130));
// 设置每个字符的随机旋转
double radianPercent = (RANDOM.nextBoolean() ? -1 : 1) * Math.PI * (RANDOM.nextInt(60) / 320D);
g.rotate(radianPercent, WIDTH * 0.8 / RANDOM_STR_NUM * i, HEIGHT / 2);
int y = (RANDOM.nextBoolean() ? -1 : 1) * RANDOM.nextInt(4) + 4;
g.translate(RANDOM.nextInt(3), y);
g.drawString(randomStr, WIDTH / RANDOM_STR_NUM * i, HEIGHT / 2);
g.rotate(-radianPercent, WIDTH * 0.8 / RANDOM_STR_NUM * i, HEIGHT / 2);
g.translate(0, -y);
}

private static BufferedImage getBufferedImage(String code) throws IOException, FontFormatException {
// BufferedImage类是具有缓冲区的Image类,Image类是用于描述图像信息的类
BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_BGR);
Graphics2D g = (Graphics2D) image.getGraphics();
g.fillRect(0, 0, WIDTH, HEIGHT);
g.setColor(getRandomColor(105, 189));
g.setFont(getFont());
int lineSize = RANDOM.nextInt(5);
// 干扰线
for (int i = 0; i < lineSize; i++) {
drawLine(g);
}
// 随机字符
for (int i = 0; i < code.length(); i++) {
drawString(g, String.valueOf(code.charAt(i)), i);
}
g.dispose();
return image;
}

/**
* 生成随机图片的base64编码字符串
*
* @param code 验证码
* @return base64
*/
public static String getRandomCodeBase64(String code) throws IOException, FontFormatException {
BufferedImage image = getBufferedImage(code);
// 返回 base64
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageIO.write(image, "PNG", bos);

byte[] bytes = bos.toByteArray();
Base64.Encoder encoder = Base64.getEncoder();

return encoder.encodeToString(bytes);
}

public static String getTag(String captcha, String secret, String iv) throws JsonProcessingException, GeneralSecurityException {
LocalDateTime time = LocalDateTime.now().plusMinutes(5);
LoginCaptchaBO captchaBO = new LoginCaptchaBO(captcha, time.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
String json = MAPPER.writeValueAsString(captchaBO);
return aesEncode(secret, iv, json);
}

public static LoginCaptchaBO decodeTag(String secret, String iv, String tag) throws JsonProcessingException, GeneralSecurityException {
String decrypted = aesDecode(secret, iv, tag);
return MAPPER.readValue(decrypted, LoginCaptchaBO.class);
}

/**
* AES加密
*/
public static String aesEncode(String secret, String iv, String content) throws GeneralSecurityException {
SecretKey secretKey = new SecretKeySpec(secret.getBytes(), AES);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(iv.getBytes(StandardCharsets.US_ASCII)));
byte[] byteEncode = content.getBytes(StandardCharsets.UTF_8);
// 根据密码器的初始化方式加密
byte[] byteAES = cipher.doFinal(byteEncode);

// 将加密后的数据转换为字符串
return Base64.getEncoder().encodeToString(byteAES);
}

/**
* AES解密
*/
public static String aesDecode(String secret, String iv, String content) throws GeneralSecurityException {
SecretKey secretKey = new SecretKeySpec(secret.getBytes(), AES);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(iv.getBytes(StandardCharsets.US_ASCII)));
// 将加密并编码后的内容解码成字节数组
byte[] byteContent = Base64.getDecoder().decode(content);
// 解密
byte[] byteDecode = cipher.doFinal(byteContent);
return new String(byteDecode, StandardCharsets.UTF_8);
}
}
48 changes: 48 additions & 0 deletions src/main/java/io/github/talelin/latticy/common/util/IPUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package io.github.talelin.latticy.common.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
* IP工具类
*/
@Slf4j
public class IPUtil {

private static final String[] IP_HEADER_CANDIDATES = {
"X-Forwarded-For",
"Proxy-Client-IP",
"WL-Proxy-Client-IP",
"HTTP_X_FORWARDED_FOR",
"HTTP_X_FORWARDED",
"HTTP_X_CLUSTER_CLIENT_IP",
"HTTP_CLIENT_IP",
"HTTP_FORWARDED_FOR",
"HTTP_FORWARDED",
"HTTP_VIA",
"REMOTE_ADDR"
};

public static String getIPFromRequest(HttpServletRequest request) {
if (request == null) {
if (null == RequestContextHolder.getRequestAttributes()) {
return null;
}
request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
}

for (String header : IP_HEADER_CANDIDATES) {
String ipList = request.getHeader(header);
if (ipList != null && ipList.length() != 0 && !"unknown".equalsIgnoreCase(ipList)) {
log.debug("ipList.split(\",\")[0]::{}", ipList.split(",")[0]);
return ipList.split(",")[0];
}
}

log.debug("request.getRemoteAddr()::{}", request.getRemoteAddr());
return request.getRemoteAddr();
}
}
Loading