【问题标题】:JWT signing with public and private key使用公钥和私钥进行 JWT 签名
【发布时间】:2022-08-06 04:24:59
【问题描述】:

我已经编写了这部分代码来创建 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 中的我自己的公钥和私钥?

提前致谢!!

  • 它正在检索哪个私钥?- 你是什么意思?似乎代码在第一行生成了密钥(这不太实用,因为您当然不希望每个 JWT 都有一个新密钥)
  • 好的很酷,所以这条线给了我私钥 -> RsaJsonWebKey rsaJsonWebKey = RsaJwkGenerator.generateJwk(2048);在那种情况下,什么会方便?如何从 jks 添加我自己的私钥

标签: spring spring-boot jwt public-key jose4j


【解决方案1】:

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

    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) {
        ...
    }

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

【讨论】:

    猜你喜欢
    • 2020-08-19
    • 2017-01-27
    • 1970-01-01
    • 2020-06-17
    • 2018-04-10
    • 2016-12-01
    • 2015-06-01
    • 2018-05-22
    • 1970-01-01
    相关资源
    最近更新 更多