Commit 935101cc by suxiaochun

增加登录加密传输

上传接口增加白名单
parent 07948711
package io.office.common.enumpack; package io.office.common.enumpack;
/** /**
*
* 
 @description: * 
 @description:
* *
* @author wudi * @author wudi
...@@ -12,7 +11,9 @@ public enum ErrorCodeEnum { ...@@ -12,7 +11,9 @@ public enum ErrorCodeEnum {
FAIL(-1, "失败"),//失败 FAIL(-1, "失败"),//失败
FILE_IS_NULL(10001,"上传文件不能为空!"); FILE_IS_NULL(10001, "上传文件不能为空!"),
FILE_TYPE_IS_NULL(10002, "文件格式不合法!");
private Integer code; private Integer code;
private String msg; private String msg;
...@@ -34,4 +35,4 @@ public enum ErrorCodeEnum { ...@@ -34,4 +35,4 @@ public enum ErrorCodeEnum {
return this.msg; return this.msg;
} }
} }
package io.office.modules.manage.utils;
import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
public class RSAUtils {
//公钥
private static String PUBLICKEYSTR = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANOf6KgVV4tc+QGyoFWMPGNpYSitenD8sqiei5KliOExO0Cq+bE1LaaFpvNPgg4H/600YsCa0Yn7P/DwbugTwe0CAwEAAQ==";
//私钥
private static String PRIVATEKEYSTR = "MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEA05/oqBVXi1z5AbKgVYw8Y2lhKK16cPyyqJ6LkqWI4TE7QKr5sTUtpoWm80+CDgf/rTRiwJrRifs/8PBu6BPB7QIDAQABAkEAsCS4jTb+YCRpqm0YoTwRg5lR4n7KnELpHgqhF9WqoexJuLyUpyIMk8SxrbZm2fkQfxT6Vy1i81XDkl0ZSrrETQIhAPDGa7YTE8MdBJ0Cv6ojtrVYSGPC2DMbv/Kl3mQ3G4bjAiEA4QGchaxk4AcnZ5K12ExiKg6dBkT4BS5Z+w6Ek6TgHO8CIGlnU6vnehVGVMivdVx0Of31YetaVu84zLTa7BqPDVvlAiA0mCLVICnoL+PnEuUMrTYY7JeJup9a3q3LwGX++QAl4wIhAMe4uayU/U3jksvzbWRAjPEctCSkqdeelDFjqDplHOyj";
private static final String ALGORITHM = "RSA";
// 加密方法
public static String encrypt(String plainText) throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, getPublicKeyFromString(PUBLICKEYSTR));
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
}
// 解密方法
public static String decrypt(String encryptedText) throws Exception {
byte[] encryptedBytes = Base64.getDecoder().decode(encryptedText);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, getPrivateKeyFromString(PRIVATEKEYSTR));
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
return new String(decryptedBytes);
}
// 从字符串格式的公钥创建 PublicKey 对象
public static PublicKey getPublicKeyFromString(String publicKeyString) throws Exception {
byte[] publicKeyBytes = Base64.getDecoder().decode(publicKeyString);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
return keyFactory.generatePublic(keySpec);
}
// 从字符串格式的私钥创建 PrivateKey 对象
public static PrivateKey getPrivateKeyFromString(String privateKeyString) throws Exception {
byte[] privateKeyBytes = Base64.getDecoder().decode(privateKeyString);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
return keyFactory.generatePrivate(keySpec);
}
public static void main(String[] args) throws Exception {
// 要加密的明文
String plainText = "Hello, RSA!";
// 使用公钥进行加密
String encryptedText = encrypt(plainText);
// 打印加密结果
System.out.println("Encrypted: " + encryptedText);
// 使用私钥进行解密
String decryptedText = decrypt(encryptedText);
// 打印解密结果
System.out.println("Decrypted: " + decryptedText);
}
/**
* 生成密钥
*/
private static void createKeys() {
try {
// 创建KeyPairGenerator对象,指定算法为RSA
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
// 初始化KeyPairGenerator对象,设置密钥长度为2048位
keyPairGenerator.initialize(512);
// 生成KeyPair对象,即公钥和私钥
KeyPair keyPair = keyPairGenerator.generateKeyPair();
// 获取公钥和私钥
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
// 将公钥和私钥转换为字符串格式
String publicKeyStr = Base64.getEncoder().encodeToString(publicKey.getEncoded());
String privateKeyStr = Base64.getEncoder().encodeToString(privateKey.getEncoded());
// 打印公钥和私钥字符串
System.out.println("公钥:" + publicKeyStr);
System.out.println("私钥:" + privateKeyStr);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
}
...@@ -11,7 +11,9 @@ import org.springframework.web.multipart.MultipartFile; ...@@ -11,7 +11,9 @@ import org.springframework.web.multipart.MultipartFile;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.Arrays;
import java.util.Date; import java.util.Date;
import java.util.List;
/** /**
* TODO * TODO
...@@ -48,14 +50,19 @@ public class UploadUtils { ...@@ -48,14 +50,19 @@ public class UploadUtils {
} }
String filename = ""; String filename = "";
filename = file.getOriginalFilename(); filename = file.getOriginalFilename();
String type = filename.substring(filename.lastIndexOf("."));
if (!hasAccess(type.toLowerCase())) {
throw new RRException(ErrorCodeEnum.FILE_TYPE_IS_NULL);
}
File fileDir = new File(fileSavePath + DateUtils.formatDateToString(new Date(), DateUtils.FORMAT4) + "/"); File fileDir = new File(fileSavePath + DateUtils.formatDateToString(new Date(), DateUtils.FORMAT4) + "/");
if (!fileDir.exists()) { if (!fileDir.exists()) {
fileDir.mkdirs(); fileDir.mkdirs();
} }
String uuid = idWorkService.getSEQByKey(IdKeysConstant.ID_SEQ_KEY); String uuid = idWorkService.getSEQByKey(IdKeysConstant.ID_SEQ_KEY);
String dateDirPath = DateUtils.formatDateToString(new Date(), DateUtils.FORMAT4); String dateDirPath = DateUtils.formatDateToString(new Date(), DateUtils.FORMAT4);
String returnFilename = fileRequestPrefix + dateDirPath +"/" +uuid+"-"+ filename; String returnFilename = fileRequestPrefix + dateDirPath + "/" + uuid + "-" + filename;
filename = fileSavePath + dateDirPath +"/" +uuid+"-"+filename; filename = fileSavePath + dateDirPath + "/" + uuid + "-" + filename;
File dest = new File(filename); File dest = new File(filename);
try { try {
file.transferTo(dest); file.transferTo(dest);
...@@ -66,6 +73,12 @@ public class UploadUtils { ...@@ -66,6 +73,12 @@ public class UploadUtils {
} }
public boolean hasAccess(String type) {
return WHITELIST.contains(type);
}
public static List<String> WHITELIST = Arrays.asList(".jpg", ".jpeg", ".png", ".gif", ".bmp", ".tiff", ".xls", ".xlsx", ".pdf");
/** /**
* 根据全路径名获取businessId * 根据全路径名获取businessId
* "http://10.0.20.46:6051/emgcysys/uploadFile/2021-03-23/1374288822837604352.JAVA核心面试知识整理.pdf", * "http://10.0.20.46:6051/emgcysys/uploadFile/2021-03-23/1374288822837604352.JAVA核心面试知识整理.pdf",
......
/** /**
* Copyright (c) 2016-2019 人人开源 All rights reserved. * Copyright (c) 2016-2019 人人开源 All rights reserved.
* * <p>
* https://www.renren.io * https://www.renren.io
* * <p>
* 版权所有,侵权必究! * 版权所有,侵权必究!
*/ */
...@@ -10,15 +10,20 @@ package io.office.modules.sys.controller; ...@@ -10,15 +10,20 @@ package io.office.modules.sys.controller;
import io.office.common.utils.R; import io.office.common.utils.R;
import io.office.modules.app.annotation.Login; import io.office.modules.app.annotation.Login;
import io.office.modules.manage.utils.RSAUtils;
import io.office.modules.sys.entity.SysUserEntity; import io.office.modules.sys.entity.SysUserEntity;
import io.office.modules.sys.form.SysLoginForm; import io.office.modules.sys.form.SysLoginForm;
import io.office.modules.sys.service.SysCaptchaService; import io.office.modules.sys.service.SysCaptchaService;
import io.office.modules.sys.service.SysUserService; import io.office.modules.sys.service.SysUserService;
import io.office.modules.sys.service.SysUserTokenService; import io.office.modules.sys.service.SysUserTokenService;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash; import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.imageio.ImageIO; import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream; import javax.servlet.ServletOutputStream;
...@@ -34,66 +39,79 @@ import java.util.Map; ...@@ -34,66 +39,79 @@ import java.util.Map;
*/ */
@RestController @RestController
public class SysLoginController extends AbstractController { public class SysLoginController extends AbstractController {
@Autowired @Autowired
private SysUserService sysUserService; private SysUserService sysUserService;
@Autowired @Autowired
private SysUserTokenService sysUserTokenService; private SysUserTokenService sysUserTokenService;
@Autowired @Autowired
private SysCaptchaService sysCaptchaService; private SysCaptchaService sysCaptchaService;
/** /**
* 验证码 * 验证码
*/ */
@GetMapping("captcha.jpg") @GetMapping("captcha.jpg")
public void captcha(HttpServletResponse response, String uuid)throws IOException { public void captcha(HttpServletResponse response, String uuid) throws IOException {
response.setHeader("Cache-Control", "no-store, no-cache"); response.setHeader("Cache-Control", "no-store, no-cache");
response.setContentType("image/jpeg"); response.setContentType("image/jpeg");
//获取图片验证码 //获取图片验证码
BufferedImage image = sysCaptchaService.getCaptcha(uuid); BufferedImage image = sysCaptchaService.getCaptcha(uuid);
ServletOutputStream out = response.getOutputStream(); ServletOutputStream out = response.getOutputStream();
ImageIO.write(image, "jpg", out); ImageIO.write(image, "jpg", out);
IOUtils.closeQuietly(out); IOUtils.closeQuietly(out);
} }
/** /**
* 登录 * 登录
*/ */
@Login @Login
@RequestMapping("/sys/login") @RequestMapping("/sys/login")
public Map<String, Object> login(@RequestBody SysLoginForm form)throws IOException { public Map<String, Object> login(@RequestBody SysLoginForm form) throws IOException {
/*boolean captcha = sysCaptchaService.validate(form.getUuid(), form.getCaptcha()); /*boolean captcha = sysCaptchaService.validate(form.getUuid(), form.getCaptcha());
if(!captcha){ if(!captcha){
return R.error("验证码不正确"); return R.error("验证码不正确");
}*/ }*/
//用户信息 //202406 增加加密传输
SysUserEntity user = sysUserService.queryByUserName(form.getUsername()); String username = form.getUsername();
String password = form.getPassword();
//账号不存在、密码错误 if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
if(user == null || !user.getPassword().equals(new Sha256Hash(form.getPassword(), user.getSalt()).toHex())) { return R.error("账号或密码不能为空");
return R.error("账号或密码不正确"); }
} try {
username = RSAUtils.decrypt(username);
//账号锁定 password = RSAUtils.decrypt(password);
if(user.getStatus() == 0){ } catch (Exception e) {
return R.error("账号已被锁定,请联系管理员"); return R.error("解密失败,请联系管理员:" + e.getLocalizedMessage());
} }
//生成token,并保存到数据库 //用户信息
R r = sysUserTokenService.createToken(user.getUserId()); SysUserEntity user = sysUserService.queryByUserName(username);
return r;
} //账号不存在、密码错误
if (user == null || !user.getPassword().equals(new Sha256Hash(password, user.getSalt()).toHex())) {
return R.error("账号或密码不正确");
/** }
* 退出
*/ //账号锁定
@RequestMapping("/sys/logout") if (user.getStatus() == 0) {
public R logout() { return R.error("账号已被锁定,请联系管理员");
sysUserTokenService.logout(getUserId()); }
return R.ok();
} //生成token,并保存到数据库
R r = sysUserTokenService.createToken(user.getUserId());
return r;
}
/**
* 退出
*/
@RequestMapping("/sys/logout")
public R logout() {
sysUserTokenService.logout(getUserId());
return R.ok();
}
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment