Converting between a standard Java key and a JSON Web Key

JSON Web Keys (JWK) are represented by the base abstract JWK class, which has the following concrete instances:

  • RSAKey -- for representing the public key parameters of an RSA JWK; can also include the private key parameters.
  • ECKeys -- for representing the public key parameters of an EC JWK; can also include the private key parameters.
  • OctetKeyPair -- for representing the public key parameters of an octet key pair (used in EdDSA and ECDH with X25519/X448); can also include the private key parameters.
  • OctetSequenceKey -- for representing a shared or asymmetric key; such as an AES or HMAC secret.

The Java platform has its own standard classes for representing cryptographic keys, which are also often used by Java security libraries, for example libraries that deal with X.509 certificates.

Converting between a Java key object and a JWK object is straightforward. Just keep in mind that any metadata that may be present in a JWK, such as key identifier (kid), will be lost when converting to a Java key object.

Standard Java key representation JSON Web Key representation
java.security.Key com.nimbusds.jose.jwk.JWK
java.security.interfaces.RSAKey
java.security.interfaces.RSAPublicKey
java.security.interfaces.RSAPrivateKey
com.nimbusds.jose.jwk.RSAKey
java.security.interfaces.ECKey
java.security.interfaces.ECPublicKey
java.security.interfaces.ECPrivateKey
com.nimbusds.jose.jwk.ECKey
No Java support yet (see JEP 339) com.nimbusds.jose.jwk.OctetKeyPair
javax.crypto.SecretKey com.nimbusds.jose.jwk.OctetSequenceKey

Converting a java.security.interfaces.RSAPublicKey to an RSA JWK:

// RSA public key using the std Java interface
java.security.interfaces.RSAPublicKey publicKey = ...;

// Convert to JWK format
RSAKey jwk = new RSAKey.Builder(publicKey).build();

// Convert back to std Java interface
publicKey = jwk.toRSAPublicKey();

Including the private parts in the RSA JWK:

java.security.interfaces.RSAPublicKey publicKey = ...;
java.security.interfaces.RSAPrivateKey privateKey = ...;

// Convert to JWK format
RSAKey jwk = new RSAKey.Builder(publicKey)
    .privateKey(privateKey)
    .build();

// Convert back to std Java interfaces
publicKey = jwk.toRSAPublicKey();
privateKey = jwk.toRSAPrivateKey();

Converting a javax.crypto.SecretKey to a an octet sequence JWK:

// Secret key using the std Java interface
javax.crypto.SecretKey secretKey = ...;

// Convert to JWK format
OctetSequenceKey jwk = new OctetSequenceKey.Builder(secretKey).build();

// Convert back to std Java interface - with algorithm set to "NONE"
secretKey = jwk.toSecretKey();

// To set the algorithm to "AES"
secretKey = jwk.toSecretKey("AES");