This source file includes following definitions.
- GetEncryptionKey
- EncryptString16
- DecryptString16
- EncryptString
- DecryptString
#include "components/os_crypt/os_crypt.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/strings/utf_string_conversions.h"
#include "crypto/encryptor.h"
#include "crypto/symmetric_key.h"
namespace {
const char kSalt[] = "saltysalt";
const size_t kDerivedKeySizeInBits = 128;
const size_t kEncryptionIterations = 1;
const size_t kIVBlockSizeAES128 = 16;
const char kObfuscationPrefix[] = "v10";
crypto::SymmetricKey* GetEncryptionKey() {
std::string password = "peanuts";
std::string salt(kSalt);
scoped_ptr<crypto::SymmetricKey> encryption_key(
crypto::SymmetricKey::DeriveKeyFromPassword(crypto::SymmetricKey::AES,
password,
salt,
kEncryptionIterations,
kDerivedKeySizeInBits));
DCHECK(encryption_key.get());
return encryption_key.release();
}
}
bool OSCrypt::EncryptString16(const base::string16& plaintext,
std::string* ciphertext) {
return EncryptString(base::UTF16ToUTF8(plaintext), ciphertext);
}
bool OSCrypt::DecryptString16(const std::string& ciphertext,
base::string16* plaintext) {
std::string utf8;
if (!DecryptString(ciphertext, &utf8))
return false;
*plaintext = base::UTF8ToUTF16(utf8);
return true;
}
bool OSCrypt::EncryptString(const std::string& plaintext,
std::string* ciphertext) {
if (plaintext.empty()) {
*ciphertext = std::string();
return true;
}
scoped_ptr<crypto::SymmetricKey> encryption_key(GetEncryptionKey());
if (!encryption_key.get())
return false;
std::string iv(kIVBlockSizeAES128, ' ');
crypto::Encryptor encryptor;
if (!encryptor.Init(encryption_key.get(), crypto::Encryptor::CBC, iv))
return false;
if (!encryptor.Encrypt(plaintext, ciphertext))
return false;
ciphertext->insert(0, kObfuscationPrefix);
return true;
}
bool OSCrypt::DecryptString(const std::string& ciphertext,
std::string* plaintext) {
if (ciphertext.empty()) {
*plaintext = std::string();
return true;
}
if (ciphertext.find(kObfuscationPrefix) != 0) {
*plaintext = ciphertext;
return true;
}
std::string raw_ciphertext = ciphertext.substr(strlen(kObfuscationPrefix));
scoped_ptr<crypto::SymmetricKey> encryption_key(GetEncryptionKey());
if (!encryption_key.get())
return false;
std::string iv(kIVBlockSizeAES128, ' ');
crypto::Encryptor encryptor;
if (!encryptor.Init(encryption_key.get(), crypto::Encryptor::CBC, iv))
return false;
if (!encryptor.Decrypt(raw_ciphertext, plaintext))
return false;
return true;
}