blob: f30ff9dd6930c273c93e7f62368da4cc02a49661 [file] [log] [blame]
Ellye430c2c72024-11-27 16:17:211// 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#ifndef CRYPTO_AES_CTR_H_
6#define CRYPTO_AES_CTR_H_
7
8#include <vector>
9
10#include "base/containers/span.h"
11#include "crypto/crypto_export.h"
12
13namespace crypto::aes_ctr {
14
15inline constexpr size_t kCounterSize = 16;
16
17// Single-shot encryption and decryption operations. These require that the
18// output span be the same size as the input span, cannot fail, and do not
19// handle incrementing the counter for you. These can either operate in-place
20// (meaning in == out) or on entirely disjoint in and out buffers, but *not* on
21// overlapping-but-unequal in and out buffers.
22//
23// Crypto note: It is VERY UNSAFE to encrypt two different messages using the
24// same key and counter in this mode - you will leak the key stream and
25// thereafter both plaintexts.
26//
27// Note: in theory it would be nicer to have a proper stateful API for this, but
28// in practive every client of raw CTR encryption in Chromium does single-shot
29// operations and throws away the counter value afterwards, so such complexity
30// would be wasted.
31
32CRYPTO_EXPORT void Encrypt(base::span<const uint8_t> key,
33 base::span<const uint8_t, kCounterSize> counter,
34 base::span<const uint8_t> in,
35 base::span<uint8_t> out);
36
37CRYPTO_EXPORT void Decrypt(base::span<const uint8_t> key,
38 base::span<const uint8_t, kCounterSize> counter,
39 base::span<const uint8_t> in,
40 base::span<uint8_t> out);
41
42// If it's more convenient, there are also wrappers that allocate a byte vector
43// for the result for you:
44
45CRYPTO_EXPORT std::vector<uint8_t> Encrypt(
46 base::span<const uint8_t> key,
47 base::span<const uint8_t, kCounterSize> iv,
48 base::span<const uint8_t> in);
49
50CRYPTO_EXPORT std::vector<uint8_t> Decrypt(
51 base::span<const uint8_t> key,
52 base::span<const uint8_t, kCounterSize> iv,
53 base::span<const uint8_t> in);
54
55} // namespace crypto::aes_ctr
56
57#endif // CRYPTO_AES_CTR_H_