diff --git a/presence/implementation/ldt.cc b/presence/implementation/ldt.cc index 68039b8a..8b38fc25 100644 --- a/presence/implementation/ldt.cc +++ b/presence/implementation/ldt.cc @@ -29,6 +29,9 @@ namespace nearby { namespace presence { namespace { +// NP LDT library says that 0 is returned when `NpLdtCreate()` fails. +constexpr NpLdtHandle kInvalidLdtHandle = static_cast(0); + template T FromStringView(absl::string_view data) { T result{ @@ -54,7 +57,7 @@ NpLdtAesCipherHandle AesCreateCipher(NpLdtAes128Key key) { int32_t AesCloseCipher(NpLdtAesCipherHandle handle) { AesContext* ctx = reinterpret_cast(handle); - free(ctx); + delete ctx; return 0; } @@ -70,6 +73,16 @@ void AesDecrypt(NpLdtAesCipherHandle handle, NpLdtAesBlock* block) { } // namespace +LdtEncryptor::LdtEncryptor(LdtEncryptor&& other) + : ldt_handle_(other.ldt_handle_) { + other.ldt_handle_ = kInvalidLdtHandle; +} +LdtEncryptor::~LdtEncryptor() { + if (ldt_handle_ != kInvalidLdtHandle) { + NpLdtClose(ldt_handle_); + } +} + absl::StatusOr LdtEncryptor::Create( absl::string_view key_seed, absl::string_view known_hmac) { NpLdtHandle handle = @@ -79,7 +92,7 @@ absl::StatusOr LdtEncryptor::Create( .decrypt = AesDecrypt}, FromStringView(key_seed), FromStringView(known_hmac)); - if (handle == nullptr) { + if (handle == kInvalidLdtHandle) { return absl::UnavailableError("Failed to create LDT encryptor"); } diff --git a/presence/implementation/ldt.h b/presence/implementation/ldt.h index 22ab45a3..f64519c0 100644 --- a/presence/implementation/ldt.h +++ b/presence/implementation/ldt.h @@ -29,19 +29,13 @@ namespace presence { class LdtEncryptor { public: LdtEncryptor(const LdtEncryptor&) = delete; - LdtEncryptor(LdtEncryptor&& other) : ldt_handle_(other.ldt_handle_) { - other.ldt_handle_ = nullptr; - } + LdtEncryptor(LdtEncryptor&& other); LdtEncryptor& operator=(const LdtEncryptor&) = delete; LdtEncryptor& operator=(LdtEncryptor&& other) { std::swap(ldt_handle_, other.ldt_handle_); return *this; } - ~LdtEncryptor() { - if (ldt_handle_ != nullptr) { - NpLdtClose(ldt_handle_); - } - } + ~LdtEncryptor(); // Creates an instance of `LdtEncryptor`. // `key_seed` is used to generate LDT encryption and decryption keys. diff --git a/presence/implementation/np_ldt.h b/presence/implementation/np_ldt.h index 070628d1..30c4c5a6 100644 --- a/presence/implementation/np_ldt.h +++ b/presence/implementation/np_ldt.h @@ -33,7 +33,7 @@ extern "C" { // decrypting advertisements from a known origin // Handle for accessing the rust ldt implementation apis -typedef void* NpLdtHandle; +typedef uint64_t NpLdtHandle; // Key material from the Nearby Presence credential from which keys will be // derived.