blob: 19079788c6ce61df5a3dd188d79b0e25ff959d3c [file] [log] [blame]
lambroslambrou@chromium.org0d2c4aa2012-05-18 03:34:59 +09001// Copyright (c) 2012 The Chromium Authors. All rights reserved.
hayato@chromium.org268ac3a2009-11-24 15:21:53 +09002// 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 "third_party/modp_b64/modp_b64.h"
8
9namespace base {
10
joth@chromium.org42544c82011-07-22 22:22:23 +090011bool Base64Encode(const StringPiece& input, std::string* output) {
hayato@chromium.org268ac3a2009-11-24 15:21:53 +090012 std::string temp;
13 temp.resize(modp_b64_encode_len(input.size())); // makes room for null byte
14
15 // null terminates result since result is base64 text!
16 int input_size = static_cast<int>(input.size());
lambroslambrou@chromium.org0d2c4aa2012-05-18 03:34:59 +090017
18 // modp_b64_encode_len() returns at least 1, so temp[0] is safe to use.
19 int output_size = modp_b64_encode(&(temp[0]), input.data(), input_size);
hayato@chromium.org268ac3a2009-11-24 15:21:53 +090020 if (output_size < 0)
21 return false;
22
23 temp.resize(output_size); // strips off null byte
24 output->swap(temp);
25 return true;
26}
27
joth@chromium.org42544c82011-07-22 22:22:23 +090028bool Base64Decode(const StringPiece& input, std::string* output) {
hayato@chromium.org268ac3a2009-11-24 15:21:53 +090029 std::string temp;
30 temp.resize(modp_b64_decode_len(input.size()));
31
32 // does not null terminate result since result is binary data!
33 int input_size = static_cast<int>(input.size());
34 int output_size = modp_b64_decode(&(temp[0]), input.data(), input_size);
35 if (output_size < 0)
36 return false;
37
38 temp.resize(output_size);
39 output->swap(temp);
40 return true;
41}
42
43} // namespace base