Commit f4386ba7 authored by Daniel Hosseinian's avatar Daniel Hosseinian Committed by Commit Bot

Implement base32:Base32Decode()

The current base32 component only has an encoder. A decoder would be
valuable, especially in testing situations where the input of the
encoder can be compared to decoded output of the encoder.

Change-Id: Ic675bb7dff405237d04f563f465a89966270bce4
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1865545Reviewed-by: default avatarGabriel Charette <gab@chromium.org>
Commit-Queue: Daniel Hosseinian <dhoss@chromium.org>
Cr-Commit-Position: refs/heads/master@{#708055}
parent af5040f3
...@@ -13,6 +13,18 @@ static_library("base32") { ...@@ -13,6 +13,18 @@ static_library("base32") {
] ]
} }
static_library("base32_test_util") {
sources = [
"base32_test_util.cc",
"base32_test_util.h",
]
deps = [
":base32",
"//base",
]
}
source_set("unit_tests") { source_set("unit_tests") {
testonly = true testonly = true
sources = [ sources = [
...@@ -21,6 +33,7 @@ source_set("unit_tests") { ...@@ -21,6 +33,7 @@ source_set("unit_tests") {
deps = [ deps = [
":base32", ":base32",
":base32_test_util",
"//base", "//base",
"//testing/gtest", "//testing/gtest",
] ]
......
...@@ -5,27 +5,18 @@ ...@@ -5,27 +5,18 @@
#include "components/base32/base32.h" #include "components/base32/base32.h"
#include <stddef.h> #include <stddef.h>
#include <algorithm>
#include <limits> #include <limits>
#include "base/logging.h" #include "base/logging.h"
#include "base/numerics/safe_math.h"
namespace base32 { namespace base32 {
namespace {
constexpr char kEncoding[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
} // namespace
std::string Base32Encode(base::StringPiece input, Base32EncodePolicy policy) { std::string Base32Encode(base::StringPiece input, Base32EncodePolicy policy) {
if (input.empty()) if (input.empty())
return std::string(); return std::string();
if (input.size() > std::numeric_limits<size_t>::max() / 8) {
NOTREACHED()
<< "Input is too large and would overflow encoded size computation.";
return std::string();
}
// Per RFC4648, the output is formed of 8 characters per 40 bits of input and // Per RFC4648, the output is formed of 8 characters per 40 bits of input and
// another 8 characters for the last group of [1,39] bits in the input. // another 8 characters for the last group of [1,39] bits in the input.
// That is: ceil(input.size() * 8.0 / 40.0) * 8 == // That is: ceil(input.size() * 8.0 / 40.0) * 8 ==
...@@ -37,7 +28,8 @@ std::string Base32Encode(base::StringPiece input, Base32EncodePolicy policy) { ...@@ -37,7 +28,8 @@ std::string Base32Encode(base::StringPiece input, Base32EncodePolicy policy) {
// input and one more for the last [1,4] bits. // input and one more for the last [1,4] bits.
// That is: ceil(input.size() * 8.0 / 5.0) == // That is: ceil(input.size() * 8.0 / 5.0) ==
// (input.size() * 8 + 4) / 5. // (input.size() * 8 + 4) / 5.
const size_t unpadded_length = (input.size() * 8 + 4) / 5; const size_t unpadded_length =
((base::MakeCheckedNum(input.size()) * 8 + 4) / 5).ValueOrDie();
std::string output; std::string output;
const size_t encoded_length = policy == Base32EncodePolicy::INCLUDE_PADDING const size_t encoded_length = policy == Base32EncodePolicy::INCLUDE_PADDING
...@@ -52,7 +44,7 @@ std::string Base32Encode(base::StringPiece input, Base32EncodePolicy policy) { ...@@ -52,7 +44,7 @@ std::string Base32Encode(base::StringPiece input, Base32EncodePolicy policy) {
int free_bits = 8; int free_bits = 8;
while (free_bits < 16) { while (free_bits < 16) {
// Extract the 5 leftmost bits in the stream // Extract the 5 leftmost bits in the stream
output.push_back(kEncoding[(bit_stream & 0xf800) >> 11]); output.push_back(kEncoding[bit_stream >> 11]);
bit_stream <<= 5; bit_stream <<= 5;
free_bits += 5; free_bits += 5;
...@@ -65,7 +57,7 @@ std::string Base32Encode(base::StringPiece input, Base32EncodePolicy policy) { ...@@ -65,7 +57,7 @@ std::string Base32Encode(base::StringPiece input, Base32EncodePolicy policy) {
} }
if (policy == Base32EncodePolicy::INCLUDE_PADDING) { if (policy == Base32EncodePolicy::INCLUDE_PADDING) {
output.append(padded_length - unpadded_length, '='); output.append(padded_length - unpadded_length, kPaddingChar);
} }
DCHECK_EQ(encoded_length, output.size()); DCHECK_EQ(encoded_length, output.size());
......
...@@ -11,6 +11,9 @@ ...@@ -11,6 +11,9 @@
namespace base32 { namespace base32 {
constexpr char kEncoding[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
constexpr char kPaddingChar = '=';
enum class Base32EncodePolicy { enum class Base32EncodePolicy {
// Include the trailing padding in the output, when necessary. // Include the trailing padding in the output, when necessary.
INCLUDE_PADDING, INCLUDE_PADDING,
......
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/base32/base32_test_util.h"
#include <stddef.h>
#include <limits>
#include "base/logging.h"
#include "base/numerics/safe_math.h"
#include "components/base32/base32.h"
namespace base32 {
namespace {
// Returns a 5 bit number between [0,31] matching the provided base 32 encoded
// character. Returns 0xff on error.
uint8_t ReverseMapping(char input_char) {
if (input_char >= 'A' && input_char <= 'Z')
return input_char - 'A';
else if (input_char >= '2' && input_char <= '7')
return input_char - '2' + 26;
NOTREACHED() << "Invalid base32 character";
return 0xff;
}
} // namespace
std::string Base32Decode(base::StringPiece input) {
if (input.empty())
return std::string();
// Remove padding, if any
const size_t padding_index = input.find(kPaddingChar);
if (padding_index != base::StringPiece::npos)
input.remove_suffix(input.size() - padding_index);
const size_t decoded_length =
(base::MakeCheckedNum(input.size()) * 5 / 8).ValueOrDie();
std::string output;
output.reserve(decoded_length);
// A bit stream which will be read from the left and appended to from the
// right as it's emptied.
uint16_t bit_stream = 0;
size_t free_bits = 16;
for (char input_char : input) {
const uint8_t decoded_5bits = ReverseMapping(input_char);
// If an invalid character is read from the input, then stop decoding.
if (decoded_5bits >= 32)
return std::string();
// Place the next decoded 5-bits in the stream.
bit_stream |= decoded_5bits << (free_bits - 5);
free_bits -= 5;
// If the stream is filled with a byte, flush the stream of that byte and
// append it to the output.
if (free_bits <= 8) {
output.push_back(static_cast<char>(bit_stream >> 8));
bit_stream <<= 8;
free_bits += 8;
}
}
DCHECK_EQ(decoded_length, output.size());
return output;
}
} // namespace base32
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_BASE32_BASE32_TEST_UTIL_H_
#define COMPONENTS_BASE32_BASE32_TEST_UTIL_H_
#include <string>
#include "base/strings/string_piece.h"
namespace base32 {
// Decodes the |input| string piece from base32.
std::string Base32Decode(base::StringPiece input);
} // namespace base32
#endif // COMPONENTS_BASE32_BASE32_TEST_UTIL_H_
...@@ -6,6 +6,7 @@ ...@@ -6,6 +6,7 @@
#include "base/stl_util.h" #include "base/stl_util.h"
#include "components/base32/base32.h" #include "components/base32/base32.h"
#include "components/base32/base32_test_util.h"
#include "testing/gtest/include/gtest/gtest.h" #include "testing/gtest/include/gtest/gtest.h"
namespace base32 { namespace base32 {
...@@ -20,9 +21,12 @@ TEST(Base32Test, EncodesRfcTestVectorsCorrectlyWithoutPadding) { ...@@ -20,9 +21,12 @@ TEST(Base32Test, EncodesRfcTestVectorsCorrectlyWithoutPadding) {
// Run the tests, with one more letter in the input every pass. // Run the tests, with one more letter in the input every pass.
for (size_t i = 0; i < base::size(expected); ++i) { for (size_t i = 0; i < base::size(expected); ++i) {
std::string output = Base32Encode(base::StringPiece(test_str, i), base::StringPiece test_substr(test_str, i);
Base32EncodePolicy::OMIT_PADDING); std::string encoded_output =
EXPECT_EQ(expected[i], output); Base32Encode(test_substr, Base32EncodePolicy::OMIT_PADDING);
EXPECT_EQ(expected[i], encoded_output);
std::string decoded_output = Base32Decode(encoded_output);
EXPECT_EQ(test_substr, decoded_output);
} }
} }
...@@ -36,8 +40,11 @@ TEST(Base32Test, EncodesRfcTestVectorsCorrectlyWithPadding) { ...@@ -36,8 +40,11 @@ TEST(Base32Test, EncodesRfcTestVectorsCorrectlyWithPadding) {
// Run the tests, with one more letter in the input every pass. // Run the tests, with one more letter in the input every pass.
for (size_t i = 0; i < base::size(expected); ++i) { for (size_t i = 0; i < base::size(expected); ++i) {
std::string output = Base32Encode(base::StringPiece(test_str, i)); base::StringPiece test_substr(test_str, i);
EXPECT_EQ(expected[i], output); std::string encoded_output = Base32Encode(test_substr);
EXPECT_EQ(expected[i], encoded_output);
std::string decoded_output = Base32Decode(encoded_output);
EXPECT_EQ(test_substr, decoded_output);
} }
} }
...@@ -47,9 +54,13 @@ TEST(Base32Test, EncodesSha256HashCorrectly) { ...@@ -47,9 +54,13 @@ TEST(Base32Test, EncodesSha256HashCorrectly) {
constexpr char hash[] = constexpr char hash[] =
"\x1f\x25\xe1\xca\xba\x4f\xf9\xb8\x27\x24\x83\x0f\xca\x60\xe4\xc2\xbe\xa8" "\x1f\x25\xe1\xca\xba\x4f\xf9\xb8\x27\x24\x83\x0f\xca\x60\xe4\xc2\xbe\xa8"
"\xc3\xa9\x44\x1c\x27\xb0\xb4\x3e\x6a\x96\x94\xc7\xb8\x04"; "\xc3\xa9\x44\x1c\x27\xb0\xb4\x3e\x6a\x96\x94\xc7\xb8\x04";
std::string output = Base32Encode(base::StringPiece(hash, 32), base::StringPiece test_str(hash, 32);
Base32EncodePolicy::OMIT_PADDING); std::string encoded_output =
EXPECT_EQ("D4S6DSV2J743QJZEQMH4UYHEYK7KRQ5JIQOCPMFUHZVJNFGHXACA", output); Base32Encode(test_str, Base32EncodePolicy::OMIT_PADDING);
EXPECT_EQ("D4S6DSV2J743QJZEQMH4UYHEYK7KRQ5JIQOCPMFUHZVJNFGHXACA",
encoded_output);
std::string decoded_output = Base32Decode(encoded_output);
EXPECT_EQ(test_str, decoded_output);
} }
} // namespace } // namespace
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment