Skip to content
Connect2id

JWS HS256 with AWS CloudHSM

Starting with v9.34 the Nimbus JOSE+JWT library is able to use HMAC keys in PKCS#11 compliant stores, such as the AWS CloudHSM. All standard HMAC JWS algorithms are supported:

  • HS256 - HMAC with SHA-256, requires 256+ bit secret
  • HS384 - HMAC with SHA-384, requires 384+ bit secret
  • HS512 - HMAC with SHA-512, requires 512+ bit secret

Example loading of an AWS CloudHSM key store and obtaining a javax.crypto.SecretKey handle from the HSM to compute the HMAC for a JWS object:

// Load the AWS CloudHSM as a JCE provider
if (Security.getProvider(CloudHsmProvider.PROVIDER_NAME) == null) {
    Security.addProvider(new CloudHsmProvider())
}

Provider hsmProvider = Security.getProvider(CloudHsmProvider.PROVIDER_NAME);

KeyStore keyStore = KeyStore.getInstance(
    CloudHsmProvider.CLOUDHSM_KEYSTORE_TYPE,
    hsmProvider);
hsmProvider.load(null);

// Get the secret key handle
String keyID = "my-key-id";
SecretKey secretKey = (SecretKey)keyStore.getKey(keyID, "".toCharArray());

// Instantiate an HMAC signer with the secret key stored in the CloudHSM
JWSSigner signer = MACSigner(secretKey);
signer.getJCAContext().setProvider(hsmProvider);

// Create the JWS object
JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.HS256)
    .keyID(keyID)
    .build()

Payload payload = new Payload("HMAC protected string");
JWSObject jws = new JWSObject(header, payload);


// Compute the HMAC
jws.sign(signer);

// Serialise to compact JWS encoding
System.out.println(jws.serialize());