crypto_provider.cc revision a794cd60a7339d576ea2eed263a4f0a20fb255af
1// Copyright (c) 2012 The Chromium OS 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#include "shill/crypto_provider.h" 6 7#include <memory> 8 9#include <base/strings/string_util.h> 10 11#include "shill/crypto_des_cbc.h" 12#include "shill/crypto_rot47.h" 13#include "shill/logging.h" 14 15using std::string; 16 17namespace shill { 18 19const char CryptoProvider::kKeyMatterFile[] = "/var/lib/whitelist/owner.key"; 20 21CryptoProvider::CryptoProvider(GLib* glib) 22 : glib_(glib), 23 key_matter_file_(kKeyMatterFile) {} 24 25void CryptoProvider::Init() { 26 cryptos_.clear(); 27 28 // Register the crypto modules in priority order -- highest priority first. 29 std::unique_ptr<CryptoDESCBC> des_cbc(new CryptoDESCBC(glib_)); 30 if (des_cbc->LoadKeyMatter(key_matter_file_)) { 31 cryptos_.push_back(des_cbc.release()); 32 } 33 cryptos_.push_back(new CryptoROT47()); 34} 35 36string CryptoProvider::Encrypt(const string& plaintext) { 37 for (auto crypto : cryptos_) { 38 string ciphertext; 39 if (crypto->Encrypt(plaintext, &ciphertext)) { 40 const string prefix = crypto->GetID() + ":"; 41 return prefix + ciphertext; 42 } 43 } 44 LOG(WARNING) << "Unable to encrypt text, returning as is."; 45 return plaintext; 46} 47 48string CryptoProvider::Decrypt(const string& ciphertext) { 49 for (auto crypto : cryptos_) { 50 const string prefix = crypto->GetID() + ":"; 51 if (base::StartsWithASCII(ciphertext, prefix, true)) { 52 string to_decrypt = ciphertext; 53 to_decrypt.erase(0, prefix.size()); 54 string plaintext; 55 if (!crypto->Decrypt(to_decrypt, &plaintext)) { 56 LOG(WARNING) << "Crypto module " << crypto->GetID() 57 << " failed to decrypt."; 58 } 59 return plaintext; 60 } 61 } 62 LOG(WARNING) << "Unable to decrypt text, returning as is."; 63 return ciphertext; 64} 65 66} // namespace shill 67