JWT generation using CryptoKit

Is there a way to generate/sign a JWT using CryptoKit?

I know there are capable third-party libraries like IBM JWT and CupertinoJWT. However, I’d like to avoid using them as much as possible, especially if it can be achieved using CryptoKit.

CryptoKit is not aware of JWTs directly: it cannot provide the JWT encoding for you. However, the cryptographic parts required for JWTs are present. CryptoKit provides HMAC (suitable for HS256, HS384, HS512 algorithms) and ECDSA over the NIST curves (suitable for ES256, ES384, and ES512). Both of these can be combined with code that is aware of the JWT format to produce appropriately signed JWTs.

Specifically, I’m looking to sign a JWT using ES256 and a .p8 file. None of the tutorials and guides I’ve checked out generate an ES256 private key from a p8 file. Using P256.Signing.PrivateKey(rawRepresentation: /*Contents of p8 file as Data*/) throws CryptoKitError.incorrectKeySize

CryptoKit does not support loading keys from PKCS#8 files today. You’ll need to transform the PKCS#8 file into a format that CryptoKit does understand, or parse it to do that transformation yourself.

Is adding this support something that's on the roadmap for CryptoKit? In my feature spec the user should be able to add a p8 file and have it "just work", so I can't have any external transformation logic. It seems like for the time being, I'll have to go with IBM's SwiftJWT (no problem with that, but I would've preferred zero third party dependencies). Thank you very much for your clarifications!

1 Like