同步数据
parent
6c8a97dec7
commit
073bfd45cd
@ -0,0 +1,34 @@
|
|||||||
|
package com.ruoyi.web.config.exception;
|
||||||
|
|
||||||
|
public class UnAuthorizedException extends RuntimeException {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Constructs a new runtime exception with the specified detail message.
|
||||||
|
* The cause is not initialized, and may subsequently be initialized by a
|
||||||
|
* call to {@link #initCause}.
|
||||||
|
*
|
||||||
|
* @param message the detail message. The detail message is saved for
|
||||||
|
* later retrieval by the {@link #getMessage()} method.
|
||||||
|
*/
|
||||||
|
public UnAuthorizedException(String message) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Constructs a new runtime exception with the specified detail message and
|
||||||
|
* cause. <p>Note that the detail message associated with
|
||||||
|
* {@code cause} is <i>not</i> automatically incorporated in
|
||||||
|
* this runtime exception's detail message.
|
||||||
|
*
|
||||||
|
* @param message the detail message (which is saved for later retrieval
|
||||||
|
* by the {@link #getMessage()} method).
|
||||||
|
* @param cause the cause (which is saved for later retrieval by the
|
||||||
|
* {@link #getCause()} method). (A {@code null} value is
|
||||||
|
* permitted, and indicates that the cause is nonexistent or
|
||||||
|
* unknown.)
|
||||||
|
* @since 1.4
|
||||||
|
*/
|
||||||
|
public UnAuthorizedException(String message, Throwable cause) {
|
||||||
|
super(message, cause);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,74 @@
|
|||||||
|
package com.ruoyi.web.config.security;
|
||||||
|
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.Setter;
|
||||||
|
import lombok.ToString;
|
||||||
|
import org.springframework.security.core.GrantedAuthority;
|
||||||
|
import org.springframework.security.core.userdetails.UserDetails;
|
||||||
|
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* jwt用户对象
|
||||||
|
*/
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@ToString
|
||||||
|
public class JwtUser implements UserDetails {
|
||||||
|
private String username;
|
||||||
|
private String password;
|
||||||
|
private String name;
|
||||||
|
private String userId;
|
||||||
|
private int roleId;
|
||||||
|
private Integer schoolId;
|
||||||
|
private int classId;
|
||||||
|
private String schoolName;
|
||||||
|
private String className;
|
||||||
|
private int majorId;
|
||||||
|
private String majorName;
|
||||||
|
private int collegeId;
|
||||||
|
private String collegeName;
|
||||||
|
private List<String> authorityCodes;
|
||||||
|
private String studentId;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Collection<? extends GrantedAuthority> getAuthorities() {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isAccountNonExpired() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isAccountNonLocked() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isCredentialsNonExpired() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isEnabled() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object o) {
|
||||||
|
if (this == o) return true;
|
||||||
|
if (!(o instanceof JwtUser)) return false;
|
||||||
|
JwtUser user = (JwtUser) o;
|
||||||
|
return username.equals(user.username);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
return Objects.hash(username);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,79 @@
|
|||||||
|
package com.ruoyi.web.config.security;
|
||||||
|
|
||||||
|
import io.swagger.annotations.ApiModel;
|
||||||
|
import io.swagger.annotations.ApiModelProperty;
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.Setter;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用户登录结果集
|
||||||
|
*
|
||||||
|
* @author 陈沅
|
||||||
|
*/
|
||||||
|
@ApiModel("用户登录结果集")
|
||||||
|
@Setter
|
||||||
|
@Getter
|
||||||
|
public class LoginResult {
|
||||||
|
@ApiModelProperty("用户ID")
|
||||||
|
private String userId;
|
||||||
|
@ApiModelProperty("姓名")
|
||||||
|
private String name;
|
||||||
|
@ApiModelProperty("访问令牌")
|
||||||
|
private String accessToken;
|
||||||
|
@ApiModelProperty("角色Id")
|
||||||
|
private int roleId;
|
||||||
|
@ApiModelProperty("用户所在班级id")
|
||||||
|
private int classId;
|
||||||
|
@ApiModelProperty("用户所在学校id")
|
||||||
|
private int schoolId;
|
||||||
|
@ApiModelProperty("用户所在学校名称")
|
||||||
|
private String schoolName;
|
||||||
|
@ApiModelProperty("用户权限")
|
||||||
|
private List<String> authorityCodes;
|
||||||
|
|
||||||
|
@ApiModelProperty("用户所在院系")
|
||||||
|
private int collegeId;
|
||||||
|
|
||||||
|
@ApiModelProperty("用户所在专业")
|
||||||
|
private int majorId;
|
||||||
|
@ApiModelProperty("用户名")
|
||||||
|
private String username;
|
||||||
|
|
||||||
|
|
||||||
|
// user.setUserId(dataObject.getStr("userId"));
|
||||||
|
// user.setName(dataObject.getStr("name"));
|
||||||
|
// user.setRoleId(dataObject.getInt("roleId"));
|
||||||
|
// user.setSchoolId(dataObject.getInt("schoolId"));
|
||||||
|
// user.setClassId(dataObject.getInt("classId"));
|
||||||
|
// user.setMajorId(dataObject.getInt("majorId"));
|
||||||
|
// user.setClassName(dataObject.getStr("className"));
|
||||||
|
// user.setMajorName(dataObject.getStr("majorName"));
|
||||||
|
// user.setSchoolName(dataObject.getStr("schoolName"));
|
||||||
|
// user.setCollegeId(dataObject.getInt("collegeId"));
|
||||||
|
// user.setCollegeName(dataObject.getStr("collegeName"));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建登录成功实体
|
||||||
|
*
|
||||||
|
* @param jwtUser 授权用户实体
|
||||||
|
* @param accessToken 令牌
|
||||||
|
* @return LoginResult
|
||||||
|
*/
|
||||||
|
public static LoginResult create(JwtUser jwtUser, String accessToken) {
|
||||||
|
LoginResult result = new LoginResult();
|
||||||
|
result.setUserId(jwtUser.getUserId());
|
||||||
|
result.setRoleId(jwtUser.getRoleId());
|
||||||
|
result.setName(jwtUser.getName());
|
||||||
|
result.setAccessToken(accessToken);
|
||||||
|
result.setClassId(jwtUser.getClassId());
|
||||||
|
result.setSchoolId(jwtUser.getSchoolId());
|
||||||
|
result.setAuthorityCodes(jwtUser.getAuthorityCodes());
|
||||||
|
result.setMajorId(jwtUser.getMajorId());
|
||||||
|
result.setCollegeId(jwtUser.getCollegeId());
|
||||||
|
result.setUsername(jwtUser.getUsername());
|
||||||
|
result.setSchoolName(jwtUser.getSchoolName());
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,217 @@
|
|||||||
|
package com.ruoyi.web.config.security;
|
||||||
|
|
||||||
|
|
||||||
|
import com.ruoyi.web.config.exception.UnAuthorizedException;
|
||||||
|
import io.jsonwebtoken.*;
|
||||||
|
import io.jsonwebtoken.security.Keys;
|
||||||
|
import io.jsonwebtoken.security.SignatureException;
|
||||||
|
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
|
||||||
|
import javax.crypto.spec.SecretKeySpec;
|
||||||
|
import javax.servlet.http.HttpServletRequest;
|
||||||
|
import java.security.Key;
|
||||||
|
import java.security.SecureRandom;
|
||||||
|
import java.util.Date;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class TokenProvider {
|
||||||
|
|
||||||
|
private final static String SECRET = "MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAghgsx+OLLThi7c+/HgCaRla8n+/QLHt++uscoK22dMeaVa3WJvRb5C5qtHGzj9V74pI96JpxdWWCN3Zr1QtanQIDAQABAkB2fWRUD1jVMBVS+rPctLnPNPMKTRdzXGv0SC5D3tRfGZqdcfsmZg8hzBVndHxngmwZS73d+hPjofcdefDDnXq1AiEAz/r1AMF7fweN70mbKgBJuTja37puJMsH2Szwrvb5jlcCIQCgIaLZ5d9J7OomL0NwH8ghba/xgBEpKzErfGbFnTfeKwIgc8ptczFFV1DWZb2eJIEqinOr79l0jwl2YiQSD+cyw1sCIHqxCvv1Wx5jPgy/zeYNE+Q5DMP3Ii7u/x+Yk436JiI9AiEAio84hFm44YTUuV7YCYsbyvnCn/vtcAaqZlczbeHlP1I=";
|
||||||
|
private final static long EXP_TIME = 1000 * 60 * 60 * 4;
|
||||||
|
|
||||||
|
private final static String SECRET_ZHIYUN = "zy_wh_mnjy_fp76ckwuczzmb67w0a8x0";
|
||||||
|
|
||||||
|
private final static String CURRENT_TO_ZHIYUN = "jVzvfoZU_eFN0CJcFARg0K6DlzTLa7oMWB7lV_y2s7bkv2Bem0281wEwlJp5afhsmM-Ynwvh3mAUTpwblGEz1A";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解析jwtToken
|
||||||
|
*
|
||||||
|
* @param jwtToken jwtToken
|
||||||
|
* @return jwt解析对象
|
||||||
|
*/
|
||||||
|
public static JwtUser getJWTUser(String jwtToken) {
|
||||||
|
jwtToken = jwtToken.replace("Bearer ", "");
|
||||||
|
try {
|
||||||
|
Claims claims = Jwts.parser()
|
||||||
|
.setSigningKey(
|
||||||
|
new SecretKeySpec(
|
||||||
|
SECRET.getBytes("UTF-8"),
|
||||||
|
SignatureAlgorithm.HS512.getJcaName()
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.parseClaimsJws(jwtToken)
|
||||||
|
.getBody();
|
||||||
|
|
||||||
|
JwtUser jwtUser = new JwtUser();
|
||||||
|
jwtUser.setName(claims.get("name") == null ? "" : claims.get("name").toString());
|
||||||
|
jwtUser.setUserId(claims.get("userId") == null ? "" : claims.get("userId").toString());
|
||||||
|
jwtUser.setRoleId(Integer.valueOf(claims.get("roleId") == null ? "0" : claims.get("roleId").toString()));
|
||||||
|
jwtUser.setClassId(Integer.valueOf(claims.get("classId") == null ? "0" : claims.get("classId").toString()));
|
||||||
|
jwtUser.setSchoolId(Integer.valueOf(claims.get("schoolId") == null ? "0" : claims.get("schoolId").toString()));
|
||||||
|
jwtUser.setUsername(claims.get("username") == null ? "" : claims.get("username").toString());
|
||||||
|
jwtUser.setAuthorityCodes((List<String>) claims.get("authorityCodes"));
|
||||||
|
return jwtUser;
|
||||||
|
} catch (ExpiredJwtException e1) {
|
||||||
|
throw new ExpiredJwtException(null, null, "token过期");
|
||||||
|
} catch (UnsupportedJwtException e2) {
|
||||||
|
throw new UnsupportedJwtException("不支持的token");
|
||||||
|
} catch (MalformedJwtException e3) {
|
||||||
|
throw new MalformedJwtException("token格式错误");
|
||||||
|
} catch (SignatureException e4) {
|
||||||
|
throw new SignatureException("签名失败");
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new UnAuthorizedException("无效token");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String createToken(JwtUser jwtUser) {
|
||||||
|
Key key = Keys.hmacShaKeyFor(SECRET.getBytes());
|
||||||
|
Date expiration = new Date(System.currentTimeMillis() + EXP_TIME);
|
||||||
|
return Jwts.builder()
|
||||||
|
.claim("userId", jwtUser.getUserId())
|
||||||
|
.claim("roleId", jwtUser.getRoleId())
|
||||||
|
.claim("name", jwtUser.getName())
|
||||||
|
.claim("classId", jwtUser.getClassId())
|
||||||
|
.claim("schoolId", jwtUser.getSchoolId())
|
||||||
|
.claim("username", jwtUser.getUsername())
|
||||||
|
.claim("authorityCodes", jwtUser.getAuthorityCodes())
|
||||||
|
.setIssuedAt(new Date(System.currentTimeMillis()))
|
||||||
|
.setExpiration(expiration)
|
||||||
|
.signWith(key, SignatureAlgorithm.HS512)
|
||||||
|
.compact();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String createZHIYUNToken(JwtUser jwtUser) {
|
||||||
|
Key key = Keys.hmacShaKeyFor(CURRENT_TO_ZHIYUN.getBytes());
|
||||||
|
Date expiration = new Date(System.currentTimeMillis() + EXP_TIME);
|
||||||
|
return Jwts.builder()
|
||||||
|
.claim("userId", jwtUser.getUserId())
|
||||||
|
.claim("roleId", jwtUser.getRoleId())
|
||||||
|
.claim("name", jwtUser.getName())
|
||||||
|
.claim("classId", jwtUser.getClassId())
|
||||||
|
.claim("schoolId", jwtUser.getSchoolId())
|
||||||
|
.claim("username", jwtUser.getUsername())
|
||||||
|
.claim("majorId", jwtUser.getMajorId())
|
||||||
|
.setIssuedAt(new Date(System.currentTimeMillis()))
|
||||||
|
.setExpiration(expiration)
|
||||||
|
.signWith(key, SignatureAlgorithm.HS512)
|
||||||
|
.compact();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
// JwtUser jwtUser = getJWTUserByZhiYun("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjb2xsZWdlIjoi5ryU56S65a2m6ZmiIiwiaWNpYnRTY2hvb2xJZCI6NCwibWQ1UHdkIjoiNDYtRjktNEMtOEQtRTEtNEYtQjMtNjYtODAtODUtMDctNjgtRkYtMUItN0YtMkEiLCJyb2xlaWQiOiI0Iiwic2V4Ijoi55S3IiwidXNlcklkIjoiMTgyOCIsInN0dWRlbnRJZCI6IjQ2MzciLCJwYXNzd29yZCI6IjEyM3F3ZSIsImNsYXNzSWQiOiIyMTYiLCJpY2lidENsYXNzSWQiOjIwOSwibWFqb3IiOiLkuqflk4HmvJTnpLrkuJPkuJoiLCJzY2hvb2wiOiLlpKnmi6nlpKflraYiLCJzY2hvb2xJZCI6IjIzMiIsIm5hbWUiOiJ0enMwMDgiLCJzdHVkZW50Tm8iOiJ0enMwMDgiLCJhcHBsaWNhdGlvbklkIjoiNDYiLCJjbGFzcyI6IuWkqeaLqea8lOekujbnj60iLCJ1c2VybmFtZSI6InR6czAwOCJ9.R7D6B9zDbtqb2lXnZMG3iAo-6zBwTfOi1BFbwMzqKfI");
|
||||||
|
// JwtUser jwtUser = getJWTUserByZhiYun("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjb2xsZWdlIjoi5ryU56S65a2m6ZmiIiwiaWNpYnRTY2hvb2xJZCI6NCwibWQ1UHdkIjoiNDYtRjktNEMtOEQtRTEtNEYtQjMtNjYtODAtODUtMDctNjgtRkYtMUItN0YtMkEiLCJyb2xlaWQiOiIzIiwic2V4Ijoi55S3IiwidXNlcklkIjoiMTg0NSIsInBhc3N3b3JkIjoiMTIzcXdlIiwidGVhY2hlcklkIjoiMzIzIiwibWFqb3IiOiLkuqflk4HmvJTnpLrkuJPkuJoiLCJzY2hvb2wiOiLlpKnmi6nlpKflraYiLCJzY2hvb2xJZCI6IjIzMiIsIm5hbWUiOiJ0enQwMDEiLCJhcHBsaWNhdGlvbklkIjoiMTE5IiwidXNlcm5hbWUiOiJ0enQwMDEifQ.rLKb20eOCN4KkyFQ5ZH8E56TsUVjBl2865nwnxYpsyk");
|
||||||
|
// JwtUser jwtUser = getJWTUserByZhiYun("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjb2xsZWdlIjoi5ryU56S65a2m6ZmiIiwiaWNpYnRTY2hvb2xJZCI6NCwibWQ1UHdkIjoiNDYtRjktNEMtOEQtRTEtNEYtQjMtNjYtODAtODUtMDctNjgtRkYtMUItN0YtMkEiLCJyb2xlaWQiOiI0Iiwic2V4Ijoi55S3IiwidXNlcklkIjoiNDg3Iiwic3R1ZGVudElkIjoiNDA0OCIsInBhc3N3b3JkIjoiMTIzcXdlIiwiY2xhc3NJZCI6IjIxMSIsImljaWJ0Q2xhc3NJZCI6MjA0LCJtYWpvciI6IuS6p-WTgea8lOekuuS4k-S4miIsInNjaG9vbCI6IuWkqeaLqeWkp-WtpiIsInNjaG9vbElkIjoiMjMyIiwibmFtZSI6InR6czAwMSIsInN0dWRlbnRObyI6InR6czAwMSIsImFwcGxpY2F0aW9uSWQiOiIxMTkiLCJjbGFzcyI6IuWkqeaLqea8lOekujHnj60iLCJ1c2VybmFtZSI6InR6czAwMSJ9.p6Uu15B1zNzuuCMOkDTkMksvjU6EOvGWprMWuJB0OII");
|
||||||
|
JwtUser jwtUser = getJWTUserByZhiYun("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjb2xsZWdlIjoi5ryU56S65a2m6ZmiIiwiaWNpYnRTY2hvb2xJZCI6NCwibWQ1UHdkIjoiNDYtRjktNEMtOEQtRTEtNEYtQjMtNjYtODAtODUtMDctNjgtRkYtMUItN0YtMkEiLCJyb2xlaWQiOiI0Iiwic2V4Ijoi55S3IiwidXNlcklkIjoiNDg3Iiwic3R1ZGVudElkIjoiNDA0OCIsInBhc3N3b3JkIjoiMTIzcXdlIiwiY2xhc3NJZCI6IjIxMSIsImljaWJ0Q2xhc3NJZCI6MjA0LCJtYWpvciI6IuS6p-WTgea8lOekuuS4k-S4miIsInNjaG9vbCI6IuWkqeaLqeWkp-WtpiIsInNjaG9vbElkIjoiMjMyIiwibmFtZSI6InR6czAwMSIsInN0dWRlbnRObyI6InR6czAwMSIsImFwcGxpY2F0aW9uSWQiOiI0NiIsImNsYXNzIjoi5aSp5oup5ryU56S6MeePrSIsInVzZXJuYW1lIjoidHpzMDAxIn0.DSjkZUCc7115znVNGZda6ZBXWfDGoL60MKpJZrwmBv8");
|
||||||
|
// JwtUser jwtUser = getJWTUserByZhiYun("");
|
||||||
|
|
||||||
|
System.out.println(jwtUser);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解析智云平台的token
|
||||||
|
*/
|
||||||
|
public static JwtUser getJWTUserByZhiYun(String token) {
|
||||||
|
// token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjb2xsZWdlIjoi57uP566h5a2m6ZmiIiwiaWNpYnRTY2hvb2xJZCI6MjI4LCJtZDVQd2QiOiI0Ni1GOS00Qy04RC1FMS00Ri1CMy02Ni04MC04NS0wNy02OC1GRi0xQi03Ri0yQSIsInJvbGVpZCI6IjQiLCJzZXgiOiLnlLciLCJ1c2VySWQiOiIzOTYxOCIsInN0dWRlbnRJZCI6IjMzNzczIiwicGFzc3dvcmQiOiIxMjNxd2UiLCJjbGFzc0lkIjoiMTg1MSIsImljaWJ0Q2xhc3NJZCI6MTIyMCwibWFqb3IiOiLph5Hono3kuJPkuJoiLCJzY2hvb2wiOiLlub_lt57ljY7llYbogYzkuJrlrabpmaIiLCJzY2hvb2xJZCI6IjEyMSIsIm5hbWUiOiIzMjE3NjA0MTMiLCJzdHVkZW50Tm8iOiIzMjE3NjA0MTMiLCJhcHBsaWNhdGlvbklkIjoiMTE5IiwiY2xhc3MiOiIyMemHkeiejeacjeWKoeS4jueuoeeQhjTnj60iLCJ1c2VybmFtZSI6IjMyMTc2MDQxMyJ9.0fgpRXUVl664QUFv96Cb7VJu-V8ea8mPB7RZ1UnWqq0";
|
||||||
|
// token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjb2xsZWdlIjoi57uP566h5a2m6ZmiIiwiaWNpYnRTY2hvb2xJZCI6MjI4LCJtZDVQd2QiOiI0Ni1GOS00Qy04RC1FMS00Ri1CMy02Ni04MC04NS0wNy02OC1GRi0xQi03Ri0yQSIsInJvbGVpZCI6IjQiLCJzZXgiOiLnlLciLCJ1c2VySWQiOiIzOTYxOCIsInN0dWRlbnRJZCI6IjMzNzczIiwicGFzc3dvcmQiOiIxMjNxd2UiLCJjbGFzc0lkIjoiMTg1MSIsImljaWJ0Q2xhc3NJZCI6MTIyMCwibWFqb3IiOiLph5Hono3kuJPkuJoiLCJzY2hvb2wiOiLlub_lt57ljY7llYbogYzkuJrlrabpmaIiLCJzY2hvb2xJZCI6IjEyMSIsIm5hbWUiOiIzMjE3NjA0MTMiLCJzdHVkZW50Tm8iOiIzMjE3NjA0MTMiLCJhcHBsaWNhdGlvbklkIjoiMTE5IiwiY2xhc3MiOiIyMemHkeiejeacjeWKoeS4jueuoeeQhjTnj60iLCJ1c2VybmFtZSI6IjMyMTc2MDQxMyJ9.0fgpRXUVl664QUFv96Cb7VJu-V8ea8mPB7RZ1UnWqq0";
|
||||||
|
try {
|
||||||
|
Claims claims = Jwts.parser()
|
||||||
|
.setSigningKey(Keys.hmacShaKeyFor(SECRET_ZHIYUN.getBytes()))
|
||||||
|
.parseClaimsJws(token)
|
||||||
|
.getBody();
|
||||||
|
|
||||||
|
JwtUser jwtUser = new JwtUser();
|
||||||
|
System.out.println(claims.toString());
|
||||||
|
jwtUser.setName(claims.get("name") == null ? null : claims.get("name").toString());
|
||||||
|
jwtUser.setUserId(claims.get("userId") == null ? null : claims.get("userId").toString());
|
||||||
|
jwtUser.setRoleId(Integer.valueOf(claims.get("roleid") == null ? "0" : claims.get("roleid").toString()));
|
||||||
|
jwtUser.setClassId(Integer.valueOf(claims.get("classId") == null ? "0" : claims.get("classId").toString()));
|
||||||
|
jwtUser.setSchoolId(Integer.valueOf(claims.get("schoolId") == null ? "0" : claims.get("schoolId").toString()));
|
||||||
|
jwtUser.setClassName(claims.get("class") == null ? null : claims.get("class").toString());
|
||||||
|
jwtUser.setSchoolName(claims.get("school") == null ? "0" : claims.get("school").toString());
|
||||||
|
jwtUser.setUsername(claims.get("username").toString());
|
||||||
|
jwtUser.setPassword(claims.get("password").toString());
|
||||||
|
if (org.apache.commons.lang3.StringUtils.isNotBlank((String) claims.get("studentNo"))) {
|
||||||
|
String studentNo = (String) claims.get("studentNo");
|
||||||
|
jwtUser.setStudentId(studentNo);
|
||||||
|
}
|
||||||
|
return jwtUser;
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new UnAuthorizedException("token解析失败");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
//生成智云平台32字节密钥
|
||||||
|
// public static void main(String[] args) {
|
||||||
|
//// String prefix = "zy_wh_mnjy_";
|
||||||
|
//// String generatedKey = generateKey(prefix);
|
||||||
|
//// System.out.println("Generated Key: " + generatedKey);
|
||||||
|
//// getJWTUserByZhiYun(null);
|
||||||
|
//
|
||||||
|
//
|
||||||
|
////生成一个新的长度为512字节的随机密钥供智云平台解析token
|
||||||
|
//// int keyLength = 512; // 根据您的要求进行调整
|
||||||
|
//// KeyGenerator keyGenerator;
|
||||||
|
//// try {
|
||||||
|
//// keyGenerator = KeyGenerator.getInstance("HmacSHA512");
|
||||||
|
//// keyGenerator.init(keyLength);
|
||||||
|
//// SecretKey secretKey = keyGenerator.generateKey();
|
||||||
|
//// byte[] secretBytes = secretKey.getEncoded();
|
||||||
|
//// String secret = Base64.getUrlEncoder().withoutPadding().encodeToString(secretBytes);
|
||||||
|
////
|
||||||
|
//// System.out.println("Generated Secret: " + secret);
|
||||||
|
//// } catch (NoSuchAlgorithmException e) {
|
||||||
|
//// e.printStackTrace();
|
||||||
|
//// }
|
||||||
|
//
|
||||||
|
// JwtUser user = new JwtUser();
|
||||||
|
// user.setUserId("486");
|
||||||
|
// user.setRoleId(3);
|
||||||
|
// user.setUsername("tzt006");
|
||||||
|
// user.setSchoolId(1);
|
||||||
|
// user.setSchoolName("天择大学");
|
||||||
|
// user.setCollegeId(1);
|
||||||
|
// user.setCollegeName("演示学院");
|
||||||
|
// user.setMajorId(1);
|
||||||
|
// user.setMajorName("产品演示专业");
|
||||||
|
// String token = createZHIYUNToken(user);
|
||||||
|
// System.out.println(token);
|
||||||
|
// }
|
||||||
|
|
||||||
|
public static String generateKey(String prefix) {
|
||||||
|
String characters = "0123456789abcdefghijklmnopqrstuvwxyz";
|
||||||
|
SecureRandom random = new SecureRandom();
|
||||||
|
|
||||||
|
StringBuilder keyBuilder = new StringBuilder(prefix);
|
||||||
|
while (keyBuilder.length() < 32) {
|
||||||
|
int randomIndex = random.nextInt(characters.length());
|
||||||
|
char randomChar = characters.charAt(randomIndex);
|
||||||
|
keyBuilder.append(randomChar);
|
||||||
|
}
|
||||||
|
return keyBuilder.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取当前用户信息
|
||||||
|
*
|
||||||
|
* @param request request
|
||||||
|
* @return JwtUser
|
||||||
|
*/
|
||||||
|
public static JwtUser getJWTUser(HttpServletRequest request) {
|
||||||
|
if (!(request.getUserPrincipal() instanceof UsernamePasswordAuthenticationToken)) {
|
||||||
|
throw new UnAuthorizedException("身份认证失败");
|
||||||
|
}
|
||||||
|
String jwtToken = request.getHeader("Authorization");
|
||||||
|
if (StringUtils.hasText(jwtToken)) {
|
||||||
|
return getJWTUser(jwtToken);
|
||||||
|
}
|
||||||
|
throw new UnAuthorizedException("身份认证失败");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,202 @@
|
|||||||
|
package com.ruoyi.web.util;
|
||||||
|
|
||||||
|
import cn.hutool.json.JSONObject;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.apache.commons.lang3.StringUtils;
|
||||||
|
import org.apache.http.HttpEntity;
|
||||||
|
import org.apache.http.HttpResponse;
|
||||||
|
import org.apache.http.HttpStatus;
|
||||||
|
import org.apache.http.client.HttpClient;
|
||||||
|
import org.apache.http.client.config.RequestConfig;
|
||||||
|
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||||
|
import org.apache.http.client.methods.HttpPost;
|
||||||
|
import org.apache.http.entity.ContentType;
|
||||||
|
import org.apache.http.entity.StringEntity;
|
||||||
|
import org.apache.http.entity.mime.MultipartEntityBuilder;
|
||||||
|
import org.apache.http.impl.client.CloseableHttpClient;
|
||||||
|
import org.apache.http.impl.client.HttpClients;
|
||||||
|
import org.apache.http.util.EntityUtils;
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
|
import java.io.BufferedReader;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStreamReader;
|
||||||
|
import java.net.HttpURLConnection;
|
||||||
|
import java.net.URL;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
@Slf4j
|
||||||
|
public class HttpUtils {
|
||||||
|
public static String CONTENT_TYPE_APPLICATION_X_WWW_FORM_URLENCODED = "application/x-www-form-urlencoded";
|
||||||
|
|
||||||
|
// 发送GET请求
|
||||||
|
public static String sendGet(String url) throws IOException {
|
||||||
|
HttpURLConnection connection = null;
|
||||||
|
BufferedReader reader = null;
|
||||||
|
StringBuilder response = new StringBuilder();
|
||||||
|
|
||||||
|
try {
|
||||||
|
URL requestUrl = new URL(url);
|
||||||
|
connection = (HttpURLConnection) requestUrl.openConnection();
|
||||||
|
connection.setRequestMethod("GET");
|
||||||
|
|
||||||
|
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
|
||||||
|
String line;
|
||||||
|
while ((line = reader.readLine()) != null) {
|
||||||
|
response.append(line);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
if (reader != null) {
|
||||||
|
reader.close();
|
||||||
|
}
|
||||||
|
if (connection != null) {
|
||||||
|
connection.disconnect();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return response.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 发送POST请求
|
||||||
|
public static JSONObject sendPost(String url, String paramStr) throws IOException {
|
||||||
|
try {
|
||||||
|
JSONObject ret = new JSONObject();
|
||||||
|
HttpPost method = new HttpPost(url);
|
||||||
|
StringEntity entity = new StringEntity(paramStr, "utf-8");
|
||||||
|
entity.setContentEncoding("UTF-8");
|
||||||
|
|
||||||
|
if (StringUtils.isEmpty(CONTENT_TYPE_APPLICATION_X_WWW_FORM_URLENCODED))
|
||||||
|
entity.setContentType("application/json");
|
||||||
|
else
|
||||||
|
entity.setContentType(CONTENT_TYPE_APPLICATION_X_WWW_FORM_URLENCODED);
|
||||||
|
|
||||||
|
|
||||||
|
method.setEntity(entity);
|
||||||
|
int timeout = 60000;
|
||||||
|
RequestConfig requestConfig = RequestConfig.custom()
|
||||||
|
.setSocketTimeout(timeout)
|
||||||
|
.setConnectTimeout(timeout)
|
||||||
|
.build();
|
||||||
|
method.setConfig(requestConfig);
|
||||||
|
HttpClient client = HttpClients.createDefault();
|
||||||
|
HttpResponse resp = client.execute(method);
|
||||||
|
int statusCode = resp.getStatusLine().getStatusCode();
|
||||||
|
if (statusCode != HttpStatus.SC_OK) {
|
||||||
|
log.info("接口请求失败,返回码:" + statusCode + ",失败原因:" + resp.getStatusLine().getReasonPhrase());
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
String respString = EntityUtils.toString(resp.getEntity(), "UTF-8");
|
||||||
|
ret.set("statusCode",statusCode);
|
||||||
|
if(StringUtils.isNotEmpty(respString)){
|
||||||
|
ret.set("respString",respString);
|
||||||
|
}
|
||||||
|
return ret;
|
||||||
|
}catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
log.info("接口请求失败,失败原因:"+e.getMessage());
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 发送POST请求
|
||||||
|
public static JSONObject sendPost(String url, String paramStr, String contentType, String token) throws IOException {
|
||||||
|
try {
|
||||||
|
JSONObject ret = new JSONObject();
|
||||||
|
HttpPost method = new HttpPost(url);
|
||||||
|
StringEntity entity = new StringEntity(paramStr, "utf-8");
|
||||||
|
entity.setContentEncoding("UTF-8");
|
||||||
|
|
||||||
|
if (StringUtils.isEmpty(contentType))
|
||||||
|
entity.setContentType("application/json");
|
||||||
|
else
|
||||||
|
entity.setContentType(contentType);
|
||||||
|
|
||||||
|
if (StringUtils.isNotEmpty(token)) {
|
||||||
|
method.setHeader("Authorization", "Bearer " + token);
|
||||||
|
}
|
||||||
|
|
||||||
|
method.setEntity(entity);
|
||||||
|
int timeout = 60000;
|
||||||
|
RequestConfig requestConfig = RequestConfig.custom()
|
||||||
|
.setSocketTimeout(timeout)
|
||||||
|
.setConnectTimeout(timeout)
|
||||||
|
.build();
|
||||||
|
method.setConfig(requestConfig);
|
||||||
|
HttpClient client = HttpClients.createDefault();
|
||||||
|
HttpResponse resp = client.execute(method);
|
||||||
|
int statusCode = resp.getStatusLine().getStatusCode();
|
||||||
|
if (statusCode != HttpStatus.SC_OK) {
|
||||||
|
log.info("接口请求失败,返回码:" + statusCode + ",失败原因:" + resp.getStatusLine().getReasonPhrase());
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
String respString = EntityUtils.toString(resp.getEntity(), "UTF-8");
|
||||||
|
ret.set("statusCode",statusCode);
|
||||||
|
if(StringUtils.isNotEmpty(respString)){
|
||||||
|
ret.set("respString",respString);
|
||||||
|
}
|
||||||
|
return ret;
|
||||||
|
}catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
log.info("接口请求失败,失败原因:"+e.getMessage());
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 发送GET请求 携带Token
|
||||||
|
public static String sendGet(String url, String token) throws IOException {
|
||||||
|
HttpURLConnection connection = null;
|
||||||
|
BufferedReader reader = null;
|
||||||
|
StringBuilder response = new StringBuilder();
|
||||||
|
|
||||||
|
try {
|
||||||
|
URL requestUrl = new URL(url);
|
||||||
|
connection = (HttpURLConnection) requestUrl.openConnection();
|
||||||
|
connection.setRequestMethod("GET");
|
||||||
|
|
||||||
|
// 添加token到请求头部
|
||||||
|
connection.setRequestProperty("Authorization", "Bearer " + token);
|
||||||
|
|
||||||
|
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
|
||||||
|
String line;
|
||||||
|
while ((line = reader.readLine()) != null) {
|
||||||
|
response.append(line);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
if (reader != null) {
|
||||||
|
reader.close();
|
||||||
|
}
|
||||||
|
if (connection != null) {
|
||||||
|
connection.disconnect();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return response.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// public static String sendPostRequestWithMultipartFile(String url, MultipartFile file,String token) throws IOException {
|
||||||
|
public static String sendPostRequestWithMultipartFile(String url, MultipartFile file) throws IOException {
|
||||||
|
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
|
||||||
|
HttpPost httpPost = new HttpPost(url);
|
||||||
|
httpPost.setHeader("Authorization", "Bearer " + null);
|
||||||
|
|
||||||
|
String originalFilename = file.getOriginalFilename();
|
||||||
|
// 将MultipartFile转换为HttpEntity
|
||||||
|
HttpEntity reqEntity = MultipartEntityBuilder.create().setCharset(StandardCharsets.UTF_8)
|
||||||
|
.addBinaryBody("file", file.getInputStream(), ContentType.DEFAULT_BINARY, file.getOriginalFilename())
|
||||||
|
.build();
|
||||||
|
|
||||||
|
httpPost.setEntity(reqEntity);
|
||||||
|
|
||||||
|
// 执行请求
|
||||||
|
CloseableHttpResponse response = httpClient.execute(httpPost);
|
||||||
|
try {
|
||||||
|
// 处理响应
|
||||||
|
HttpEntity responseEntity = response.getEntity();
|
||||||
|
String responseString = EntityUtils.toString(responseEntity);
|
||||||
|
return responseString;
|
||||||
|
} finally {
|
||||||
|
response.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,150 @@
|
|||||||
|
package com.ruoyi.web.util;
|
||||||
|
|
||||||
|
import org.apache.commons.codec.binary.Base64;
|
||||||
|
|
||||||
|
import javax.crypto.Cipher;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.security.*;
|
||||||
|
import java.security.interfaces.RSAPrivateKey;
|
||||||
|
import java.security.interfaces.RSAPublicKey;
|
||||||
|
import java.security.spec.PKCS8EncodedKeySpec;
|
||||||
|
import java.security.spec.X509EncodedKeySpec;
|
||||||
|
|
||||||
|
public class RsaUtil {
|
||||||
|
private static final String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCRehqqa1eLnTL3BSRq3zmB+Yw7nLAMAZ0G+FpoGP0eFLc0JVC2P2sfkCJJjH2cOmoLcUFjHfDcHzMNyl4wmNTMeXhpvK3v2ha1ufZnGmoMd9d4+1R/t/pZdxXXzkQMN2012X/KIojluEJmrIXLUM0zjOTABSMlTY6TPfSrmuXyGwIDAQAB";
|
||||||
|
private static final String privateKey = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAJF6GqprV4udMvcFJGrfOYH5jDucsAwBnQb4WmgY/R4UtzQlULY/ax+QIkmMfZw6agtxQWMd8NwfMw3KXjCY1Mx5eGm8re/aFrW59mcaagx313j7VH+3+ll3FdfORAw3bTXZf8oiiOW4QmashctQzTOM5MAFIyVNjpM99Kua5fIbAgMBAAECgYBtr3fNiHOQg6z6jLkBj18nvYTbKW+fDdRcfgKEPFsURCBBw+TQFI7rVFxVwgSvN2ffSrw3RErnXOq8ehl8YK8IfPWleMTXkuGB4QDptou3S7aJ4OlK+p5YOsjVEgnzJ3J7gPUYJRGAX59G+EbEnHKvoTQQjlQ4EaFqp77ba+SN+QJBAM1rre1TSSIuZd7biS4d0znVDRA3Zv/AnpmSaLZODU6p70DnPn3WCf5LNJGsS+Bt1xkq/EHzhpspjy/IfJrZOO8CQQC1S/vrpm8+WsXp8FAlvuQ+UOR1UlMs4WMokVMSOcPcgG2Iab8f1UcD9GptjBjORKiloQBpjG/+FXp2VJPd7yGVAkBvmRRAXoLYwwQs8m+wUhuyy3/xU2ftgaOoItYoVHb+SWvlgrt8eY+sSwcgLM57+rBkx+mLmtWB7i4P84deSKyZAkBYJ5FgnXY8MLFJtoOSRwb+0iC0d4pgKVwo7rkhBJubTYt1KE458V/tqVxS1it9qN8EYowrxpDyUIlSnn+kC9IdAkAH6TkJw2tb4N7rIvcZWjd74EBNQdP0FzvZWU2rE6SGqj87yWDKOKGKWu/hz84DCSkyltII4uB+YasJhsgsJnjb";
|
||||||
|
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
// System.out.println("\n");
|
||||||
|
// RsaKeyPair keyPair = generateKeyPair();
|
||||||
|
// System.out.println("公钥:" + keyPair.getPublicKey());
|
||||||
|
// System.out.println("私钥:" + keyPair.getPrivateKey());
|
||||||
|
//System.out.println("\n");
|
||||||
|
String text1 = encryptByPublicKey("123qwe");
|
||||||
|
// String text1 = encryptByPrivateKey("123");
|
||||||
|
System.out.println(text1);
|
||||||
|
//String text1 = "Bs+MJo8yrGxvwD/G5QGTihU6lh/PjaDKQNxBDs66GQrNXoX0ttzX0grYFxWh8MibHkHikkw8rLsoxXk6bQOzs0eHst/yzj823sTZRDBYdx0oYoEKeda7s7xjYheq4nBnHJn8HVkQbYtchddRRfKVcwyBrUQquhlnzmnfZQ98QiU=";
|
||||||
|
// String text1 = "CP7GpqY3Tw3DSazqwMHvlRys0/RARfjNL0fgw5IEXEHdZB2K+7G8Ro+wVAm9fiViMba3KcQidG5g244RrpD0HJc/g6PVW4kn81xx1WHjW0SgVUUrsjj4RgHUnUyY/lN0506Ng945svGrGd6pXb+XdtETv4ZKau5EHdR6L/TOR8I=";
|
||||||
|
// String text1 = "dWRzqk2DC/rm55B+m1Is4mwTnPoc3qoDIZ41Plie6s4vsJwDdHzoWhnIx1pfdFAwEZ3eQ6FV7tcfHJwHDFzNal15e1c2+EFThmWdqdgGNCXttH/c/fsmzaXda5kQRzQxqbhvF96KmJKtshzq23766iLV1Vm3KUsvB6c7bP5yKYc=";
|
||||||
|
//String text2 = decryptByPrivateKey(text1);
|
||||||
|
// String text2 = decryptByPrivateKey("R/t6KFVPbCgYSVlYJ4ULuFFwn29/RlLo/IBeXqdtwm0ulIcG0iTDqbCNcQZChE8iN/AL7S4MoGL/HWZArEqAz4BdDmYgLggykX/hhu1fue7tpefyVEnW5TF27rFBCxo1cH0kB1VP0FbwlWHDqG1GCnHOBZbS6j4yUTqu41WBmq4=");
|
||||||
|
// System.out.println(text2);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String encryptByPublicKey(String text) throws Exception {
|
||||||
|
X509EncodedKeySpec x509EncodedKeySpec2 = new X509EncodedKeySpec(Base64.decodeBase64(publicKey));
|
||||||
|
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
|
||||||
|
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec2);
|
||||||
|
Cipher cipher = Cipher.getInstance("RSA");
|
||||||
|
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
|
||||||
|
byte[] result = cipher.doFinal(text.getBytes("UTF-8"));
|
||||||
|
return Base64.encodeBase64String(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 私钥加密
|
||||||
|
*
|
||||||
|
* @param text 待加密的信息
|
||||||
|
* @return /
|
||||||
|
* @throws Exception /
|
||||||
|
*/
|
||||||
|
public static String encryptByPrivateKey(String text) throws Exception {
|
||||||
|
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
|
||||||
|
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
|
||||||
|
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
|
||||||
|
Cipher cipher = Cipher.getInstance("RSA");
|
||||||
|
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
|
||||||
|
byte[] result = cipher.doFinal(text.getBytes(StandardCharsets.UTF_8));
|
||||||
|
return Base64.encodeBase64String(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public static String decryptByPrivateKey(String text) throws Exception {
|
||||||
|
PKCS8EncodedKeySpec pkcs8EncodedKeySpec5 = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
|
||||||
|
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
|
||||||
|
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec5);
|
||||||
|
Cipher cipher = Cipher.getInstance("RSA");
|
||||||
|
cipher.init(Cipher.DECRYPT_MODE, privateKey);
|
||||||
|
byte[] result = cipher.doFinal(Base64.decodeBase64(text));
|
||||||
|
return new String(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String decryptByPublicKey(String text) throws Exception {
|
||||||
|
X509EncodedKeySpec x509EncodedKeySpec2 = new X509EncodedKeySpec(Base64.decodeBase64(publicKey));
|
||||||
|
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
|
||||||
|
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec2);
|
||||||
|
Cipher cipher = Cipher.getInstance("RSA");
|
||||||
|
cipher.init(Cipher.DECRYPT_MODE, publicKey);
|
||||||
|
byte[] result = cipher.doFinal(Base64.decodeBase64(text));
|
||||||
|
return new String(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 构建RSA密钥对
|
||||||
|
*
|
||||||
|
* @return /
|
||||||
|
* @throws NoSuchAlgorithmException /
|
||||||
|
*/
|
||||||
|
public static RsaKeyPair generateKeyPair() throws NoSuchAlgorithmException {
|
||||||
|
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
|
||||||
|
keyPairGenerator.initialize(1024);
|
||||||
|
KeyPair keyPair = keyPairGenerator.generateKeyPair();
|
||||||
|
RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
|
||||||
|
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
|
||||||
|
String publicKeyString = Base64.encodeBase64String(rsaPublicKey.getEncoded());
|
||||||
|
String privateKeyString = Base64.encodeBase64String(rsaPrivateKey.getEncoded());
|
||||||
|
return new RsaKeyPair(publicKeyString, privateKeyString);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
public static String calculateMD5(String input) {
|
||||||
|
try {
|
||||||
|
MessageDigest md = MessageDigest.getInstance("MD5");
|
||||||
|
byte[] hashBytes = md.digest(input.getBytes(StandardCharsets.UTF_8));
|
||||||
|
StringBuilder sb = new StringBuilder();
|
||||||
|
for (byte b : hashBytes) {
|
||||||
|
sb.append(String.format("%02X", b));
|
||||||
|
}
|
||||||
|
return sb.toString();
|
||||||
|
} catch (NoSuchAlgorithmException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String formatHash(String hash) {
|
||||||
|
StringBuilder formattedHash = new StringBuilder();
|
||||||
|
for (int i = 0; i < hash.length(); i += 2) {
|
||||||
|
formattedHash.append(hash.substring(i, i + 2));
|
||||||
|
if (i < hash.length() - 2) {
|
||||||
|
formattedHash.append("-");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return formattedHash.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* RSA密钥对对象
|
||||||
|
*/
|
||||||
|
public static class RsaKeyPair {
|
||||||
|
|
||||||
|
private final String publicKey;
|
||||||
|
private final String privateKey;
|
||||||
|
|
||||||
|
public RsaKeyPair(String publicKey, String privateKey) {
|
||||||
|
this.publicKey = publicKey;
|
||||||
|
this.privateKey = privateKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getPublicKey() {
|
||||||
|
return publicKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getPrivateKey() {
|
||||||
|
return privateKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,21 @@
|
|||||||
|
package com.ruoyi.biemo.business.domain;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
public class ZYUserInfo {
|
||||||
|
private String username;
|
||||||
|
private String password;
|
||||||
|
private String name;
|
||||||
|
private Integer userId;
|
||||||
|
private Integer roleId;
|
||||||
|
private Integer schoolId;
|
||||||
|
private String schoolName;
|
||||||
|
private Integer classId;
|
||||||
|
private String className;
|
||||||
|
private String phone;
|
||||||
|
private Long collegeId;
|
||||||
|
private String collegeName;
|
||||||
|
private Long majorId;
|
||||||
|
private String majorName;
|
||||||
|
}
|
Loading…
Reference in New Issue