chromeos: bluetooth: add BluetoothInputClient
[chromium-blink-merge.git] / crypto / encryptor_mac.cc
blob6be373a5d92028052b1de94d5f1d85739b54ffcf
1 // Copyright (c) 2011 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 <CommonCrypto/CommonCryptor.h>
9 #include "base/logging.h"
10 #include "base/string_util.h"
11 #include "crypto/symmetric_key.h"
13 namespace crypto {
15 Encryptor::Encryptor()
16 : key_(NULL),
17 mode_(CBC) {
20 Encryptor::~Encryptor() {
23 bool Encryptor::Init(SymmetricKey* key,
24 Mode mode,
25 const base::StringPiece& iv) {
26 DCHECK(key);
27 DCHECK_EQ(CBC, mode) << "Unsupported mode of operation";
28 CSSM_DATA raw_key = key->cssm_data();
29 if (raw_key.Length != kCCKeySizeAES128 &&
30 raw_key.Length != kCCKeySizeAES192 &&
31 raw_key.Length != kCCKeySizeAES256)
32 return false;
33 if (iv.size() != kCCBlockSizeAES128)
34 return false;
36 key_ = key;
37 mode_ = mode;
38 iv.CopyToString(&iv_);
39 return true;
42 bool Encryptor::Crypt(int /*CCOperation*/ op,
43 const base::StringPiece& input,
44 std::string* output) {
45 DCHECK(key_);
46 CSSM_DATA raw_key = key_->cssm_data();
47 // CommonCryptor.h: "A general rule for the size of the output buffer which
48 // must be provided by the caller is that for block ciphers, the output
49 // length is never larger than the input length plus the block size."
51 size_t output_size = input.size() + iv_.size();
52 CHECK_GT(output_size, 0u);
53 CHECK_GT(output_size + 1, input.size());
54 CCCryptorStatus err = CCCrypt(op,
55 kCCAlgorithmAES128,
56 kCCOptionPKCS7Padding,
57 raw_key.Data, raw_key.Length,
58 iv_.data(),
59 input.data(), input.size(),
60 WriteInto(output, output_size + 1),
61 output_size,
62 &output_size);
63 if (err) {
64 output->clear();
65 LOG(ERROR) << "CCCrypt returned " << err;
66 return false;
68 output->resize(output_size);
69 return true;
72 bool Encryptor::Encrypt(const base::StringPiece& plaintext,
73 std::string* ciphertext) {
74 CHECK(!plaintext.empty() || (mode_ == CBC));
75 return Crypt(kCCEncrypt, plaintext, ciphertext);
78 bool Encryptor::Decrypt(const base::StringPiece& ciphertext,
79 std::string* plaintext) {
80 CHECK(!ciphertext.empty());
81 return Crypt(kCCDecrypt, ciphertext, plaintext);
84 } // namespace crypto