[email protected] | c8838bf | 2012-05-17 18:34:59 | [diff] [blame] | 1 | // Copyright (c) 2012 The Chromium Authors. All rights reserved. |
license.bot | bf09a50 | 2008-08-24 00:55:55 | [diff] [blame] | 2 | // Use of this source code is governed by a BSD-style license that can be |
3 | // found in the LICENSE file. | ||||
initial.commit | 586acc5fe | 2008-07-26 22:42:52 | [diff] [blame] | 4 | |
[email protected] | 978df34 | 2009-11-24 06:21:53 | [diff] [blame] | 5 | #include "base/base64.h" |
initial.commit | 586acc5fe | 2008-07-26 22:42:52 | [diff] [blame] | 6 | |
avi | 9b6f4293 | 2015-12-26 22:15:14 | [diff] [blame] | 7 | #include <stddef.h> |
8 | |||||
initial.commit | 586acc5fe | 2008-07-26 22:42:52 | [diff] [blame] | 9 | #include "third_party/modp_b64/modp_b64.h" |
initial.commit | 586acc5fe | 2008-07-26 22:42:52 | [diff] [blame] | 10 | |
[email protected] | 978df34 | 2009-11-24 06:21:53 | [diff] [blame] | 11 | namespace base { |
[email protected] | a9bb6f69 | 2008-07-30 16:40:10 | [diff] [blame] | 12 | |
[email protected] | 33fca12 | 2013-12-11 01:48:50 | [diff] [blame] | 13 | void Base64Encode(const StringPiece& input, std::string* output) { |
initial.commit | 586acc5fe | 2008-07-26 22:42:52 | [diff] [blame] | 14 | std::string temp; |
15 | temp.resize(modp_b64_encode_len(input.size())); // makes room for null byte | ||||
16 | |||||
[email protected] | c8838bf | 2012-05-17 18:34:59 | [diff] [blame] | 17 | // modp_b64_encode_len() returns at least 1, so temp[0] is safe to use. |
[email protected] | 33fca12 | 2013-12-11 01:48:50 | [diff] [blame] | 18 | size_t output_size = modp_b64_encode(&(temp[0]), input.data(), input.size()); |
initial.commit | 586acc5fe | 2008-07-26 22:42:52 | [diff] [blame] | 19 | |
20 | temp.resize(output_size); // strips off null byte | ||||
21 | output->swap(temp); | ||||
initial.commit | 586acc5fe | 2008-07-26 22:42:52 | [diff] [blame] | 22 | } |
23 | |||||
[email protected] | 1dda977 | 2011-07-22 13:22:23 | [diff] [blame] | 24 | bool Base64Decode(const StringPiece& input, std::string* output) { |
initial.commit | 586acc5fe | 2008-07-26 22:42:52 | [diff] [blame] | 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! | ||||
[email protected] | c525312 | 2012-12-27 22:01:58 | [diff] [blame] | 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) | ||||
initial.commit | 586acc5fe | 2008-07-26 22:42:52 | [diff] [blame] | 32 | return false; |
33 | |||||
34 | temp.resize(output_size); | ||||
35 | output->swap(temp); | ||||
36 | return true; | ||||
37 | } | ||||
[email protected] | a9bb6f69 | 2008-07-30 16:40:10 | [diff] [blame] | 38 | |
[email protected] | 978df34 | 2009-11-24 06:21:53 | [diff] [blame] | 39 | } // namespace base |