@since 0.12.0
| 40 | * @since 0.12.0 |
| 41 | */ |
| 42 | abstract class AesAlgorithm extends CryptoAlgorithm implements KeyBuilderSupplier<SecretKey, SecretKeyBuilder>, KeyLengthSupplier { |
| 43 | |
| 44 | protected static final String KEY_ALG_NAME = "AES"; |
| 45 | protected static final int BLOCK_SIZE = 128; |
| 46 | protected static final int BLOCK_BYTE_SIZE = BLOCK_SIZE / Byte.SIZE; |
| 47 | protected static final int GCM_IV_SIZE = 96; // https://tools.ietf.org/html/rfc7518#section-5.3 |
| 48 | //protected static final int GCM_IV_BYTE_SIZE = GCM_IV_SIZE / Byte.SIZE; |
| 49 | protected static final String DECRYPT_NO_IV = "This algorithm implementation rejects decryption " + |
| 50 | "requests that do not include initialization vectors. AES ciphertext without an IV is weak and " + |
| 51 | "susceptible to attack."; |
| 52 | |
| 53 | protected final int keyBitLength; |
| 54 | protected final int ivBitLength; |
| 55 | protected final int tagBitLength; |
| 56 | protected final boolean gcm; |
| 57 | |
| 58 | /** |
| 59 | * Ensures {@code keyBitLength is a valid AES key length} |
| 60 | * @param keyBitLength the key length (in bits) to check |
| 61 | * @since 0.12.4 |
| 62 | */ |
| 63 | static void assertKeyBitLength(int keyBitLength) { |
| 64 | if (keyBitLength == 128 || keyBitLength == 192 || keyBitLength == 256) return; // valid |
| 65 | String msg = "Invalid AES key length: " + Bytes.bitsMsg(keyBitLength) + ". AES only supports " + |
| 66 | "128, 192, or 256 bit keys."; |
| 67 | throw new IllegalArgumentException(msg); |
| 68 | } |
| 69 | |
| 70 | static SecretKey keyFor(byte[] bytes) { |
| 71 | int bitlen = (int) Bytes.bitLength(bytes); |
| 72 | assertKeyBitLength(bitlen); |
| 73 | return new SecretKeySpec(bytes, KEY_ALG_NAME); |
| 74 | } |
| 75 | |
| 76 | AesAlgorithm(String id, final String jcaTransformation, int keyBitLength) { |
| 77 | super(id, jcaTransformation); |
| 78 | assertKeyBitLength(keyBitLength); |
| 79 | this.keyBitLength = keyBitLength; |
| 80 | this.gcm = jcaTransformation.startsWith("AES/GCM"); |
| 81 | this.ivBitLength = jcaTransformation.equals("AESWrap") ? 0 : (this.gcm ? GCM_IV_SIZE : BLOCK_SIZE); |
| 82 | // https://tools.ietf.org/html/rfc7518#section-5.2.3 through https://tools.ietf.org/html/rfc7518#section-5.3 : |
| 83 | this.tagBitLength = this.gcm ? BLOCK_SIZE : this.keyBitLength; |
| 84 | } |
| 85 | |
| 86 | @Override |
| 87 | public int getKeyBitLength() { |
| 88 | return this.keyBitLength; |
| 89 | } |
| 90 | |
| 91 | @Override |
| 92 | public SecretKeyBuilder key() { |
| 93 | return new DefaultSecretKeyBuilder(KEY_ALG_NAME, getKeyBitLength()); |
| 94 | } |
| 95 | |
| 96 | protected SecretKey assertKey(SecretKey key) { |
| 97 | Assert.notNull(key, "Request key cannot be null."); |
| 98 | validateLengthIfPossible(key); |
| 99 | return key; |
nothing calls this directly
no outgoing calls
no test coverage detected
searching dependent graphs…