Index: base/crypto/encryptor_mac.cc |
diff --git a/base/crypto/encryptor_mac.cc b/base/crypto/encryptor_mac.cc |
index 2b04537a2d1bd32364dc76a5dfc7cb3916a845a1..4e8984aff459fc440e71144190cc1c7f2c71c09b 100644 |
--- a/base/crypto/encryptor_mac.cc |
+++ b/base/crypto/encryptor_mac.cc |
@@ -4,10 +4,12 @@ |
#include "base/crypto/encryptor.h" |
-namespace base { |
+#include <CommonCrypto/CommonCryptor.h> |
+ |
+#include "base/logging.h" |
+#include "base/string_util.h" |
-// TODO(albertb): Implement on Mac using the Common Crypto Library: |
-// http://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man3/CCCryptor.3cc.html#//apple_ref/doc/man/10.5/3cc/CCCryptor?useVersion=10.5 |
+namespace base { |
Encryptor::Encryptor() { |
} |
@@ -16,15 +18,56 @@ Encryptor::~Encryptor() { |
} |
bool Encryptor::Init(SymmetricKey* key, Mode mode, const std::string& iv) { |
- return false; |
+ DCHECK(key); |
+ DCHECK_EQ(CBC, mode) << "Unsupported mode of operation"; |
+ CSSM_DATA raw_key = key->cssm_data(); |
+ if (raw_key.Length != kCCKeySizeAES128 && |
+ raw_key.Length != kCCKeySizeAES192 && |
+ raw_key.Length != kCCKeySizeAES256) |
+ return false; |
+ if (iv.size() != kCCBlockSizeAES128) |
+ return false; |
+ |
+ key_.reset(key); |
+ mode_ = mode; |
+ iv_ = iv; |
+ return true; |
+} |
+ |
+bool Encryptor::Crypt(int /*CCOperation*/ op, |
+ const std::string& input, |
+ std::string* output) { |
+ DCHECK(key_.get()); |
+ CSSM_DATA raw_key = key_->cssm_data(); |
+ // CommonCryptor.h: "A general rule for the size of the output buffer which |
+ // must be provided by the caller is that for block ciphers, the output |
+ // length is never larger than the input length plus the block size." |
+ |
+ size_t output_size = input.size() + iv_.size(); |
+ CCCryptorStatus err = CCCrypt(op, |
+ kCCAlgorithmAES128, |
+ kCCOptionPKCS7Padding, |
+ raw_key.Data, raw_key.Length, |
+ iv_.data(), |
+ input.data(), input.size(), |
+ WriteInto(output, output_size), |
+ output_size, |
+ &output_size); |
+ if (err) { |
+ output->resize(0); |
+ LOG(ERROR) << "CCCrypt returned " << err; |
+ return false; |
+ } |
+ output->resize(output_size); |
+ return true; |
} |
bool Encryptor::Encrypt(const std::string& plaintext, std::string* ciphertext) { |
- return false; |
+ return Crypt(kCCEncrypt, plaintext, ciphertext); |
} |
bool Encryptor::Decrypt(const std::string& ciphertext, std::string* plaintext) { |
- return false; |
+ return Crypt(kCCDecrypt, ciphertext, plaintext); |
} |
} // namespace base |