• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2024 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include <vector>
6 
7 #include "base/containers/span.h"
8 #include "crypto/crypto_export.h"
9 
10 #ifndef CRYPTO_AES_CBC_H_
11 #define CRYPTO_AES_CBC_H_
12 
13 // These functions implement one-shot block cipher encrypt/decrypt operations
14 // for AES-CBC. This interface is deliberately not abstracted over cipher type -
15 // new code should prefer the higher-level AEAD interface instead.
16 namespace crypto::aes_cbc {
17 
18 inline constexpr size_t kBlockSize = 16;
19 
20 // WARNING: In general you should not use these, and should prefer an AEAD mode
21 // which includes authentication.
22 //
23 // * The key must be 16 or 32 bytes long, for AES-128 or AES-256 respectively.
24 // * Decrypt() can fail if padding is incorrect, in which case it returns
25 //   nullopt.
26 //
27 // Design note:
28 // It may at first seem appealing to replace these functions with equivalents
29 // that take out parameters to avoid allocating a new value, but it is fiddly
30 // for the caller to compute the size of the output buffer correctly and for
31 // Encrypt() to ensure that junk data is not left in the buffer afterwards. For
32 // example, one could do:
33 //   size_t Encrypt(&[u8] key, &[u8] iv, &[u8] plaintext, &mut [u8] ciphertext)
34 // but then the caller could accidentally discard the size and use the full
35 // ciphertext buffer, even if not all of it was written. It's simpler to just
36 // always do a heap allocation here, and let callers that care about avoiding it
37 // use the BoringSSL APIs directly.
38 //
39 // WARNING: Do not call Decrypt() with an unauthenticated ciphertext, because
40 // you are very likely to accidentally create a padding oracle.
41 CRYPTO_EXPORT std::vector<uint8_t> Encrypt(
42     base::span<const uint8_t> key,
43     base::span<const uint8_t, kBlockSize> iv,
44     base::span<const uint8_t> plaintext);
45 CRYPTO_EXPORT std::optional<std::vector<uint8_t>> Decrypt(
46     base::span<const uint8_t> key,
47     base::span<const uint8_t, kBlockSize> iv,
48     base::span<const uint8_t> ciphertext);
49 
50 }  // namespace crypto::aes_cbc
51 
52 #endif  // CRYPTO_AES_CBC_H_
53