All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.github.yawenok.apns.http2.utils.JWTUtils Maven / Gradle / Ivy

package io.github.yawenok.apns.http2.utils;

import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import sun.security.ec.ECPrivateKeyImpl;

import javax.xml.bind.DatatypeConverter;
import java.io.*;
import java.security.InvalidKeyException;
import java.security.interfaces.ECPrivateKey;

public class JWTUtils {

    /**
     * Create a JWT for authentication tokens.
     *
     * @param privateKeyFile
     * @param keyId
     * @param teamId
     * @return
     * @throws IOException
     * @throws InvalidKeyException
     *
     * @see Communicating with APNs
     */
    public static String createJWT(File privateKeyFile, String keyId, String teamId) throws IOException, InvalidKeyException {
        // Read private key info
        StringBuffer p8KeyBuffer = new StringBuffer();
        BufferedReader bufferedReader = new BufferedReader(new FileReader(privateKeyFile));
        boolean haveReadHeader = false, haveReadFooter = false;
        for (String line; (line = bufferedReader.readLine()) != null; ) {
            if (!haveReadHeader) {
                if (line.contains("BEGIN PRIVATE KEY")) {
                    haveReadHeader = true;
                }
            } else {
                if (line.contains("END PRIVATE KEY")) {
                    haveReadFooter = true;
                    break;
                } else {
                    p8KeyBuffer.append(line);
                }
            }
        }
        if (!(haveReadHeader && haveReadFooter)) {
            throw new IOException("Could not find private key header/footer");
        }

        // APNs only support es256
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.ES256;
        ECPrivateKey privateKey = new ECPrivateKeyImpl(DatatypeConverter.parseBase64Binary(p8KeyBuffer.toString()));

        JSONObject header = new JSONObject();
        header.put("alg", signatureAlgorithm);
        header.put("kid", keyId);

        JSONObject claims = new JSONObject();
        claims.put("iss", teamId);
        claims.put("iat", System.currentTimeMillis() / 1000);

        JwtBuilder jwtBuilder = Jwts.builder().setHeader(header).setClaims(claims).signWith(signatureAlgorithm, privateKey);

        return jwtBuilder.compact();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy