完成前端加密

This commit is contained in:
2019-06-11 21:23:29 +08:00
parent 7473c0e36a
commit 7a3105c414
49 changed files with 769 additions and 738 deletions
@@ -1,7 +1,9 @@
package net.alawn.bill.config;
import lombok.extern.slf4j.Slf4j;
import net.alawn.bill.security.JwtAuthenticationEntryPoint;
import net.alawn.bill.security.JwtAuthenticationTokenFilter;
import net.alawn.bill.util.AesEncryptUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
@@ -34,6 +36,8 @@ import java.util.Arrays;
* @Description:
* @Date: Create in 16:53 2019-05-17
*/
@Slf4j
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@@ -70,6 +74,7 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
/** 装载BCrypt密码编码器 */
@Bean
public PasswordEncoder passwordEncoder() {
log.info("passwordEncoder()");
return new BCryptPasswordEncoder();
}
@@ -154,12 +159,18 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
//对密码进行加密
@Override
public String encode(CharSequence charSequence) {
System.out.println(charSequence.toString());
log.info("encode password:" + charSequence.toString());
// String password = AesEncryptUtil.decrypt(charSequence.toString());
// return DigestUtils.md5DigestAsHex(password.getBytes());
return DigestUtils.md5DigestAsHex(charSequence.toString().getBytes());
}
//对密码进行判断匹配
@Override
public boolean matches(CharSequence charSequence, String s) {
log.info("matches passwordRaw :" + charSequence.toString());
log.info("matches passwordDb:" + charSequence.toString());
// String password = AesEncryptUtil.decrypt(charSequence.toString());
// String encode = DigestUtils.md5DigestAsHex(password.getBytes());
String encode = DigestUtils.md5DigestAsHex(charSequence.toString().getBytes());
boolean res = s.equals( encode );
return res;
@@ -49,7 +49,7 @@ public class BasicController {
@RequestMapping(value = "/posts",method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<Post> addPost(@RequestBody NewPost newPost, Principal principal) throws URISyntaxException {
public ResponseEntity<Post> addPost(@RequestBody NewPost newPost) {
AuthUser authUser = (AuthUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
long userId = authUser.getId();
@@ -90,7 +90,7 @@ public class BasicController {
@RequestMapping(value = "/merchants",method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<Merchant> addMerchant(@RequestBody NewMerchant newMerchant) throws URISyntaxException {
public ResponseEntity<Merchant> addMerchant(@RequestBody NewMerchant newMerchant) {
/** 登记 Post */
Merchant merchant = merchantRepo.save(newMerchant.build());
merchantRepo.flush();
@@ -99,7 +99,7 @@ public class BasicController {
@RequestMapping(value = "/merchants",method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<List<Merchant>> fetchMerchants() throws URISyntaxException {
public ResponseEntity<List<Merchant>> fetchMerchants() {
List<Merchant> merchants = merchantRepo.findAll();
return ResponseEntity.ok(merchants);
}
@@ -0,0 +1,41 @@
package net.alawn.bill.entity.po;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.*;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;
import javax.persistence.*;
@Data
@Builder
@Entity
@Table(name = "t_bill_premission")
@ToString(exclude = {"user"})
@NoArgsConstructor
@AllArgsConstructor
@JsonIgnoreProperties(value = { "hibernateLazyInitializer", "handler" },ignoreUnknown = true)
@DynamicUpdate
public class Premission extends EntityId{
@ManyToOne(fetch = FetchType.LAZY)
@NotFound(action = NotFoundAction.IGNORE)
// @JoinColumn(name = "userId", referencedColumnName = "id")
@JoinColumn(name = "userId", referencedColumnName = "id")
// @MapsId("username")
@MapsId("id")
private User user;
@Override
public boolean equals(Object o) {
return this == o || o instanceof Premission
&& id != null
&& id.equals(((Premission) o).id);
}
@Override
public int hashCode() {
return 31;
}
}
@@ -24,6 +24,7 @@ public enum RespMsg {
NO_DATA ( "200017", RespMsgConstants.NO_DATA ) ,
USER_ALREADY_EXIST ( "200018", RespMsgConstants.USER_ALREADY_EXIST ) ,
USER_NOT_EXIST_OR_PASSWORD_INCORRECT ( "200019", RespMsgConstants.USER_NOT_EXIST_OR_PASSWORD_INCORRECT ) ,
USERNAME_OR_PASSWORD_IS_EMPTY ( "200020", RespMsgConstants.USERNAME_OR_PASSWORD_IS_EMPTY ) ,
SUCCESS ( "000000", RespMsgConstants.SUCCESS ) ;
@@ -7,22 +7,23 @@ package net.alawn.bill.exception;
*/
public final class RespMsgConstants {
public final static String NO_STORAGE_FOUND = "没有发现存储" ;
public final static String NO_STORAGE_FOUND = "没有发现存储" ;
public final static String BLOB_DUPLICATE = "发现重复Blob" ;
public final static String BLOB_NOT_EXIST = "Blob对象不存在" ;
public final static String NO_BLOB_FOUND = "Blob对象不存在" ;
public final static String BLOB_NOT_EXIST = "Blob对象不存在" ;
public final static String NO_BLOB_FOUND = "Blob对象不存在" ;
public final static String BUCKET_DUPLICATE = "发现重复Bucket" ;
public final static String FILE_HANDLING = "文件处理异常" ;
public final static String FILE_NOT_EXIST = "文件不存在" ;
public final static String FILE_OCCUPIED = "文件/文件夹已被占用" ;
public final static String NO_ACCESS_PERMISSION = "没有该访问权限" ;
public final static String FILE_HANDLING = "文件处理异常" ;
public final static String FILE_NOT_EXIST = "文件不存在" ;
public final static String FILE_OCCUPIED = "文件/文件夹已被占用" ;
public final static String NO_ACCESS_PERMISSION = "没有该访问权限" ;
public final static String NO_BUCKET_FOUND = "没有找到Bucket" ;
public final static String NO_DEFAULT_BUCKET = "没有找到默认Bucket" ;
public final static String NO_DEFAULT_BUCKET = "没有找到默认Bucket" ;
public final static String NO_DEFAULT_STORAGE = "没有找到默认存储设备" ;
public final static String REQUEST_PARAMS = "请求参数有误" ;
public final static String INTERNAL_ERROR = "内部错误" ;
public final static String NO_DATA = "没有数据" ;
public final static String USER_ALREADY_EXIST = "用户已存在" ;
public final static String USER_NOT_EXIST_OR_PASSWORD_INCORRECT = "用户不存在或密码不正确" ;
public final static String USERNAME_OR_PASSWORD_IS_EMPTY = "用户名或密码不得为空" ;
public final static String SUCCESS = "业务成功" ;
}
@@ -11,6 +11,6 @@ import org.springframework.web.HttpRequestMethodNotSupportedException;
*/
public interface AuthService {
NewUser register(NewUser userDTO) throws HttpRequestMethodNotSupportedException, AuthenticationException;
String login(String username, String password);
String login(String username, String password) throws AuthenticationException;
String refresh(String oldToken);
}
@@ -1,5 +1,6 @@
package net.alawn.bill.service.impl;
import lombok.extern.slf4j.Slf4j;
import net.alawn.bill.entity.dto.NewUser;
import net.alawn.bill.entity.po.Authority;
import net.alawn.bill.entity.po.AuthorityId;
@@ -11,6 +12,7 @@ import net.alawn.bill.repository.UserRepo;
import net.alawn.bill.security.AuthUser;
import net.alawn.bill.security.JwtTokenUtil;
import net.alawn.bill.service.AuthService;
import net.alawn.bill.util.AesEncryptUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
@@ -23,6 +25,7 @@ import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
/**
@@ -31,6 +34,7 @@ import org.springframework.stereotype.Service;
* @Date: Create in 15:59 2019-05-20
*/
@Slf4j
@Service
//@AllArgsConstructor(onConstructor = @__(@Autowired))
public class AuthServiceImpl implements AuthService {
@@ -62,6 +66,8 @@ public class AuthServiceImpl implements AuthService {
@Override
public NewUser register(NewUser userDTO) throws AuthenticationException {
log.info("AuthServiceImpl.register start");
log.info("userDTO:" + userDTO);
final String username = userDTO.getUsername();
if(userRepo.findByUsername(username) != null) {
@@ -69,10 +75,14 @@ public class AuthServiceImpl implements AuthService {
}
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
final String rawPassword = userDTO.getPassword();
// final String rawPassword = userDTO.getPassword();
final String password = AesEncryptUtil.decrypt(userDTO.getPassword());
User user = User.builder()
.username(username)
.password(encoder.encode(rawPassword)).build();
.password(encoder.encode(password)).build();
// .password(userDTO.getPassword()).build();
User saved = userRepo.save(user);
Authority savedAuth = authorityRepo.save(
Authority.builder()
@@ -90,11 +100,26 @@ public class AuthServiceImpl implements AuthService {
@Override
public String login(String username, String password) {
// public String login(String username, String passwordAES) {
/** 为空检查*/
// if(StringUtils.isEmpty(username) || StringUtils.isEmpty(passwordAES)) {
// throw new CommonException(RespMsg.USER_NOT_EXIST_OR_PASSWORD_INCORRECT);
// }
// BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
password = AesEncryptUtil.decrypt(password);
UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(username, password);
final Authentication authentication = authenticationManager.authenticate(upToken);
SecurityContextHolder.getContext().setAuthentication(authentication);
final UserDetails userDetails = userDetailsService.loadUserByUsername(username);
// if(!encoder.matches(password,userDetails.getPassword())) {
// throw new CommonException(RespMsg.USER_NOT_EXIST_OR_PASSWORD_INCORRECT);
// }
final String token = jwtTokenUtil.generateToken(userDetails);
return token;
}
@@ -0,0 +1,128 @@
package net.alawn.bill.util;
import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
/**
* @Author: Alawn
* @Description:
* @Date: Create in 17:27 2019-06-11
*/
public class AesEncryptUtil {
private static String iv = "0123456789ABCDEF";//偏移量字符串必须是16位 当模式是CBC的时候必须设置偏移量
private static String Algorithm = "AES";
private static String AlgorithmProvider = "AES/CBC/PKCS5Padding"; //算法/模式/补码方式
public static byte[] generatorKey() throws NoSuchAlgorithmException {
KeyGenerator keyGenerator = KeyGenerator.getInstance(Algorithm);
keyGenerator.init(256);//默认128,获得无政策权限后可为192或256
SecretKey secretKey = keyGenerator.generateKey();
return secretKey.getEncoded();
}
public static IvParameterSpec getIv() throws UnsupportedEncodingException {
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes("utf-8"));
return ivParameterSpec;
}
/**
* 加密
* @param src
* @param key
* @return
* @throws NoSuchAlgorithmException
* @throws NoSuchPaddingException
* @throws InvalidKeyException
* @throws IllegalBlockSizeException
* @throws BadPaddingException
* @throws UnsupportedEncodingException
* @throws InvalidAlgorithmParameterException
*/
public static byte[] encrypt(String src, byte[] key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException, InvalidAlgorithmParameterException {
SecretKey secretKey = new SecretKeySpec(key, Algorithm);
IvParameterSpec ivParameterSpec = getIv();
Cipher cipher = Cipher.getInstance(AlgorithmProvider);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);
byte[] cipherBytes = cipher.doFinal(src.getBytes(Charset.forName("utf-8")));
return cipherBytes;
}
/**
* 解密
* @param src 原密码
* @param key 解密后的byte数组
* @return
* @throws Exception
*/
public static byte[] decrypt(String src, byte[] key) throws Exception {
SecretKey secretKey = new SecretKeySpec(key, Algorithm);
IvParameterSpec ivParameterSpec = getIv();
Cipher cipher = Cipher.getInstance(AlgorithmProvider);
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
byte[] hexBytes = hexStringToBytes(src);
byte[] plainBytes = cipher.doFinal(hexBytes);
return plainBytes;
}
/**
* 将byte转换为16进制字符串
* @param src
* @return
*/
public static String byteToHexString(byte[] src) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < src.length; i++) {
int v = src[i] & 0xff;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
sb.append("0");
}
sb.append(hv);
}
return sb.toString();
}
/**
* 将16进制字符串装换为byte数组
* @param hexString
* @return
*/
public static byte[] hexStringToBytes(String hexString) {
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] b = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
b[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return b;
}
private static byte charToByte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}
/**
* 直接传入psd然后解码进行验证使用
* @param psd 前台传过来的String 加密后的数组
* @return
*/
public static String decrypt(String psd) {
try {
byte key[] = "1234567890ABCDEF1234567890ABCDEf".getBytes("utf-8");
return new String(decrypt(psd, key));
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}