1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef CRYPTO_ENCRYPTOR_H_
6 #define CRYPTO_ENCRYPTOR_H_
14 #include "base/strings/string_piece.h"
15 #include "build/build_config.h"
16 #include "crypto/crypto_export.h"
22 class CRYPTO_EXPORT Encryptor {
29 // This class implements a 128-bits counter to be used in AES-CTR encryption.
30 // Only 128-bits counter is supported in this class.
31 class CRYPTO_EXPORT Counter {
33 explicit Counter(base::StringPiece counter);
36 // Increment the counter value.
39 // Write the content of the counter to |buf|. |buf| should have enough
40 // space for |GetLengthInBytes()|.
41 void Write(void* buf);
43 // Return the length of this counter.
44 size_t GetLengthInBytes() const;
48 uint32_t components32[4];
49 uint64_t components64[2];
56 // Initializes the encryptor using |key| and |iv|. Returns false if either the
57 // key or the initialization vector cannot be used.
59 // If |mode| is CBC, |iv| must not be empty; if it is CTR, then |iv| must be
61 bool Init(const SymmetricKey* key, Mode mode, base::StringPiece iv);
63 // Encrypts |plaintext| into |ciphertext|. |plaintext| may only be empty if
65 bool Encrypt(base::StringPiece plaintext, std::string* ciphertext);
67 // Decrypts |ciphertext| into |plaintext|. |ciphertext| must not be empty.
69 // WARNING: In CBC mode, Decrypt() returns false if it detects the padding
70 // in the decrypted plaintext is wrong. Padding errors can result from
71 // tampered ciphertext or a wrong decryption key. But successful decryption
72 // does not imply the authenticity of the data. The caller of Decrypt()
73 // must either authenticate the ciphertext before decrypting it, or take
74 // care to not report decryption failure. Otherwise it could inadvertently
75 // be used as a padding oracle to attack the cryptosystem.
76 bool Decrypt(base::StringPiece ciphertext, std::string* plaintext);
78 // Sets the counter value when in CTR mode. Currently only 128-bits
79 // counter value is supported.
81 // Returns true only if update was successful.
82 bool SetCounter(base::StringPiece counter);
84 // TODO(albertb): Support streaming encryption.
87 const SymmetricKey* key_;
89 std::unique_ptr<Counter> counter_;
91 bool Crypt(bool do_encrypt, // Pass true to encrypt, false to decrypt.
92 base::StringPiece input,
94 bool CryptCTR(bool do_encrypt, base::StringPiece input, std::string* output);
100 #endif // CRYPTO_ENCRYPTOR_H_