首页 > 编程知识 正文

jwt 加密,jwt加密原理

时间:2023-05-06 14:23:49 阅读:208027 作者:4601

首先引入maven依赖

<dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt</artifactId><version>0.7.0</version></dependency><!--commons-codec --><dependency><groupId>commons-codec</groupId><artifactId>commons-codec</artifactId></dependency>

加解密核心代码快

public static String encryptPassword(String userName,String password, String idCardNum){JSONObject subject = new JSONObject(true);subject.put("userName", userName);subject.put("password", password);subject.put("idCardNum" , idCardNum);try {return JWTUtils.createJWT(userName,subject.toJSONString(),-1);} catch (Exception e) {throw new BusinessException(BusinessException.EncryptPasswordFail_CODE,"密码加密失败") ;}} public static String parsePassword(String password){Claims claims = JWTUtils.parseJWT(password);JSONObject subject = JSONObject.parseObject(claims.getSubject());return subject.getString("password");}

这里是引用工具类

public class JWTUtils { static String SECRETKEY = "KJHUhjjJYgYUllVbXhKDHXhkSyHjlNiVkYzWTBac1Yxkjhuad"; /** * 由字符串生成加密key * * @return */ public static SecretKey generalKey(String stringKey) { byte[] encodedKey = Base64.decodeBase64(stringKey); SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES"); return key; } /** * 创建jwt * @param id 唯一id,uuid即可 * @param subject json形式字符串或字符串,增加用户非敏感信息存储,如用户id或用户账号,与token解析后进行对比,防止乱用 * @param expirationDate 生成jwt的有效期,单位秒 * @return jwt token * @throws Exception */ public static String createJWT(String userName, String subject, long expirationDate) throws Exception { SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; long nowMillis = System.currentTimeMillis(); Date now = new Date(nowMillis); SecretKey key = generalKey(SECRETKEY); JwtBuilder builder = Jwts.builder().setIssuer("").setId(userName).setIssuedAt(now).setSubject(subject) .signWith(signatureAlgorithm, key); if (expirationDate >= 0) { long expMillis = nowMillis + expirationDate*1000; Date exp = new Date(expMillis); builder.setExpiration(exp); } return builder.compact(); } /** * 解密jwt,获取实体 * @param jwt */ public static Claims parseJWT(String jwt) throws ExpiredJwtException, UnsupportedJwtException, MalformedJwtException, SignatureException, IllegalArgumentException { SecretKey key = generalKey(SECRETKEY); Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(jwt).getBody(); return claims; }}

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。