Poynt在JAVA中从私钥创建JWT

时间:2017-10-03 12:30:52

标签: java jwt private-key

我正在尝试从java中的私钥创建JWT。私钥位于文件中。

这是我的方法。

protected String prepareJWT() throws NoSuchAlgorithmException, InvalidKeySpecException, JOSEException {

    String poyntPrivateKey = this.getPoyntPrivateKey();
    byte[] privateBytes = poyntPrivateKey.getBytes();
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateBytes);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");

    PrivateKey privateKey = keyFactory.generatePrivate(keySpec);

    JWSSigner signer = new RSASSASigner((RSAPrivateKey) privateKey);
    ...

}

我在keyFactory.generatePrivate(keySpec);收到一条例外消息:

  

java.security.InvalidKeyException:无效的密钥格式

这里是getPoyntPrivateKey()

protected String getPoyntPrivateKey() {
    File file = new File("resources/poynt_api_private_key.txt");
    StringBuilder privateKeyBuilder = new StringBuilder();
    String privateKey = privateKeyBuilder.toString();
    try {
        FileReader fr = new FileReader(file);
        Scanner scanner = new Scanner(fr);
        while(scanner.hasNextLine()) {
            privateKeyBuilder.append(scanner.nextLine() + "\r");
        }
        scanner.close();
        privateKey = privateKeyBuilder.toString();
    } catch (Exception e) {
        privateKey = "Error";

    } finally {

    }

    return privateKey;

}

1 个答案:

答案 0 :(得分:2)

你去(使用com.nimbusds.jwt。*和org.bouncycastle.openssl。*):

    private static String getJWT() throws Exception{

    File f = new File(privateKeyFile);
    InputStreamReader isr = new InputStreamReader(new FileInputStream(f));

    PEMParser pemParser = new PEMParser(isr);
    Object object = pemParser.readObject();
    PEMKeyPair kp = (PEMKeyPair) object;
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
    RSAPrivateKey privateKey = (RSAPrivateKey) converter.getPrivateKey(kp.getPrivateKeyInfo());
    pemParser.close();


    // Create RSA-signer with the private key
    JWSSigner signer = new RSASSASigner(privateKey);

    // Prepare JWT with claims set
    JWTClaimsSet claimsSet = new JWTClaimsSet();
    claimsSet.setSubject(applicationId);
    claimsSet.setAudience(Arrays.asList(apiEndpoint));
    claimsSet.setIssuer(applicationId);
    claimsSet.setExpirationTime(new Date(new Date().getTime() + 360 * 1000));

    claimsSet.setIssueTime(new Date(new Date().getTime()));
    claimsSet.setJWTID(UUID.randomUUID().toString());

    SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.RS256), claimsSet);

    // Compute the RSA signature
    signedJWT.sign(signer);

    String s = signedJWT.serialize();
    return s;
}