使用es256算法生成jwt

2023-12-13 10:04:29

1、使用hutool来做

1、先去jwt解密/加密 - bejson在线工具弄个公私钥

2、导入hutool maven

 <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.7.22</version>
        </dependency>
        <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-jdk15to18</artifactId>
            <version>1.68</version>
        </dependency>

3、代码

public class JwtUtil {
    

    public static void main(String[] args) {
        System.out.println("jwt:" + genEs256Jwt("123"));
    }


    static String es256PrimaryKey = "xxx";

    static String es256PublicKey = "xxx";

   
    // 生成jwt
    @SneakyThrows
    public static String genEs256Jwt(String username){
        byte[] privateKeyBytes = Base64.decode(es256PrimaryKey);
        KeyFactory keyFactory = KeyFactory.getInstance("EC");
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);

        JWTSigner signer = JWTSignerUtil.es256(privateKey);
        String token = JWT.create()
                .setPayload("username", username)
                .setPayload("iss", "xxx")
                // 签发时间
                .setPayload("timeStamp",new Date().getTime())
                .setKey(secret)
                .setSigner(signer)
                .sign();
        
    }

  

4、解密

@SneakyThrows
    public static String parseEs256Jwt(String token){
        Security.addProvider(new BouncyCastleProvider());
        KeyFactory keyFactory = KeyFactory.getInstance("ECDH", "BC");

        byte[] publicKeyBytes = Base64.decode(es256PublicKey);
        X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(publicKeyBytes);
        PublicKey publicKey = keyFactory.generatePublic(pubX509);


        JWTSigner signer = JWTSignerUtil.es256(publicKey);
        JWT jwt = JWT.of(token).setSigner(signer);
        return jwt.getPayload("username").toString();
    }

5、ps:hutool的在jwt解密/加密 - bejson在线工具上校验不过去,只能自己和自己校验玩

2、使用io.jsonwebtoken(推荐)

1、导入maven

<dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-impl</artifactId>
            <version>0.11.1</version>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-api</artifactId>
            <version>0.11.1</version>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-jackson</artifactId>
            <version>0.11.1</version>
        </dependency>

2、代码

@SneakyThrows
    public static String genEs256Jwt(String username){
      
        Security.addProvider(new BouncyCastleProvider());
        byte[] privateKeyBytes = Base64.decode(es256PrimaryKey);
//        KeyFactory keyFactory = KeyFactory.getInstance("EC");
        KeyFactory keyFactory = KeyFactory.getInstance("ECDH", "BC");
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);

        Claims claims = Jwts.claims();
        claims.put("username", username);
        String token = Jwts.builder()
                .setClaims(claims)
                .setIssuer("xxx")
                .signWith(privateKey,SignatureAlgorithm.ES256)
//                .signWith(privateKey, SignatureAlgorithm.ES256)
                .compact();
        return token;
    }

3、解密

    @SneakyThrows
    public static String parseEs256Jwt(String token){
        Security.addProvider(new BouncyCastleProvider());
        KeyFactory keyFactory = KeyFactory.getInstance("ECDH", "BC");
        byte[] publicKeyBytes = Base64.decode(es256PublicKey);
        X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(publicKeyBytes);
        PublicKey publicKey = keyFactory.generatePublic(pubX509);
        Jws<Claims> jwt = null;
        String username = null;
        try {
            jwt = Jwts.parserBuilder()
                    .setSigningKey(publicKey)
                    .build()
                    .parseClaimsJws(token);
            username = jwt.getBody().get("username").toString();
        } catch (ExpiredJwtException e) {
            e.printStackTrace();
        } catch (UnsupportedJwtException e) {
            e.printStackTrace();
        } catch (MalformedJwtException e) {
            e.printStackTrace();
        } catch (SignatureException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }

        return username;
    }

参考:JWT Token 使用 RS256 和 ES256 签名_jwt解码es256解密-CSDN博客

文章来源:https://blog.csdn.net/pengbin790000/article/details/134873015
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。