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 #include "crypto/encryptor.h"
7 #include "base/logging.h"
8 #include "base/sys_byteorder.h"
12 /////////////////////////////////////////////////////////////////////////////
13 // Encyptor::Counter Implementation.
14 Encryptor::Counter::Counter(const base::StringPiece& counter) {
15 CHECK(sizeof(counter_) == counter.length());
17 memcpy(&counter_, counter.data(), sizeof(counter_));
20 Encryptor::Counter::~Counter() {
23 bool Encryptor::Counter::Increment() {
24 uint64 low_num = base::NetToHost64(counter_.components64[1]);
25 uint64 new_low_num = low_num + 1;
26 counter_.components64[1] = base::HostToNet64(new_low_num);
28 // If overflow occured then increment the most significant component.
29 if (new_low_num < low_num) {
30 counter_.components64[0] =
31 base::HostToNet64(base::NetToHost64(counter_.components64[0]) + 1);
34 // TODO(hclam): Return false if counter value overflows.
38 void Encryptor::Counter::Write(void* buf) {
39 uint8* buf_ptr = reinterpret_cast<uint8*>(buf);
40 memcpy(buf_ptr, &counter_, sizeof(counter_));
43 size_t Encryptor::Counter::GetLengthInBytes() const {
44 return sizeof(counter_);
47 /////////////////////////////////////////////////////////////////////////////
48 // Partial Encryptor Implementation.
50 bool Encryptor::SetCounter(const base::StringPiece& counter) {
53 if (counter.length() != 16u)
56 counter_.reset(new Counter(counter));
60 bool Encryptor::GenerateCounterMask(size_t plaintext_len,
63 DCHECK_EQ(CTR, mode_);
67 const size_t kBlockLength = counter_->GetLengthInBytes();
68 size_t blocks = (plaintext_len + kBlockLength - 1) / kBlockLength;
71 *mask_len = blocks * kBlockLength;
73 for (size_t i = 0; i < blocks; ++i) {
74 counter_->Write(mask);
77 bool ret = counter_->Increment();
84 void Encryptor::MaskMessage(const void* plaintext,
87 void* ciphertext) const {
88 DCHECK_EQ(CTR, mode_);
89 const uint8* plaintext_ptr = reinterpret_cast<const uint8*>(plaintext);
90 const uint8* mask_ptr = reinterpret_cast<const uint8*>(mask);
91 uint8* ciphertext_ptr = reinterpret_cast<uint8*>(ciphertext);
93 for (size_t i = 0; i < plaintext_len; ++i)
94 ciphertext_ptr[i] = plaintext_ptr[i] ^ mask_ptr[i];