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
,
25 const base::StringPiece
& iv
) {
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
)
33 if (iv
.size() != kCCBlockSizeAES128
)
38 iv
.CopyToString(&iv_
);
42 bool Encryptor::Crypt(int /*CCOperation*/ op
,
43 const base::StringPiece
& input
,
44 std::string
* output
) {
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
,
56 kCCOptionPKCS7Padding
,
57 raw_key
.Data
, raw_key
.Length
,
59 input
.data(), input
.size(),
60 WriteInto(output
, output_size
+ 1),
65 LOG(ERROR
) << "CCCrypt returned " << err
;
68 output
->resize(output_size
);
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
);