Reland revision 174161 (reverted in 174163 because it broke the build).
[chromium-blink-merge.git] / sync / util / data_encryption_win.cc
blob943f849e36a27bc34f4159cac64a2e9a48da0369
1 // Copyright (c) 2012 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 "sync/util/data_encryption_win.h"
7 #include <windows.h>
8 #include <wincrypt.h>
10 #include <cstddef>
12 #include "base/logging.h"
14 #pragma comment(lib, "crypt32.lib")
16 // TODO(akalin): Merge this with similar code in
17 // chrome/browser/password_manager/encryptor_win.cc. Preferably, all
18 // this stuff would live in crypto/.
20 namespace syncer {
22 std::vector<uint8> EncryptData(const std::string& data) {
23 DATA_BLOB unencrypted_data = { 0 };
24 unencrypted_data.pbData = (BYTE*)(data.data());
25 unencrypted_data.cbData = data.size();
26 DATA_BLOB encrypted_data = { 0 };
28 if (!CryptProtectData(&unencrypted_data, L"", NULL, NULL, NULL, 0,
29 &encrypted_data))
30 LOG(ERROR) << "Encryption fails: " << data;
32 std::vector<uint8> result(encrypted_data.pbData,
33 encrypted_data.pbData + encrypted_data.cbData);
34 LocalFree(encrypted_data.pbData);
35 return result;
38 bool DecryptData(const std::vector<uint8>& in_data, std::string* out_data) {
39 DATA_BLOB encrypted_data, decrypted_data;
40 encrypted_data.pbData =
41 (in_data.empty() ? NULL : const_cast<BYTE*>(&in_data[0]));
42 encrypted_data.cbData = in_data.size();
43 LPWSTR descrip = L"";
45 if (!CryptUnprotectData(&encrypted_data, &descrip, NULL, NULL, NULL, 0,
46 &decrypted_data)) {
47 LOG(ERROR) << "Decryption fails: ";
48 return false;
49 } else {
50 out_data->assign(reinterpret_cast<const char*>(decrypted_data.pbData),
51 decrypted_data.cbData);
52 LocalFree(decrypted_data.pbData);
53 return true;
57 } // namespace syncer