Subclass representing an Hash-based MAC signing algorithm This class is thread-safe.
| 16 | * This class is thread-safe. |
| 17 | */ |
| 18 | class HMACAlgorithm extends Algorithm { |
| 19 | |
| 20 | private final CryptoHelper crypto; |
| 21 | private final byte[] secret; |
| 22 | |
| 23 | //Visible for testing |
| 24 | HMACAlgorithm(CryptoHelper crypto, String id, String algorithm, byte[] secretBytes) |
| 25 | throws IllegalArgumentException { |
| 26 | super(id, algorithm); |
| 27 | if (secretBytes == null) { |
| 28 | throw new IllegalArgumentException("The Secret cannot be null"); |
| 29 | } |
| 30 | this.secret = Arrays.copyOf(secretBytes, secretBytes.length); |
| 31 | this.crypto = crypto; |
| 32 | } |
| 33 | |
| 34 | HMACAlgorithm(String id, String algorithm, byte[] secretBytes) throws IllegalArgumentException { |
| 35 | this(new CryptoHelper(), id, algorithm, secretBytes); |
| 36 | } |
| 37 | |
| 38 | HMACAlgorithm(String id, String algorithm, String secret) throws IllegalArgumentException { |
| 39 | this(new CryptoHelper(), id, algorithm, getSecretBytes(secret)); |
| 40 | } |
| 41 | |
| 42 | //Visible for testing |
| 43 | static byte[] getSecretBytes(String secret) throws IllegalArgumentException { |
| 44 | if (secret == null) { |
| 45 | throw new IllegalArgumentException("The Secret cannot be null"); |
| 46 | } |
| 47 | return secret.getBytes(StandardCharsets.UTF_8); |
| 48 | } |
| 49 | |
| 50 | @Override |
| 51 | public void verify(DecodedJWT jwt) throws SignatureVerificationException { |
| 52 | try { |
| 53 | byte[] signatureBytes = Base64.getUrlDecoder().decode(jwt.getSignature()); |
| 54 | boolean valid = crypto.verifySignatureFor( |
| 55 | getDescription(), secret, jwt.getHeader(), jwt.getPayload(), signatureBytes); |
| 56 | if (!valid) { |
| 57 | throw new SignatureVerificationException(this); |
| 58 | } |
| 59 | } catch (IllegalStateException | InvalidKeyException | NoSuchAlgorithmException | IllegalArgumentException e) { |
| 60 | throw new SignatureVerificationException(this, e); |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | @Override |
| 65 | public byte[] sign(byte[] headerBytes, byte[] payloadBytes) throws SignatureGenerationException { |
| 66 | try { |
| 67 | return crypto.createSignatureFor(getDescription(), secret, headerBytes, payloadBytes); |
| 68 | } catch (NoSuchAlgorithmException | InvalidKeyException e) { |
| 69 | throw new SignatureGenerationException(this, e); |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | @Override |
| 74 | public byte[] sign(byte[] contentBytes) throws SignatureGenerationException { |
| 75 | try { |
nothing calls this directly
no outgoing calls
no test coverage detected
searching dependent graphs…