生成并读取base64私钥以从Java签名JWT令牌

时间:2019-06-02 04:51:53

标签: java jwt private-key

1-从命令行生成私钥:

  

openssl genrsa -aes256 -out private.key 2048

    java
  1. ,请阅读:

    String privateKey = IOUtils.toString(TestJwtSecurityUtil.class.getResourceAsStream("/private.key"));
    privateKey = privateKey.replace("-----BEGIN RSA PRIVATE KEY-----", "");
    privateKey = privateKey.replace("-----END RSA PRIVATE KEY-----", "");
    privateKey = privateKey.replaceAll("\\s+","");
    
    byte[] encodedKey = DatatypeConverter.parseBase64Binary( privateKey );
    
    
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encodedKey);
    
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PrivateKey pKey = kf.generatePrivate(keySpec); // fails
    

有例外:

  

线程“ main”中的异常java.security.spec.InvalidKeySpecException:   java.security.InvalidKeyException:IOException:   DerInputStream.getLength():lengthTag = 58,太大。

我试图转换为base64:

byte[] encodedKey = DatatypeConverter.parseBase64Binary( encodedString );
 PrivateKey pKey = kf.generatePrivate(keySpec); // fails

得到:

Exception in thread "main" java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format
    at java.base/sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:251)
问:如何通过?为了使私钥被读取,最后我可以使用JWT令牌:

final JwtBuilder builder = Jwts.builder().setId("id1")
                ....
                .signWith(signatureAlgorithm, pKey);

1 个答案:

答案 0 :(得分:0)

是的,它是重复的。但是由于我花了超过1个小时在SO网站上寻找它。基于此replybouncycastle的PEMParser。谢谢@ dave_thompson_085

  1. 要创建私钥-公钥:

    • openssl genrsa -out private.key 4096
    • openssl rsa -pubout -in private.key -out public.key
  2. 然后从java

-

         final PrivateKey pKey = getPrivateKey();

         final SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.RS256; // private key to sign / public to confrim a sign
     final JwtBuilder builder = Jwts.builder().setId("id1")
                    .setIssuedAt(now)
                    .setSubject(subject)
                    .setIssuer(issuer)
                    .setAudience("api")
                    .addClaims(Map.of(
                            "user_name", "test user",
                            "authorities", List.of("ROLE_USER"),
                            "scope", List.of("read", "write"),
                            "client_id", "test-client"
                            )
                    )                     .signWith(signatureAlgorithm, pKey);

String jwt = builder.compact();

其中:

private static PrivateKey getPrivateKey() throws Exception {

        val path = TestUtils.class.getResource("/").getPath();

        final PEMParser pemParser = new PEMParser(new FileReader(path + "/private.key"));
        final JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
        final PEMKeyPair object = (PEMKeyPair) pemParser.readObject();
        final KeyPair kp = converter.getKeyPair(object);
        final PrivateKey pKey = kp.getPrivate();

        return pKey;
    }

然后检查,粘贴:生成的jwthttps://jwt.io/(或任何其他工具)以查看/检查内容。

在其中放置public.key内容以检查签名。看到所有的都是绿色的。