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"
15 Encryptor::Encryptor()
20 Encryptor::~Encryptor() {
23 bool Encryptor::Init(SymmetricKey
* key
, Mode mode
, const std::string
& iv
) {
25 DCHECK_EQ(CBC
, mode
) << "Unsupported mode of operation";
26 CSSM_DATA raw_key
= key
->cssm_data();
27 if (raw_key
.Length
!= kCCKeySizeAES128
&&
28 raw_key
.Length
!= kCCKeySizeAES192
&&
29 raw_key
.Length
!= kCCKeySizeAES256
)
31 if (iv
.size() != kCCBlockSizeAES128
)
40 bool Encryptor::Crypt(int /*CCOperation*/ op
,
41 const std::string
& input
,
42 std::string
* output
) {
44 CSSM_DATA raw_key
= key_
->cssm_data();
45 // CommonCryptor.h: "A general rule for the size of the output buffer which
46 // must be provided by the caller is that for block ciphers, the output
47 // length is never larger than the input length plus the block size."
49 size_t output_size
= input
.size() + iv_
.size();
50 CCCryptorStatus err
= CCCrypt(op
,
52 kCCOptionPKCS7Padding
,
53 raw_key
.Data
, raw_key
.Length
,
55 input
.data(), input
.size(),
56 WriteInto(output
, output_size
+1),
61 LOG(ERROR
) << "CCCrypt returned " << err
;
64 output
->resize(output_size
);
68 bool Encryptor::Encrypt(const std::string
& plaintext
, std::string
* ciphertext
) {
69 return Crypt(kCCEncrypt
, plaintext
, ciphertext
);
72 bool Encryptor::Decrypt(const std::string
& ciphertext
, std::string
* plaintext
) {
73 return Crypt(kCCDecrypt
, ciphertext
, plaintext
);