Skip to content

Commit

Permalink
MbedAead::inplaceEncrypt()
Browse files Browse the repository at this point in the history
Summary: - implements ::inplaceEncrypt, however doesn't support inplace encryption for now

Reviewed By: kvtsoy

Differential Revision: D49326639

fbshipit-source-id: 7a3d12fb9a7cd9d396b563f47a5a72435afb598f
  • Loading branch information
hanidamlaj authored and facebook-github-bot committed Sep 22, 2023
1 parent 9fe6442 commit 58d44aa
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 5 deletions.
36 changes: 36 additions & 0 deletions quic/mbed/MbedAead.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,42 @@ MbedAead::MbedAead(const CipherType cipherType, TrafficKey&& key)
CHECK_EQ(mbedtls_cipher_setup(&cipher_ctx, cipher_info), 0);
}

// does not support inplace encryption just yet
std::unique_ptr<folly::IOBuf> MbedAead::inplaceEncrypt(
std::unique_ptr<folly::IOBuf>&& plaintext,
const folly::IOBuf* assocData,
uint64_t seqNum) const {
// support only unchained iobufs for now
CHECK(!plaintext->isChained());
CHECK(assocData == nullptr || !assocData->isChained());

setCipherKey(MBEDTLS_ENCRYPT);

// create IOBuf of size len(plaintext) + getCipherOverhead()
const size_t tag_len = getCipherOverhead();
auto ciphertext_buf = folly::IOBuf::create(plaintext->length() + tag_len);
auto iv = getIV(seqNum);
size_t write_size{0};

if (mbedtls_cipher_auth_encrypt_ext(
/*ctx=*/&cipher_ctx,
/*iv=*/iv.data(),
/*iv_len=*/std::min<size_t>(iv.size(), key_.iv->length()),
/*ad=*/assocData ? assocData->data() : nullptr,
/*ad_len=*/assocData ? assocData->length() : 0,
/*input=*/plaintext->data(),
/*ilen=*/plaintext->length(),
/*output=*/ciphertext_buf->writableData(),
/*output_len=*/ciphertext_buf->capacity(),
/*olen=*/&write_size,
/*tag_len=*/tag_len) != 0) {
throw std::runtime_error("mbedtls: failed to encrypt!");
}

ciphertext_buf->append(write_size);
return ciphertext_buf;
}

size_t MbedAead::getCipherOverhead() const {
return TAG_LENGTH;
}
Expand Down
9 changes: 4 additions & 5 deletions quic/mbed/MbedAead.h
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,11 @@ class MbedAead : public Aead {
return TrafficKey{.key = key_.key->clone(), .iv = key_.iv->clone()};
}

// does not support inplace encryption just yet
std::unique_ptr<folly::IOBuf> inplaceEncrypt(
std::unique_ptr<folly::IOBuf>&& /*plaintext*/,
const folly::IOBuf* /*associatedData*/,
uint64_t /*seqNum*/) const override {
return nullptr;
}
std::unique_ptr<folly::IOBuf>&& plaintext,
const folly::IOBuf* assocData,
uint64_t seqNum) const override;

folly::Optional<std::unique_ptr<folly::IOBuf>> tryDecrypt(
std::unique_ptr<folly::IOBuf>&& /*ciphertext*/,
Expand Down

0 comments on commit 58d44aa

Please sign in to comment.