JWT 使用公钥和私钥签名

问题描述 投票:0回答:1

我编写了这部分代码来创建 JWT。

public String createJWT() throws JoseException {

        RsaJsonWebKey rsaJsonWebKey = RsaJwkGenerator.generateJwk(2048);

        // Give the JWK a Key ID (kid), which is just the polite thing to do
        rsaJsonWebKey.setKeyId(keyId);

        // Create the Claims, which will be the content of the JWT
        JwtClaims claims = new JwtClaims();
        claims.setIssuer(issuer);
        claims.setExpirationTimeMinutesInTheFuture(60);
        claims.setJwtId(keyId);
        claims.setIssuedAtToNow();
        claims.setNotBeforeMinutesInThePast(2);
        claims.setSubject(subject);

        // We create a JsonWebSignature object.
        JsonWebSignature jws = new JsonWebSignature();

        // The payload of the JWS is JSON content of the JWT Claims
        jws.setPayload(claims.toJson());

        //The header of the JWS
        jws.setHeader("typ", "JWT");

        // The JWT is signed using the private key
        jws.setKey(rsaJsonWebKey.getPrivateKey());

        jws.setKeyIdHeaderValue(rsaJsonWebKey.getKeyId());

        // Set the signature algorithm on the JWT/JWS that will integrity protect the claims
        jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);

        // Sign the JWS and produce the compact serialization or the complete JWT/JWS
        // representation, which is a string consisting of three dot ('.') separated
        // base64url-encoded parts in the form Header.Payload.Signature
        String jwt = jws.getCompactSerialization();

        System.out.println("JWT: " + jwt);

        return jwt;
    }

但我不明白它检索的是哪个私钥?如何自定义此代码以发送存储在本地 JKS 中的我自己的公钥和私钥?

spring spring-boot jwt public-key jose4j
1个回答
0
投票

尝试使用以下命令加载您自己的密钥库:

    try (InputStream is = new FileInputStream(new File("path to keystore"))) {
        KeyStore keyStore = KeyStore.getInstance(ksType);
        keyStore.load(is, password);
        final Enumeration<String> aliases = keyStore.aliases();
        final String alias = aliases.nextElement(); // assuming only one entry
        final Entry entry = keyStore.getEntry(alias, password);
        if (entry instanceof PrivateKeyEntry) {
                PrivateKeyEntry pke = (PrivateKeyEntry) entry;
                PrivateKey privateKey = pke .getPrivateKey();

                // and here you may return the PrivateKey

        }

    } catch (Exception e) {
        ...
    }

免责声明:我没有测试代码,但它应该可以工作。

© www.soinside.com 2019 - 2024. All rights reserved.