### Question:
HMACAlgorithm extends Algorithm { @Override public byte[] sign(byte[] headerBytes, byte[] payloadBytes) throws SignatureGenerationException { try { return crypto.createSignatureFor(getDescription(), secret, headerBytes, payloadBytes); } catch (NoSuchAlgorithmException | InvalidKeyException e) { throw new SignatureGenerationException(this, e); } } HMACAlgorithm(CryptoHelper crypto, String id, String algorithm, byte[] secretBytes);   HMACAlgorithm(String id, String algorithm, byte[] secretBytes);   HMACAlgorithm(String id, String algorithm, String secret); @Override void verify(DecodedJWT jwt); @Override byte[] sign(byte[] headerBytes, byte[] payloadBytes); @Override @Deprecated byte[] sign(byte[] contentBytes);  }### Answer:
@Test public void shouldThrowOnSignWhenSignatureAlgorithmDoesNotExists() throws Exception { exception.expect(SignatureGenerationException.class); exception.expectMessage("The Token's Signature couldn't be generated when signing using the Algorithm: some-algorithm"); exception.expectCause(isA(NoSuchAlgorithmException.class)); CryptoHelper crypto = mock(CryptoHelper.class); when(crypto.createSignatureFor(anyString(), any(byte[].class), any(byte[].class), any(byte[].class))) .thenThrow(NoSuchAlgorithmException.class); Algorithm algorithm = new HMACAlgorithm(crypto, "some-alg", "some-algorithm", "secret".getBytes(StandardCharsets.UTF_8)); algorithm.sign(new byte[0], new byte[0]); }
@Test public void shouldThrowOnSignWhenTheSecretIsInvalid() throws Exception { exception.expect(SignatureGenerationException.class); exception.expectMessage("The Token's Signature couldn't be generated when signing using the Algorithm: some-algorithm"); exception.expectCause(isA(InvalidKeyException.class)); CryptoHelper crypto = mock(CryptoHelper.class); when(crypto.createSignatureFor(anyString(), any(byte[].class), any(byte[].class), any(byte[].class))) .thenThrow(InvalidKeyException.class); Algorithm algorithm = new HMACAlgorithm(crypto, "some-alg", "some-algorithm", "secret".getBytes(StandardCharsets.UTF_8)); algorithm.sign(new byte[0], new byte[0]); }
@Test public void shouldBeEqualSignatureMethodResults() throws Exception { Algorithm algorithm = Algorithm.HMAC256("secret"); byte[] header = new byte[]{0x00, 0x01, 0x02}; byte[] payload = new byte[]{0x04, 0x05, 0x06}; ByteArrayOutputStream bout = new ByteArrayOutputStream(); bout.write(header); bout.write('.'); bout.write(payload); assertThat(algorithm.sign(bout.toByteArray()), is(algorithm.sign(header, payload))); }