Home | History | Annotate | Download | only in brillo
      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 <cstring>  // memcpy
      6 
      7 #include <base/stl_util.h>
      8 
      9 #include "brillo/secure_blob.h"
     10 
     11 namespace brillo {
     12 
     13 SecureBlob::SecureBlob(const std::string& data)
     14     : SecureBlob(data.begin(), data.end()) {}
     15 
     16 SecureBlob::~SecureBlob() {
     17   clear();
     18 }
     19 
     20 void SecureBlob::resize(size_type count) {
     21   if (count < size()) {
     22     SecureMemset(data() + count, 0, capacity() - count);
     23   }
     24   Blob::resize(count);
     25 }
     26 
     27 void SecureBlob::resize(size_type count, const value_type& value) {
     28   if (count < size()) {
     29     SecureMemset(data() + count, 0, capacity() - count);
     30   }
     31   Blob::resize(count, value);
     32 }
     33 
     34 void SecureBlob::clear() {
     35   SecureMemset(data(), 0, capacity());
     36   Blob::clear();
     37 }
     38 
     39 std::string SecureBlob::to_string() const {
     40   return std::string(data(), data() + size());
     41 }
     42 
     43 SecureBlob SecureBlob::Combine(const SecureBlob& blob1,
     44                                const SecureBlob& blob2) {
     45   SecureBlob result;
     46   result.reserve(blob1.size() + blob2.size());
     47   result.insert(result.end(), blob1.begin(), blob1.end());
     48   result.insert(result.end(), blob2.begin(), blob2.end());
     49   return result;
     50 }
     51 
     52 void* SecureMemset(void* v, int c, size_t n) {
     53   volatile uint8_t* p = reinterpret_cast<volatile uint8_t*>(v);
     54   while (n--)
     55     *p++ = c;
     56   return v;
     57 }
     58 
     59 int SecureMemcmp(const void* s1, const void* s2, size_t n) {
     60   const uint8_t* us1 = reinterpret_cast<const uint8_t*>(s1);
     61   const uint8_t* us2 = reinterpret_cast<const uint8_t*>(s2);
     62   int result = 0;
     63 
     64   if (0 == n)
     65     return 1;
     66 
     67   /* Code snippet without data-dependent branch due to
     68    * Nate Lawson (nate (at) root.org) of Root Labs. */
     69   while (n--)
     70     result |= *us1++ ^ *us2++;
     71 
     72   return result != 0;
     73 }
     74 
     75 }  // namespace brillo
     76