Home | History | Annotate | Download | only in shill
      1 //
      2 // Copyright (C) 2012 The Android Open Source Project
      3 //
      4 // Licensed under the Apache License, Version 2.0 (the "License");
      5 // you may not use this file except in compliance with the License.
      6 // You may obtain a copy of the License at
      7 //
      8 //      http://www.apache.org/licenses/LICENSE-2.0
      9 //
     10 // Unless required by applicable law or agreed to in writing, software
     11 // distributed under the License is distributed on an "AS IS" BASIS,
     12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13 // See the License for the specific language governing permissions and
     14 // limitations under the License.
     15 //
     16 
     17 #include "shill/crypto_provider.h"
     18 
     19 #include <memory>
     20 
     21 #include <base/strings/string_util.h>
     22 
     23 #include "shill/crypto_des_cbc.h"
     24 #include "shill/crypto_rot47.h"
     25 #include "shill/logging.h"
     26 
     27 using std::string;
     28 
     29 namespace shill {
     30 
     31 const char CryptoProvider::kKeyMatterFile[] = "/var/lib/whitelist/owner.key";
     32 
     33 CryptoProvider::CryptoProvider()
     34     : key_matter_file_(kKeyMatterFile) {}
     35 
     36 void CryptoProvider::Init() {
     37   cryptos_.clear();
     38 
     39   // Register the crypto modules in priority order -- highest priority first.
     40   std::unique_ptr<CryptoDESCBC> des_cbc(new CryptoDESCBC());
     41   if (des_cbc->LoadKeyMatter(key_matter_file_)) {
     42     cryptos_.push_back(des_cbc.release());
     43   }
     44   cryptos_.push_back(new CryptoROT47());
     45 }
     46 
     47 string CryptoProvider::Encrypt(const string& plaintext) {
     48   for (auto crypto : cryptos_) {
     49     string ciphertext;
     50     if (crypto->Encrypt(plaintext, &ciphertext)) {
     51       const string prefix = crypto->GetID() + ":";
     52       return prefix + ciphertext;
     53     }
     54   }
     55   LOG(WARNING) << "Unable to encrypt text, returning as is.";
     56   return plaintext;
     57 }
     58 
     59 string CryptoProvider::Decrypt(const string& ciphertext) {
     60   for (auto crypto : cryptos_) {
     61     const string prefix = crypto->GetID() + ":";
     62     if (base::StartsWith(ciphertext, prefix, base::CompareCase::SENSITIVE)) {
     63       string to_decrypt = ciphertext;
     64       to_decrypt.erase(0, prefix.size());
     65       string plaintext;
     66       if (!crypto->Decrypt(to_decrypt, &plaintext)) {
     67         LOG(WARNING) << "Crypto module " << crypto->GetID()
     68                      << " failed to decrypt.";
     69       }
     70       return plaintext;
     71     }
     72   }
     73   LOG(WARNING) << "Unable to decrypt text, returning as is.";
     74   return ciphertext;
     75 }
     76 
     77 }  // namespace shill
     78