1 // Copyright (c) 2013 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.
4
5 #include "quiche/quic/core/crypto/chacha_base_encrypter.h"
6
7 #include "absl/base/macros.h"
8 #include "absl/strings/string_view.h"
9 #include "openssl/chacha.h"
10 #include "quiche/quic/core/quic_data_reader.h"
11 #include "quiche/quic/platform/api/quic_bug_tracker.h"
12 #include "quiche/common/quiche_endian.h"
13
14 namespace quic {
15
SetHeaderProtectionKey(absl::string_view key)16 bool ChaChaBaseEncrypter::SetHeaderProtectionKey(absl::string_view key) {
17 if (key.size() != GetKeySize()) {
18 QUIC_BUG(quic_bug_10656_1) << "Invalid key size for header protection";
19 return false;
20 }
21 memcpy(pne_key_, key.data(), key.size());
22 return true;
23 }
24
GenerateHeaderProtectionMask(absl::string_view sample)25 std::string ChaChaBaseEncrypter::GenerateHeaderProtectionMask(
26 absl::string_view sample) {
27 if (sample.size() != 16) {
28 return std::string();
29 }
30 const uint8_t* nonce = reinterpret_cast<const uint8_t*>(sample.data()) + 4;
31 uint32_t counter;
32 QuicDataReader(sample.data(), 4, quiche::HOST_BYTE_ORDER)
33 .ReadUInt32(&counter);
34 const uint8_t zeroes[] = {0, 0, 0, 0, 0};
35 std::string out(ABSL_ARRAYSIZE(zeroes), 0);
36 CRYPTO_chacha_20(reinterpret_cast<uint8_t*>(const_cast<char*>(out.data())),
37 zeroes, ABSL_ARRAYSIZE(zeroes), pne_key_, nonce, counter);
38 return out;
39 }
40
41 } // namespace quic
42