|
| 1 | +package org.cryptomator.jose.alg; |
| 2 | + |
| 3 | +import org.cryptomator.jose.MacAlg; |
| 4 | + |
| 5 | +import javax.crypto.Mac; |
| 6 | +import javax.crypto.SecretKey; |
| 7 | +import java.security.InvalidKeyException; |
| 8 | +import java.security.NoSuchAlgorithmException; |
| 9 | +import java.util.Arrays; |
| 10 | + |
| 11 | +/// HMAC with SHA-2 for JWS (`HS256`, `HS384`, `HS512`), see [RFC 7518, Section 3.2](https://www.rfc-editor.org/rfc/rfc7518#section-3.2). |
| 12 | +public final class HmacAlg implements MacAlg { |
| 13 | + |
| 14 | + public enum Type { |
| 15 | + HS256("HS256", "HmacSHA256", 32), |
| 16 | + HS384("HS384", "HmacSHA384", 48), |
| 17 | + HS512("HS512", "HmacSHA512", 64), |
| 18 | + ; |
| 19 | + |
| 20 | + private final String jwaAlgName; |
| 21 | + private final String jcaAlgName; |
| 22 | + private final int minKeyLength; // RFC 7518 §3.2: a key of the same size as the hash output or larger MUST be used |
| 23 | + |
| 24 | + Type(String jwaAlgName, String jcaAlgName, int minKeyLength) { |
| 25 | + this.jwaAlgName = jwaAlgName; |
| 26 | + this.jcaAlgName = jcaAlgName; |
| 27 | + this.minKeyLength = minKeyLength; |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + private final Type type; |
| 32 | + private final SecretKey key; |
| 33 | + |
| 34 | + /// @param type The HMAC variant |
| 35 | + /// @param key The HMAC key, which remains owned (and eventually destroyed) by the caller |
| 36 | + /// @throws IllegalArgumentException if the key is shorter than the hash output |
| 37 | + public HmacAlg(Type type, SecretKey key) { |
| 38 | + var encoded = key.getEncoded(); |
| 39 | + if (encoded == null) { |
| 40 | + throw new IllegalArgumentException("Key must be extractable"); // e.g. hardware-backed keys are not supported |
| 41 | + } |
| 42 | + try { |
| 43 | + if (encoded.length < type.minKeyLength) { |
| 44 | + throw new IllegalArgumentException(type.jwaAlgName + " requires a key of at least " + type.minKeyLength * Byte.SIZE + " bits, but got " + encoded.length * Byte.SIZE); |
| 45 | + } |
| 46 | + } finally { |
| 47 | + Arrays.fill(encoded, (byte) 0x00); |
| 48 | + } |
| 49 | + this.type = type; |
| 50 | + this.key = key; |
| 51 | + } |
| 52 | + |
| 53 | + @Override |
| 54 | + public String name() { |
| 55 | + return type.jwaAlgName; |
| 56 | + } |
| 57 | + |
| 58 | + @Override |
| 59 | + public byte[] sign(byte[] signingInput) { |
| 60 | + try { |
| 61 | + var mac = Mac.getInstance(type.jcaAlgName); |
| 62 | + mac.init(key); |
| 63 | + return mac.doFinal(signingInput); |
| 64 | + } catch (NoSuchAlgorithmException e) { |
| 65 | + throw new UnsupportedOperationException("JVM does not support " + type.jcaAlgName, e); |
| 66 | + } catch (InvalidKeyException e) { |
| 67 | + throw new IllegalStateException("Unsuitable key for " + type.jcaAlgName, e); |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | +} |
0 commit comments