/** * @param keyFormat {@code AesCtrHmacAeadKeyFormat} proto * @return new {@code AesCtrHmacAeadKey} proto */ @Override public MessageLite newKey(MessageLite keyFormat) throws GeneralSecurityException { if (!(keyFormat instanceof AesCtrHmacAeadKeyFormat)) { throw new GeneralSecurityException("expected AesCtrHmacAeadKeyFormat proto"); } AesCtrHmacAeadKeyFormat format = (AesCtrHmacAeadKeyFormat) keyFormat; AesCtrKey aesCtrKey = (AesCtrKey) Registry.newKey( AesCtrKeyManager.TYPE_URL, format.getAesCtrKeyFormat()); HmacKey hmacKey = (HmacKey) Registry.newKey( MacConfig.HMAC_TYPE_URL, format.getHmacKeyFormat()); return AesCtrHmacAeadKey.newBuilder() .setAesCtrKey(aesCtrKey) .setHmacKey(hmacKey) .setVersion(VERSION) .build(); }
RegistryEciesAeadHkdfDemHelper(KeyTemplate demTemplate) throws GeneralSecurityException { demKeyTypeUrl = demTemplate.getTypeUrl(); if (demKeyTypeUrl.equals(AeadConfig.AES_GCM_TYPE_URL)) { try { AesGcmKeyFormat gcmKeyFormat = AesGcmKeyFormat.parseFrom(demTemplate.getValue()); this.aesGcmKey = (AesGcmKey) Registry.newKey(demTemplate); this.symmetricKeySize = gcmKeyFormat.getKeySize(); } catch (InvalidProtocolBufferException e) { throw new GeneralSecurityException( "invalid KeyFormat protobuf, expected AesGcmKeyFormat", e); } } else if (demKeyTypeUrl.equals(AeadConfig.AES_CTR_HMAC_AEAD_TYPE_URL)) { try { AesCtrHmacAeadKeyFormat aesCtrHmacAeadKeyFormat = AesCtrHmacAeadKeyFormat.parseFrom(demTemplate.getValue()); this.aesCtrHmacAeadKey = (AesCtrHmacAeadKey) Registry.newKey(demTemplate); this.aesCtrKeySize = aesCtrHmacAeadKeyFormat.getAesCtrKeyFormat().getKeySize(); int hmacKeySize = aesCtrHmacAeadKeyFormat.getHmacKeyFormat().getKeySize(); this.symmetricKeySize = aesCtrKeySize + hmacKeySize; } catch (InvalidProtocolBufferException e) { throw new GeneralSecurityException( "invalid KeyFormat protobuf, expected AesCtrHmacAeadKeyFormat", e); } } else { throw new GeneralSecurityException("unsupported AEAD DEM key type: " + demKeyTypeUrl); } }
@Override public byte[] encrypt(final byte[] plaintext, final byte[] associatedData) throws GeneralSecurityException { // Generate a new DEK. byte[] dek = Registry.newKey(dekTemplate).toByteArray(); // Wrap it with remote. byte[] encryptedDek = remote.encrypt(dek, EMPTY_AAD); // Use DEK to encrypt plaintext. Aead aead = Registry.getPrimitive(dekTemplate.getTypeUrl(), dek); byte[] payload = aead.encrypt(plaintext, associatedData); // Build ciphertext protobuf and return result. return buildCiphertext(encryptedDek, payload); }