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.
5 #include "net/quic/crypto/aead_base_decrypter.h"
7 #include <openssl/err.h>
8 #include <openssl/evp.h>
10 #include "base/memory/scoped_ptr.h"
12 using base::StringPiece
;
18 // Clear OpenSSL error stack.
19 void ClearOpenSslErrors() {
20 while (ERR_get_error()) {}
23 // In debug builds only, log OpenSSL error stack. Then clear OpenSSL error
25 void DLogOpenSslErrors() {
29 while (uint32_t error
= ERR_get_error()) {
31 ERR_error_string_n(error
, buf
, arraysize(buf
));
32 DLOG(ERROR
) << "OpenSSL error: " << buf
;
39 AeadBaseDecrypter::AeadBaseDecrypter(const EVP_AEAD
* aead_alg
,
42 size_t nonce_prefix_size
)
43 : aead_alg_(aead_alg
),
45 auth_tag_size_(auth_tag_size
),
46 nonce_prefix_size_(nonce_prefix_size
) {
47 DCHECK_LE(key_size_
, sizeof(key_
));
48 DCHECK_LE(nonce_prefix_size_
, sizeof(nonce_prefix_
));
51 AeadBaseDecrypter::~AeadBaseDecrypter() {}
53 bool AeadBaseDecrypter::SetKey(StringPiece key
) {
54 DCHECK_EQ(key
.size(), key_size_
);
55 if (key
.size() != key_size_
) {
58 memcpy(key_
, key
.data(), key
.size());
60 EVP_AEAD_CTX_cleanup(ctx_
.get());
61 if (!EVP_AEAD_CTX_init(ctx_
.get(), aead_alg_
, key_
, key_size_
,
62 auth_tag_size_
, nullptr)) {
70 bool AeadBaseDecrypter::SetNoncePrefix(StringPiece nonce_prefix
) {
71 DCHECK_EQ(nonce_prefix
.size(), nonce_prefix_size_
);
72 if (nonce_prefix
.size() != nonce_prefix_size_
) {
75 memcpy(nonce_prefix_
, nonce_prefix
.data(), nonce_prefix
.size());
79 bool AeadBaseDecrypter::DecryptPacket(QuicPacketNumber packet_number
,
80 const StringPiece
& associated_data
,
81 const StringPiece
& ciphertext
,
83 size_t* output_length
,
84 size_t max_output_length
) {
85 if (ciphertext
.length() < auth_tag_size_
) {
89 uint8 nonce
[sizeof(nonce_prefix_
) + sizeof(packet_number
)];
90 const size_t nonce_size
= nonce_prefix_size_
+ sizeof(packet_number
);
91 memcpy(nonce
, nonce_prefix_
, nonce_prefix_size_
);
92 memcpy(nonce
+ nonce_prefix_size_
, &packet_number
, sizeof(packet_number
));
93 if (!EVP_AEAD_CTX_open(
94 ctx_
.get(), reinterpret_cast<uint8_t*>(output
), output_length
,
95 max_output_length
, reinterpret_cast<const uint8_t*>(nonce
),
96 nonce_size
, reinterpret_cast<const uint8_t*>(ciphertext
.data()),
98 reinterpret_cast<const uint8_t*>(associated_data
.data()),
99 associated_data
.size())) {
100 // Because QuicFramer does trial decryption, decryption errors are expected
101 // when encryption level changes. So we don't log decryption errors.
102 ClearOpenSslErrors();
108 StringPiece
AeadBaseDecrypter::GetKey() const {
109 return StringPiece(reinterpret_cast<const char*>(key_
), key_size_
);
112 StringPiece
AeadBaseDecrypter::GetNoncePrefix() const {
113 if (nonce_prefix_size_
== 0) {
114 return StringPiece();
116 return StringPiece(reinterpret_cast<const char*>(nonce_prefix_
),