I can't figure out how to sign JWT with PKCS#8 key. The key is similar to this one:
-----BEGIN PRIVATE KEY-----
MIGTAgEAMBNGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgtbN7M/7webqa1i3k
3UiwERpWUIoRj6nebM7yRyFphVWgCgYIKoHihj0DAQehRANCAAQl6Z+2bWXLgxJC
J2It6UNYSuxios4A1A6/7/7hNs0y3Yus53q6RD1snvMU5yTBewrRALyDz/8MNADm
eN7dRD41
-----END PRIVATE KEY-----
The key is explained in this SO answer: https://stackoverflow.com/a/54981397/1051180
I need to use the com.nimbusds library. I think it should be doable but couldn't find the way. The closest I found is this SO answer: https://stackoverflow.com/a/57437626/1051180
I managed to sign it with the io.jsonwebtoken library:
String token = Jwts.builder().signWith(getPrivateKey(), SignatureAlgorithm.ES256).compact();
private static PrivateKey getPrivateKey() {
PrivateKey key = null;
try (var pemParser = new PEMParser(privateKeyReader)) {
var keyInfo = (PrivateKeyInfo) pemParser.readObject();
key = new JcaPEMKeyConverter().getPrivateKey(keyInfo);
}
return key;
}
Background: I obtained the key in an .p8 file. I use it to sign JWT that is used to authenticate against Apple server during Sign In with Apple.
Since I did not have an Apple-provided private key at hand I tried to generate one myself using this command:
Here's the code that can use such PEM file to sign a token:
Apparently, the PKCS#8 file provided by Apple does not have a public key included in it. Hence, the above method to create
ECDSASigner
fails with"Missing PEM-encoded public key to construct JWK"
exception. The code below loads the private key from such PEM file and creates an instance ofECDSASigner
which can be used to sign the token.