Home | History | Annotate | Download | only in util
      1 // Copyright (c) 2010 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 // NOTE: this file is Winodws specific.
      6 
      7 #include "chrome/browser/sync/util/data_encryption.h"
      8 
      9 #include <windows.h>
     10 #include <wincrypt.h>
     11 
     12 #include <cstddef>
     13 #include <string>
     14 #include <vector>
     15 
     16 #include "base/logging.h"
     17 
     18 using std::string;
     19 using std::vector;
     20 
     21 vector<uint8> EncryptData(const string& data) {
     22   DATA_BLOB unencrypted_data = { 0 };
     23   unencrypted_data.pbData = (BYTE*)(data.data());
     24   unencrypted_data.cbData = data.size();
     25   DATA_BLOB encrypted_data = { 0 };
     26 
     27   if (!CryptProtectData(&unencrypted_data, L"", NULL, NULL, NULL, 0,
     28                         &encrypted_data))
     29     LOG(ERROR) << "Encryption fails: " << data;
     30 
     31   vector<uint8> result(encrypted_data.pbData,
     32                        encrypted_data.pbData + encrypted_data.cbData);
     33   LocalFree(encrypted_data.pbData);
     34   return result;
     35 }
     36 
     37 bool DecryptData(const vector<uint8>& in_data, string* out_data) {
     38   DATA_BLOB encrypted_data, decrypted_data;
     39   encrypted_data.pbData =
     40     (in_data.empty() ? NULL : const_cast<BYTE*>(&in_data[0]));
     41   encrypted_data.cbData = in_data.size();
     42   LPWSTR descrip = L"";
     43 
     44   if (!CryptUnprotectData(&encrypted_data, &descrip, NULL, NULL, NULL, 0,
     45                           &decrypted_data)) {
     46     LOG(ERROR) << "Decryption fails: ";
     47     return false;
     48   } else {
     49     out_data->assign(reinterpret_cast<const char*>(decrypted_data.pbData),
     50                      decrypted_data.cbData);
     51     LocalFree(decrypted_data.pbData);
     52     return true;
     53   }
     54 }
     55