blob: 1bd73590c4d469b05667a6511a1802da65226181 [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
Ben Chancd477322014-10-17 14:19:30 -07007#include <memory>
8
Ben Chana0ddf462014-02-06 11:32:42 -08009#include <base/strings/string_util.h>
Darin Petkov86964e02011-06-29 13:49:28 -070010
11#include "shill/crypto_des_cbc.h"
12#include "shill/crypto_rot47.h"
Christopher Wileyb691efd2012-08-09 13:51:51 -070013#include "shill/logging.h"
Darin Petkov86964e02011-06-29 13:49:28 -070014
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() {
Paul Stewart5ad16062013-02-21 18:10:48 -080026 cryptos_.clear();
Darin Petkov86964e02011-06-29 13:49:28 -070027
28 // Register the crypto modules in priority order -- highest priority first.
Ben Chancd477322014-10-17 14:19:30 -070029 std::unique_ptr<CryptoDESCBC> des_cbc(new CryptoDESCBC(glib_));
Darin Petkov86964e02011-06-29 13:49:28 -070030 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) {
Paul Stewart6db7b242014-05-02 15:34:21 -070037 for (auto crypto : cryptos_) {
Darin Petkov86964e02011-06-29 13:49:28 -070038 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) {
Paul Stewart6db7b242014-05-02 15:34:21 -070049 for (auto crypto : cryptos_) {
Darin Petkov86964e02011-06-29 13:49:28 -070050 const string prefix = crypto->GetID() + ":";
51 if (StartsWithASCII(ciphertext, prefix, true)) {
52 string to_decrypt = ciphertext;
53 to_decrypt.erase(0, prefix.size());
54 string plaintext;
Darin Petkov92e65612012-06-10 12:52:10 +020055 if (!crypto->Decrypt(to_decrypt, &plaintext)) {
56 LOG(WARNING) << "Crypto module " << crypto->GetID()
57 << " failed to decrypt.";
58 }
Darin Petkov86964e02011-06-29 13:49:28 -070059 return plaintext;
60 }
61 }
62 LOG(WARNING) << "Unable to decrypt text, returning as is.";
63 return ciphertext;
64}
65
66} // namespace shill