github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/c-deps/libroach/ccl/ctr_stream.h (about) 1 // Copyright 2018 The Cockroach Authors. 2 // 3 // Licensed as a CockroachDB Enterprise file under the Cockroach Community 4 // License (the "License"); you may not use this file except in compliance with 5 // the License. You may obtain a copy of the License at 6 // 7 // https://github.com/cockroachdb/cockroach/blob/master/licenses/CCL.txt 8 9 #pragma once 10 11 #include <string> 12 #include "../rocksdbutils/env_encryption.h" 13 #include "key_manager.h" 14 15 namespace cockroach { 16 17 // CTRCipherStreamCreator creates a CTRCipherStream using a KeyManager. 18 // Takes ownership of the KeyManager. 19 class CTRCipherStreamCreator final : public rocksdb_utils::CipherStreamCreator { 20 public: 21 CTRCipherStreamCreator(KeyManager* key_mgr, enginepb::EnvType env_type) 22 : key_manager_(key_mgr), env_type_(env_type) {} 23 virtual ~CTRCipherStreamCreator(); 24 25 // Initialize 'settings' based on the current encryption algorithm and key 26 // and assign a new cipher stream to 'result'. 27 virtual rocksdb::Status InitSettingsAndCreateCipherStream( 28 std::string* settings, 29 std::unique_ptr<rocksdb_utils::BlockAccessCipherStream>* result) override; 30 31 // Create a cipher stream given encryption settings. 32 virtual rocksdb::Status CreateCipherStreamFromSettings( 33 const std::string& settings, 34 std::unique_ptr<rocksdb_utils::BlockAccessCipherStream>* result) override; 35 36 virtual enginepb::EnvType GetEnvType() override; 37 38 private: 39 std::unique_ptr<KeyManager> key_manager_; 40 enginepb::EnvType env_type_; 41 }; 42 43 class CTRCipherStream final : public rocksdb_utils::BlockAccessCipherStream { 44 public: 45 // Create a CTR cipher stream given: 46 // - a block cipher (takes ownership) 47 // - nonce of size 'cipher.BlockSize - sizeof(counter)' (eg: 16-4 = 12 bytes for AES) 48 // - counter 49 CTRCipherStream(std::shared_ptr<enginepbccl::SecretKey> key, const std::string& nonce, 50 uint32_t counter); 51 virtual ~CTRCipherStream(); 52 53 protected: 54 // Initialize a new cipher object. A Cipher is not thread-safe but can be used for any 55 // number of EncryptBlock/DecryptBlock calls. 56 virtual rocksdb::Status 57 InitCipher(std::unique_ptr<rocksdb_utils::BlockCipher>* cipher) const override; 58 59 // Encrypt a block of data at the given block index. 60 // Length of data is equal to BlockSize(); 61 virtual rocksdb::Status EncryptBlock(rocksdb_utils::BlockCipher* cipher, uint64_t blockIndex, 62 char* data, char* scratch) const override; 63 64 // Decrypt a block of data at the given block index. 65 // Length of data is equal to BlockSize(); 66 virtual rocksdb::Status DecryptBlock(rocksdb_utils::BlockCipher* cipher, uint64_t blockIndex, 67 char* data, char* scratch) const override; 68 69 private: 70 const std::shared_ptr<enginepbccl::SecretKey> key_; 71 const std::string nonce_; 72 const uint32_t counter_; 73 }; 74 75 } // namespace cockroach