当前位置: 首页 > 知识库问答 >
问题:

使用Java库创建带有RSA加密的JWT(Json Web令牌)

马淇
2023-03-14

我正在寻找使用“Nimbus JOSE JWT”库开发具有RSA加密的JWT应用程序。我正在寻找示例代码。

我想使用以下Maven依赖项:

<dependency>
    <groupId>com.nimbusds</groupId>
    <artifactId>nimbus-jose-jwt</artifactId>
    <version>3.10</version>
</dependency>

注意:请始终使用Maven Central repository的最新版本。

共有3个答案

蔺弘
2023-03-14
//This is a complete encryption and decryption module using 
//Algorithm: JWEAlgorithm.RSA_OAEP_256
//Encryption Method: A128CBC_HS256

public static String  encrypt(String text) throws Exception {
    // Set the plain text
    Payload payload = new Payload(text);
    // Create the header
    JWEHeader header = new JWEHeader(JWEAlgorithm.RSA_OAEP_256, EncryptionMethod.A128CBC_HS256);
    // Create the JWE object and encrypt it
    JWEObject jweObject = new JWEObject(header, payload);
    jweObject.encrypt(new RSAEncrypter(getPublicKey()));
    // Serialise to compact JOSE form...
    String jweString = jweObject.serialize();
    LOG.info("Generated Encrypted Key : {}", jweString);
    return jweString;
}

public static String decrypt(String text) throws Exception {
    // Parse into JWE object...
    JWEObject jweObject = JWEObject.parse(text);
    jweObject.decrypt(new RSADecrypter(getPrivateKey()));
    // Get the plain text
    Payload payload = jweObject.getPayload();
    System.out.println(payload.toString());
    return payload.toString();
}

private static RSAPublicKey getPublicKey() throws Exception {
    String filename = "/home/vaibhav/Setups/cert/pub.der";
    File f = new File(filename);
    FileInputStream fis = new FileInputStream(f);
    DataInputStream dis = new DataInputStream(fis);
    byte[] keyBytes = new byte[(int)f.length()];
    dis.readFully(keyBytes);
    dis.close();

    X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    return (RSAPublicKey) kf.generatePublic(spec);
}

private static RSAPrivateKey getPrivateKey() throws Exception {
    String filename = "/home/vaibhav/Setups/cert/private.pkcs8";
    File f = new File(filename);
    FileInputStream fis = new FileInputStream(f);
    DataInputStream dis = new DataInputStream(fis);
    byte[] keyBytes = new byte[(int)f.length()];
    dis.readFully(keyBytes);
    dis.close();

    PKCS8EncodedKeySpec spec1 = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    return (RSAPrivateKey) kf.generatePrivate(spec1);
}
聂鹏云
2023-03-14

我实现了使用“nimbus jose jwt”库的代码,请查找下面的代码

          JWTClaimsSet jwtClaims = new JWTClaimsSet();
            jwtClaims.setIssuer(ISSUER);
            jwtClaims.setSubject(SUBJECT);

            List<String> aud = new ArrayList<String>();
            aud.add("https://app-one.com");
            aud.add("https://app-two.com");

            jwtClaims.setAudience(aud);
            // Set expiration in 10 minutes
            jwtClaims.setExpirationTime(new Date(new Date().getTime() + 1000*60*10));
            jwtClaims.setNotBeforeTime(new Date());
            jwtClaims.setIssueTime(new Date());
            jwtClaims.setJWTID(UUID.randomUUID().toString());

            System.out.println("=========== JWT CLAMINS =============");
            System.out.println(jwtClaims.toJSONObject());


            // Request JWT encrypted with RSA-OAEP and 128-bit AES/GCM
            JWEHeader header = new JWEHeader(JWEAlgorithm.RSA_OAEP, EncryptionMethod.A128GCM);

            // Create the encrypted JWT object
            EncryptedJWT jwt = new EncryptedJWT(header, jwtClaims);


            // Create an encrypter with the specified public RSA key
            RSAEncrypter encrypter = new RSAEncrypter(publicKey);
            jwt.encrypt(encrypter);

            String jwtString = jwt.serialize();

            System.out.println(jwtString);


            // Parse back
            jwt = EncryptedJWT.parse(jwtString);

            // Create a decrypter with the specified private RSA key
            RSADecrypter decrypter = new RSADecrypter(privateKey);

            // Decrypt
            jwt.decrypt(decrypter);

            // Retrieve JWT claims
            System.out.println(jwt.getJWTClaimsSet().getIssuer());;
            System.out.println(jwt.getJWTClaimsSet().getSubject());
            System.out.println(jwt.getJWTClaimsSet().getAudience().size());
            System.out.println(jwt.getJWTClaimsSet().getExpirationTime());
            System.out.println(jwt.getJWTClaimsSet().getNotBeforeTime());
            System.out.println(jwt.getJWTClaimsSet().getIssueTime());
            System.out.println(jwt.getJWTClaimsSet().getJWTID());

This code has also use the public and private keys to create JWT token, also you will need those keys to extract claims and validate it.

Once you run this code, you should be able to see following jwtClaims:


     {
           "exp": 1429126207,
           "sub": "alice",
           "nbf": 1429125607,
           "aud": [
              "https://app-one.com",
              "https://app-two.com"
           ],
           "iss": "A FaceBook Cooperation",    
           "jti": "5c94d2db-e818-4746-b2f2-a4cd084d5a44",
           "iat": 1429125607
        }
和光启
2023-03-14

如果您使用的是“Nimbus Jose JWT”的最新版本4.23,那么API中会有一些小改动。

<dependency>
    <groupId>com.nimbusds</groupId>
    <artifactId>nimbus-jose-jwt</artifactId>
    <version>4.23</version>
</dependency>

以下代码仅供参考:

public class JwtJoseExample {
    public static void main(String[] args) {
        KeyPairGenerator keyPairGenerator;
        try {
            keyPairGenerator = KeyPairGenerator.getInstance("RSA");

            keyPairGenerator.initialize(1024);

            // generate the key pair
            KeyPair keyPair = keyPairGenerator.genKeyPair();

            // create KeyFactory and RSA Keys Specs
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            RSAPublicKeySpec publicKeySpec = keyFactory.getKeySpec(keyPair.getPublic(), RSAPublicKeySpec.class);
            RSAPrivateKeySpec privateKeySpec = keyFactory.getKeySpec(keyPair.getPrivate(), RSAPrivateKeySpec.class);

            // generate (and retrieve) RSA Keys from the KeyFactory using Keys Specs
            RSAPublicKey publicRsaKey = (RSAPublicKey) keyFactory.generatePublic(publicKeySpec);
            RSAPrivateKey privateRsaKey  = (RSAPrivateKey) keyFactory.generatePrivate(privateKeySpec);

            JWTClaimsSet.Builder claimsSet = new JWTClaimsSet.Builder();
            claimsSet.issuer("https://my-auth-server.com");
            claimsSet.subject("John Kerr");
            claimsSet.audience(getAudience());
            claimsSet.expirationTime(new Date(new Date().getTime() + 1000*60*10));
            claimsSet.notBeforeTime(new Date());
            claimsSet.jwtID(UUID.randomUUID().toString());

            System.out.println("--------------------------");
            System.out.println("Claim Set : \n"+claimsSet.build());

            // create the JWT header and specify:
            //  RSA-OAEP as the encryption algorithm
            //  128-bit AES/GCM as the encryption method
            JWEHeader header = new JWEHeader(JWEAlgorithm.RSA_OAEP, EncryptionMethod.A128GCM);

            // create the EncryptedJWT object
            EncryptedJWT jwt = new EncryptedJWT(header, claimsSet.build());

            // create an RSA encrypter with the specified public RSA key
            RSAEncrypter encrypter = new RSAEncrypter(publicRsaKey);

            // do the actual encryption
            jwt.encrypt(encrypter);

            // serialize to JWT compact form
            String jwtString = jwt.serialize();
            System.out.println("\nJwt Compact Form : "+jwtString);

            // in order to read back the data from the token using your private RSA key:
            // parse the JWT text string using EncryptedJWT object
            jwt = EncryptedJWT.parse(jwtString);

            // create a decrypter with the specified private RSA key
            RSADecrypter decrypter = new RSADecrypter(privateRsaKey);

            // do the decryption
            jwt.decrypt(decrypter);

            // print out the claims

            System.out.println("===========================================================");
            System.out.println("Issuer: [ " + jwt.getJWTClaimsSet().getIssuer() + "]");
            System.out.println("Subject: [" + jwt.getJWTClaimsSet().getSubject()+ "]");
            System.out.println("Audience size: [" + jwt.getJWTClaimsSet().getAudience().size()+ "]");
            System.out.println("Expiration Time: [" + jwt.getJWTClaimsSet().getExpirationTime()+ "]");
            System.out.println("Not Before Time: [" + jwt.getJWTClaimsSet().getNotBeforeTime()+ "]");
            System.out.println("Issue At: [" + jwt.getJWTClaimsSet().getIssueTime()+ "]");
            System.out.println("JWT ID: [" + jwt.getJWTClaimsSet().getJWTID()+ "]");
            System.out.println("===========================================================");

        } catch (NoSuchAlgorithmException | InvalidKeySpecException | JOSEException | ParseException e) {
            System.out.println(e.getMessage());
        }
    }

    private static List<String> getAudience(){
        List<String> audience = new ArrayList<>();
        audience.add("https://my-web-app.com");
        audience.add("https://your-web-app.com");
        return audience;
    }
}

索赔集:

{"sub":"John Kerr","aud":["https:\/\/my-web-app.com","https:\/\/your-web-app.com"],"nbf":1471116052,"iss":"https:\/\/my-auth-server.com","exp":1471116652,"jti":"8769fc6d-b69f-45e3-b1a5-52695c23675e"}

Jwt紧凑型:

eyJlbmMiOiJBMTI4R0NNIiwiYWxnIjoiUlNBLU9BRVAifQ.f2ZZyMaJi03RqunyWsLvIr7tNX1KvTRUcpN9qsBHvbXIouZCyepQMsbI1v88GHuLIV3f6SviCDyICp7kZCj_9q-yIi_dIuroADWQ-P_UnqNPRXQ1yEwbmrLUK80lBtKyc3Z6g_3Db_HLtD6QPEq-zUAh3wJ7uSPxhql2oc9otGc.Xbyrf4iWM0shNp4S.TCKoJGAEQ4rpJJk2qZP11awxTEWTg-r5VpppGgZNhiHCBhnGnyR2sb86O7ISc3j-i4OYp7Xl2vThzztD1ojy_IKPYQkg_iACuo6yjzdopQQT143vjYuFLfFhQFfjfCoO6iibTqK7vmqfF0bUWD6Nj-4MwjlW6dFV7mNQEN50dkiMrFMZkmiVKZRa50jOK1NcoWYiKSrCOQduJYibJfF6jSQARX9MsX5tib-3BXSsKtPLNrQ6mFfvDzzruBuO4gKWLE3PQPUfIQ.gXt5KcpxEbfYLP854GvcQw
===========================================================
Issuer: [ https://my-auth-server.com]
Subject: [John Kerr]
Audience size: [2]
Expiration Time: [Sun Aug 14 01:00:52 IST 2016]
Not Before Time: [Sun Aug 14 00:50:52 IST 2016]
Issue At: [null]
JWT ID: [8769fc6d-b69f-45e3-b1a5-52695c23675e]
===========================================================
 类似资料:
  • 我们正在使用JWT Nuget来创建和验证令牌。下面是我们用来创建令牌的代码 我的理解是,这不会加密令牌,因为我能够通过访问jwt.io解析令牌,并且能够读取内容。我想加密令牌,这样它就不应该被解析。我在JWT Nuget中找不到任何可以加密令牌的方法。 那么如何使用JWT nuget对令牌进行签名和加密呢? 编辑: 我知道JWT不需要任何加密,因为只有经过身份验证的用户才能读取令牌,这意味着,我

  • 我的项目正在基于构建身份验证服务。NET内核和nuget软件包。我们希望创建包含公钥证书(或证书链)的JWT令牌,该证书可用于验证JWT数字签名。这在商业身份提供者(SaaS)中是可能的,并且在JWT规范中通过称为“x5c”的头参数得到支持。但到目前为止,我无法使用。 我能够创建使用证书签名的JWT令牌。证书是使用openssl(下面包含的命令)自签名和创建的。我在C#中的测试代码如下所示: 生成

  • 我正在尝试为下面的行API创建一个访问令牌,这是我的私钥 { "alg":"RS256", "d":"TC4Ij...... wqSQIQ", "dp":"nJg12KiRo... nc02GdK-d8", "dq":"UzRtJ...... HA70", "e":"AQAB", "ext": true, "key_ops":[ "符号" ], "kty":"RSA", "n":"rj_fXZ..

  • 问题内容: 我试图来回编码一个简单的String“ test”。 但是,尽管加密工作得很好(ALGORITHM是“ RSA”),但是当尝试解密刚刚从加密“ test”中获得的字符串时,出现以下异常: javax.crypto.IllegalBlockSizeException:数据不得超过256个字节 我是否应该将加密的字节分成256个块才能解密? 问题答案: 您无法可靠地将随机字节转换为。结果将

  • 我正在做一个简单的程序来加密/解密使用RSA算法在Java。我创建一个密码对象如下: 我通过调用加密函数进行加密: 解密过程如下: 但是,当我将创建密码对象的代码编辑为://Create a Cipher object Cipher rsapier=Cipher时。getInstance(“RSA”); 问题出在哪里。在第一种情况下(当空格出现时),我指定了NoPadd?为什么空格出现在解密的消息

  • 在本章中,我们将重点介绍使用Python逐步实现RSA算法。 生成RSA密钥 生成RSA密钥涉及以下步骤 - 创建两个大素数,即p和q 。 这些数字的乘积称为n ,其中n= p*q 生成与(p-1)和(q-1).相对素数的随机数(q-1). 将数字称为e 。 计算e的模逆。 计算的倒数将被称为d 。 生成RSA密钥的算法 我们需要两个使用Python生成RSA密钥的主要算法 - Cryptomat