JWT(2)对称加密和非对称加密

JWT
placeholder image
admin 发布于:2023-01-29 22:22:28
阅读:loading

对称加密

package cn.chendd.jjwt;


/**
 * 对称加密简单示例
 *
 * @author chendd
 * @date 2022/11/6 9:02
 */
@RunWith(JUnit4.class)
public class JjwtShaTest {

    @Test
    public void test() {
        //生成随机key
        String jwtTokenRandomKey = Jwts.builder().setPayload("chendd").signWith(Keys.secretKeyFor(SignatureAlgorithm.HS256)).compact();
        System.out.println("随机密钥key生成Token:" + jwtTokenRandomKey);
        System.out.println("------------------------------------");

        //使用自定义密钥 签名 注意源码中限制了密钥存在的最小长度限制 【传递字节数组长度 * 8 必须大于定等于加密枚举实例中定义的最小大小】
        SecretKey key = Keys.hmacShaKeyFor("abcdefghijklmnopqrstuvwxyz123456".getBytes());

        //使用 payload 设置 content 数据
        {
            String jwtToken = Jwts.builder().setPayload("chendd").signWith(key).compact();
            System.out.println("固定密钥key和Payload生成Token:" + jwtToken);
            //解密
            Jwt parse = Jwts.parserBuilder().setSigningKey(key).build().parse(jwtToken);
            System.out.println("固定密钥key解析Token Header:" + parse.getHeader());
            System.out.println("固定密钥key解析Token Body:" + parse.getBody());
        }
        System.out.println("------------------------------------");

        //使用 chaim 设置 header 和 content 数据
        {
            String jwtToken = Jwts.builder()
                    //设置header
                    .setHeaderParam(JwsHeader.TYPE , JwsHeader.JWT_TYPE)
                    .setHeaderParam(JwsHeader.ALGORITHM , SignatureAlgorithm.HS256.name())
                    //设置 claim 标准参数(另有更多)
                    .setClaims(new DefaultClaims()
                            //jwt Id
                            .setId(UUID.randomUUID().toString())
                            //jwt 主题
                            .setSubject("chendd-examples-jjwt")
                    )
                    //设置 自定义 参数
                    .claim("userId" , "88911006")
                    .claim("userName" , "chendd")
                    //设置 密钥 签名
                    .signWith(key)
                    .compact();
            System.out.println("固定密钥key和Chaim生成Token:" + jwtToken);
            //解密
            Jws<Claims> claimsJws = Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(jwtToken);
            System.out.println("Header:" + claimsJws.getHeader());
            System.out.println("Body:" + claimsJws.getBody());
            System.out.println("Signature:" + claimsJws.getSignature());
        }
    }

}

注意:源码中限制了密钥存在的最小长度限制 【传递字节数组长度 * 8 必须大于定等于加密枚举实例中定义的最小大小】

image.png

非对称加密

package cn.chendd.jjwt;


/**
 * Jwt RSA 非对称加密
 *
 * @author chendd
 * @date 2022/11/6 10:20
 */
@RunWith(JUnit4.class)
public class JwtRsaTest {

    /**
     * 私钥
     */
    private Key privateKey;
    /**
     * 公钥
     */
    private Key publicKey;

    @Before
    public void initKey() throws NoSuchAlgorithmException {
        KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
        generator.initialize(2048);
        KeyPair keyPair = generator.genKeyPair();
        this.privateKey = keyPair.getPrivate();
        this.publicKey = keyPair.getPublic();
        System.out.println("私钥:" + Base64.getEncoder().encodeToString(this.privateKey.getEncoded()));
        System.out.println("公钥:" + Base64.getEncoder().encodeToString(this.publicKey.getEncoded()));
    }

    @Test
    public void test() {
        String jwtToken = Jwts.builder()
                //设置header
                .setHeaderParam(JwsHeader.TYPE , JwsHeader.JWT_TYPE)
                .setHeaderParam(JwsHeader.ALGORITHM , SignatureAlgorithm.HS256.name())
                //设置 claim 标准参数(另有更多)
                .setClaims(new DefaultClaims()
                        //jwt Id
                        .setId(UUID.randomUUID().toString())
                        //jwt 主题
                        .setSubject("chendd-examples-jjwt")
                )
                //设置 自定义 参数
                .claim("userId" , "88911006")
                .claim("userName" , "chendd")
                //设置 密钥 签名
                .signWith(this.privateKey)
                .compact();
        System.out.println("非对称加密key和Chaim生成Token:" + jwtToken);
        System.out.println("------------------------------------");
        //解密
        Jws<Claims> claimsJws = Jwts.parserBuilder().setSigningKey(this.publicKey).build().parseClaimsJws(jwtToken);
        System.out.println("Header:" + claimsJws.getHeader());
        System.out.println("Body:" + claimsJws.getBody());
        System.out.println("Signature:" + claimsJws.getSignature());
    }

}

image.png


 点赞


 发表评论

当前回复:作者

 评论列表


留言区