blob: 9273334bae33a8b44e7dd3335781d04bfd12cbaf [file] [log] [blame]
Darin Petkov92e65612012-06-10 12:52:10 +02001// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Darin Petkov86964e02011-06-29 13:49:28 -07002// 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
Darin Petkov86964e02011-06-29 13:49:28 -07007#include <base/memory/scoped_ptr.h>
8#include <base/string_util.h>
9
10#include "shill/crypto_des_cbc.h"
11#include "shill/crypto_rot47.h"
Christopher Wileyb691efd2012-08-09 13:51:51 -070012#include "shill/logging.h"
Darin Petkov86964e02011-06-29 13:49:28 -070013
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() {
Paul Stewart5ad16062013-02-21 18:10:48 -080025 cryptos_.clear();
Darin Petkov86964e02011-06-29 13:49:28 -070026
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;
Darin Petkov92e65612012-06-10 12:52:10 +020056 if (!crypto->Decrypt(to_decrypt, &plaintext)) {
57 LOG(WARNING) << "Crypto module " << crypto->GetID()
58 << " failed to decrypt.";
59 }
Darin Petkov86964e02011-06-29 13:49:28 -070060 return plaintext;
61 }
62 }
63 LOG(WARNING) << "Unable to decrypt text, returning as is.";
64 return ciphertext;
65}
66
67} // namespace shill