Index: crypto/encryptor_win.cc |
diff --git a/crypto/encryptor_win.cc b/crypto/encryptor_win.cc |
index fae1f8220b73035252e91751bfcb8877f5d7d781..e4f108f03bbf7dc40810547c1ef5d48107c4f25b 100644 |
--- a/crypto/encryptor_win.cc |
+++ b/crypto/encryptor_win.cc |
@@ -41,8 +41,8 @@ Encryptor::~Encryptor() { |
bool Encryptor::Init(SymmetricKey* key, |
Mode mode, |
const base::StringPiece& iv) { |
- DCHECK(key); |
- DCHECK_EQ(CBC, mode) << "Unsupported mode of operation"; |
+ if (!key || mode != CBC) |
+ return false; |
// In CryptoAPI, the IV, padding mode, and feedback register (for a chaining |
// mode) are properties of a key, so we have to create a copy of the key for |
@@ -82,44 +82,50 @@ bool Encryptor::Init(SymmetricKey* key, |
bool Encryptor::Encrypt(const base::StringPiece& plaintext, |
std::string* ciphertext) { |
+ ciphertext->clear(); |
+ if (plaintext.empty() && mode_ != CBC) |
+ return false; |
+ |
DWORD data_len = plaintext.size(); |
DWORD total_len = data_len + block_size_; |
- CHECK_GT(total_len, data_len); |
+ if (total_len == 0 || total_len + 1 < data_len) |
+ return false; |
// CryptoAPI encrypts/decrypts in place. |
- char* ciphertext_data = WriteInto(ciphertext, total_len + 1); |
- memcpy(ciphertext_data, plaintext.data(), data_len); |
+ std::string result; |
+ char* result_data = WriteInto(&result, total_len + 1); |
+ memcpy(result_data, plaintext.data(), data_len); |
BOOL ok = CryptEncrypt(capi_key_.get(), NULL, TRUE, 0, |
- reinterpret_cast<BYTE*>(ciphertext_data), &data_len, |
+ reinterpret_cast<BYTE*>(result_data), &data_len, |
total_len); |
- if (!ok) { |
- ciphertext->clear(); |
+ if (!ok) |
return false; |
- } |
- ciphertext->resize(data_len); |
+ result.resize(data_len); |
+ ciphertext->swap(result); |
return true; |
} |
bool Encryptor::Decrypt(const base::StringPiece& ciphertext, |
std::string* plaintext) { |
+ plaintext->clear(); |
DWORD data_len = ciphertext.size(); |
- if (data_len == 0 || (data_len + 1) < data_len) |
+ if (data_len == 0 || data_len + 1 < data_len) |
return false; |
// CryptoAPI encrypts/decrypts in place. |
- char* plaintext_data = WriteInto(plaintext, data_len + 1); |
- memcpy(plaintext_data, ciphertext.data(), data_len); |
+ std::string result; |
+ char* result_data = WriteInto(&result, data_len + 1); |
+ memcpy(result_data, ciphertext.data(), data_len); |
BOOL ok = CryptDecrypt(capi_key_.get(), NULL, TRUE, 0, |
- reinterpret_cast<BYTE*>(plaintext_data), &data_len); |
- if (!ok) { |
- plaintext->clear(); |
+ reinterpret_cast<BYTE*>(result_data), &data_len); |
+ if (!ok) |
return false; |
- } |
- plaintext->resize(data_len); |
+ result.resize(data_len); |
+ plaintext->swap(result); |
return true; |
} |