Add standard Base64 encoding support
[ Merge of http://go/wvgerrit/16550 ] This is in addition to Web safe Base64 encode/decode support by core. Change-Id: I9ed51721b138a7f15fb4d216796deadd5d5b31a2
This commit is contained in:
@@ -10,6 +10,7 @@
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
|
||||
#include <modp_b64.h>
|
||||
#include <modp_b64w.h>
|
||||
|
||||
#include "log.h"
|
||||
@@ -78,6 +79,26 @@ std::string b2a_hex(const std::string& byte) {
|
||||
byte.length());
|
||||
}
|
||||
|
||||
// Encode for standard base64 encoding (RFC4648).
|
||||
std::string Base64Encode(const std::vector<uint8_t>& bin_input) {
|
||||
if (bin_input.empty()) {
|
||||
return std::string();
|
||||
}
|
||||
|
||||
int in_size = bin_input.size();
|
||||
std::string b64_output(modp_b64_encode_len(in_size), 0);
|
||||
|
||||
int out_size = modp_b64_encode(
|
||||
&b64_output[0], reinterpret_cast<const char*>(&bin_input[0]), in_size);
|
||||
if (out_size == -1) {
|
||||
LOGE("Base64Encode failed");
|
||||
return std::string();
|
||||
}
|
||||
|
||||
b64_output.resize(out_size);
|
||||
return b64_output;
|
||||
}
|
||||
|
||||
// Filename-friendly base64 encoding (RFC4648), commonly referred to
|
||||
// as Base64WebSafeEncode.
|
||||
//
|
||||
@@ -111,6 +132,25 @@ std::string Base64SafeEncodeNoPad(const std::vector<uint8_t>& bin_input) {
|
||||
return b64_output;
|
||||
}
|
||||
|
||||
// Decode for standard base64 encoding (RFC4648).
|
||||
std::vector<uint8_t> Base64Decode(const std::string& b64_input) {
|
||||
if (b64_input.empty()) {
|
||||
return std::vector<uint8_t>();
|
||||
}
|
||||
|
||||
int in_size = b64_input.size();
|
||||
std::vector<uint8_t> bin_output(modp_b64_decode_len(in_size), 0);
|
||||
int out_size = modp_b64_decode(reinterpret_cast<char*>(&bin_output[0]),
|
||||
b64_input.data(), in_size);
|
||||
if (out_size == -1) {
|
||||
LOGE("Base64Decode failed");
|
||||
return std::vector<uint8_t>(0);
|
||||
}
|
||||
|
||||
bin_output.resize(out_size);
|
||||
return bin_output;
|
||||
}
|
||||
|
||||
// Decode for Filename-friendly base64 encoding (RFC4648), commonly referred
|
||||
// as Base64WebSafeDecode.
|
||||
std::vector<uint8_t> Base64SafeDecode(const std::string& b64_input) {
|
||||
|
||||
Reference in New Issue
Block a user