Home | History | Annotate | Download | only in base
      1 // Copyright (c) 2012 The Chromium 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 "base/base64.h"
      6 
      7 #include <stddef.h>
      8 
      9 #include <modp_b64/modp_b64.h>
     10 
     11 namespace base {
     12 
     13 void Base64Encode(const StringPiece& input, std::string* output) {
     14   std::string temp;
     15   temp.resize(modp_b64_encode_len(input.size()));  // makes room for null byte
     16 
     17   // modp_b64_encode_len() returns at least 1, so temp[0] is safe to use.
     18   size_t output_size = modp_b64_encode(&(temp[0]), input.data(), input.size());
     19 
     20   temp.resize(output_size);  // strips off null byte
     21   output->swap(temp);
     22 }
     23 
     24 bool Base64Decode(const StringPiece& input, std::string* output) {
     25   std::string temp;
     26   temp.resize(modp_b64_decode_len(input.size()));
     27 
     28   // does not null terminate result since result is binary data!
     29   size_t input_size = input.size();
     30   size_t output_size = modp_b64_decode(&(temp[0]), input.data(), input_size);
     31   if (output_size == MODP_B64_ERROR)
     32     return false;
     33 
     34   temp.resize(output_size);
     35   output->swap(temp);
     36   return true;
     37 }
     38 
     39 }  // namespace base
     40