| OLD | NEW |
| (Empty) |
| 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. | |
| 4 | |
| 5 #include "base/crypto/encryptor.h" | |
| 6 | |
| 7 #include <CommonCrypto/CommonCryptor.h> | |
| 8 | |
| 9 #include "base/crypto/symmetric_key.h" | |
| 10 #include "base/logging.h" | |
| 11 #include "base/string_util.h" | |
| 12 | |
| 13 namespace base { | |
| 14 | |
| 15 Encryptor::Encryptor() | |
| 16 : key_(NULL), | |
| 17 mode_(CBC) { | |
| 18 } | |
| 19 | |
| 20 Encryptor::~Encryptor() { | |
| 21 } | |
| 22 | |
| 23 bool Encryptor::Init(SymmetricKey* key, Mode mode, const std::string& iv) { | |
| 24 DCHECK(key); | |
| 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) | |
| 30 return false; | |
| 31 if (iv.size() != kCCBlockSizeAES128) | |
| 32 return false; | |
| 33 | |
| 34 key_ = key; | |
| 35 mode_ = mode; | |
| 36 iv_ = iv; | |
| 37 return true; | |
| 38 } | |
| 39 | |
| 40 bool Encryptor::Crypt(int /*CCOperation*/ op, | |
| 41 const std::string& input, | |
| 42 std::string* output) { | |
| 43 DCHECK(key_); | |
| 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." | |
| 48 | |
| 49 size_t output_size = input.size() + iv_.size(); | |
| 50 CCCryptorStatus err = CCCrypt(op, | |
| 51 kCCAlgorithmAES128, | |
| 52 kCCOptionPKCS7Padding, | |
| 53 raw_key.Data, raw_key.Length, | |
| 54 iv_.data(), | |
| 55 input.data(), input.size(), | |
| 56 WriteInto(output, output_size+1), | |
| 57 output_size, | |
| 58 &output_size); | |
| 59 if (err) { | |
| 60 output->resize(0); | |
| 61 LOG(ERROR) << "CCCrypt returned " << err; | |
| 62 return false; | |
| 63 } | |
| 64 output->resize(output_size); | |
| 65 return true; | |
| 66 } | |
| 67 | |
| 68 bool Encryptor::Encrypt(const std::string& plaintext, std::string* ciphertext) { | |
| 69 return Crypt(kCCEncrypt, plaintext, ciphertext); | |
| 70 } | |
| 71 | |
| 72 bool Encryptor::Decrypt(const std::string& ciphertext, std::string* plaintext) { | |
| 73 return Crypt(kCCDecrypt, ciphertext, plaintext); | |
| 74 } | |
| 75 | |
| 76 } // namespace base | |
| OLD | NEW |