blob: 1ca4b04220d66408751c26d4872ca14f18db301d [file] [log] [blame]
Darin Petkov86964e02011-06-29 13:49:28 -07001// Copyright (c) 2011 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 <base/logging.h>
8#include <base/memory/scoped_ptr.h>
9#include <base/string_util.h>
10
11#include "shill/crypto_des_cbc.h"
12#include "shill/crypto_rot47.h"
13
14using std::string;
15
16namespace shill {
17
18const char CryptoProvider::kKeyMatterFile[] = "/var/lib/whitelist/owner.key";
19
20CryptoProvider::CryptoProvider(GLib *glib)
21 : glib_(glib),
22 key_matter_file_(kKeyMatterFile) {}
23
24void CryptoProvider::Init() {
25 cryptos_.reset();
26
27 // Register the crypto modules in priority order -- highest priority first.
28 scoped_ptr<CryptoDESCBC> des_cbc(new CryptoDESCBC(glib_));
29 if (des_cbc->LoadKeyMatter(key_matter_file_)) {
30 cryptos_.push_back(des_cbc.release());
31 }
32 cryptos_.push_back(new CryptoROT47());
33}
34
35string CryptoProvider::Encrypt(const string &plaintext) {
36 for (Cryptos::iterator it = cryptos_.begin(); it != cryptos_.end(); ++it) {
37 CryptoInterface *crypto = *it;
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 (Cryptos::iterator it = cryptos_.begin(); it != cryptos_.end(); ++it) {
50 CryptoInterface *crypto = *it;
51 const string prefix = crypto->GetID() + ":";
52 if (StartsWithASCII(ciphertext, prefix, true)) {
53 string to_decrypt = ciphertext;
54 to_decrypt.erase(0, prefix.size());
55 string plaintext;
56 LOG_IF(WARNING, !crypto->Decrypt(to_decrypt, &plaintext))
57 << "Crypto module " << crypto->GetID() << " failed to decrypt.";
58 return plaintext;
59 }
60 }
61 LOG(WARNING) << "Unable to decrypt text, returning as is.";
62 return ciphertext;
63}
64
65} // namespace shill