ipc: Use a global for the process's attachment broker.
[chromium-blink-merge.git] / crypto / encryptor.cc
bloba673f81c1781d47f2338adc220474d6a79d4b5da
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"
10 namespace crypto {
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.
35 return true;
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) {
51 if (mode_ != CTR)
52 return false;
53 if (counter.length() != 16u)
54 return false;
56 counter_.reset(new Counter(counter));
57 return true;
60 bool Encryptor::GenerateCounterMask(size_t plaintext_len,
61 uint8* mask,
62 size_t* mask_len) {
63 DCHECK_EQ(CTR, mode_);
64 CHECK(mask);
65 CHECK(mask_len);
67 const size_t kBlockLength = counter_->GetLengthInBytes();
68 size_t blocks = (plaintext_len + kBlockLength - 1) / kBlockLength;
69 CHECK(blocks);
71 *mask_len = blocks * kBlockLength;
73 for (size_t i = 0; i < blocks; ++i) {
74 counter_->Write(mask);
75 mask += kBlockLength;
77 bool ret = counter_->Increment();
78 if (!ret)
79 return false;
81 return true;
84 void Encryptor::MaskMessage(const void* plaintext,
85 size_t plaintext_len,
86 const void* mask,
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];
97 } // namespace crypto