RegistryEciesAeadHkdfDemHelper implements EciesAeadHkdfDemHelper { @Override public Aead getAead(final byte[] symmetricKeyValue) throws GeneralSecurityException { if (symmetricKeyValue.length != getSymmetricKeySizeInBytes()) { throw new GeneralSecurityException("Symmetric key has incorrect length"); } if (demKeyTypeUrl.equals(AeadConfig.AES_GCM_TYPE_URL)) { AesGcmKey aeadKey = AesGcmKey.newBuilder() .mergeFrom(aesGcmKey) .setKeyValue(ByteString.copyFrom(symmetricKeyValue, 0, symmetricKeySize)) .build(); return Registry.getPrimitive(demKeyTypeUrl, aeadKey, Aead.class); } else if (demKeyTypeUrl.equals(AeadConfig.AES_CTR_HMAC_AEAD_TYPE_URL)) { byte[] aesCtrKeyValue = Arrays.copyOfRange(symmetricKeyValue, 0, aesCtrKeySize); byte[] hmacKeyValue = Arrays.copyOfRange(symmetricKeyValue, aesCtrKeySize, symmetricKeySize); AesCtrKey aesCtrKey = AesCtrKey.newBuilder() .mergeFrom(aesCtrHmacAeadKey.getAesCtrKey()) .setKeyValue(ByteString.copyFrom(aesCtrKeyValue)) .build(); HmacKey hmacKey = HmacKey.newBuilder() .mergeFrom(aesCtrHmacAeadKey.getHmacKey()) .setKeyValue(ByteString.copyFrom(hmacKeyValue)) .build(); AesCtrHmacAeadKey aeadKey = AesCtrHmacAeadKey.newBuilder() .setVersion(aesCtrHmacAeadKey.getVersion()) .setAesCtrKey(aesCtrKey) .setHmacKey(hmacKey) .build(); return Registry.getPrimitive(demKeyTypeUrl, aeadKey, Aead.class); } else { throw new GeneralSecurityException("unknown DEM key type"); } } RegistryEciesAeadHkdfDemHelper(KeyTemplate demTemplate); @Override int getSymmetricKeySizeInBytes(); @Override Aead getAead(final byte[] symmetricKeyValue);  }
@Test public void testGetAead() throws Exception { byte[] plaintext = "some plaintext string".getBytes(UTF_8); byte[] associatedData = "some associated data".getBytes(UTF_8); int count = 0; for (KeyTemplate template : keyTemplates) { RegistryEciesAeadHkdfDemHelper helper = new RegistryEciesAeadHkdfDemHelper(template); byte[] symmetricKey = Random.randBytes(helper.getSymmetricKeySizeInBytes()); Aead aead = helper.getAead(symmetricKey); byte[] ciphertext = aead.encrypt(plaintext, associatedData); byte[] decrypted = aead.decrypt(ciphertext, associatedData); assertArrayEquals(plaintext, decrypted); symmetricKey = Random.randBytes(helper.getSymmetricKeySizeInBytes() - 1); try { aead = helper.getAead(symmetricKey); fail("Symmetric key too short, should have thrown exception:\n" + template.toString()); } catch (GeneralSecurityException e) { assertExceptionContains(e, "incorrect length"); } symmetricKey = Random.randBytes(helper.getSymmetricKeySizeInBytes() + 1); try { aead = helper.getAead(symmetricKey); fail("Symmetric key too long, should have thrown exception:\n" + template.toString()); } catch (GeneralSecurityException e) { assertExceptionContains(e, "incorrect length"); } count++; } assertEquals(keyTemplates.length, count); }