| 1 | #include "base32.hh" |
| 2 | |
| 3 | #include <algorithm> |
| 4 | #include <cctype> |
| 5 | #include <cstddef> |
| 6 | #include <iterator> |
| 7 | #include <stdexcept> |
| 8 | #include <string> |
| 9 | |
| 10 | int Base32::char_to_val(char c) { |
| 11 | std::string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; |
| 12 | auto it = std::find(alphabet.begin(), alphabet.end(), c); |
| 13 | return (it != alphabet.end()) ? std::distance(alphabet.begin(), it) : -1; |
| 14 | } |
| 15 | |
| 16 | std::vector<unsigned char> Base32::decode(const std::string &encoded) { |
| 17 | std::string encoded_up = encoded; |
| 18 | for (auto &c : encoded_up) { |
| 19 | c = std::toupper(static_cast<unsigned char>(c)); |
| 20 | } |
| 21 | |
| 22 | size_t encoded_len = encoded_up.length(); |
| 23 | size_t padding = 0; |
| 24 | for (int i = encoded_len - 1; i >= 0 && encoded_up[i] == '='; --i) { |
| 25 | ++padding; |
| 26 | } |
| 27 | |
| 28 | size_t out_len = (encoded_len - padding) * 5 / 8; |
| 29 | if (out_len == 0) return {}; |
| 30 | |
| 31 | std::vector<unsigned char> decoded(out_len); |
| 32 | |
| 33 | int buffer = 0, bits_left = 0, count = 0; |
| 34 | Base32 b32; |
| 35 | for (size_t i = 0; i < encoded_len - padding; ++i) { |
| 36 | int val = b32.char_to_val(encoded_up[i]); |
| 37 | if (val < 0) { |
| 38 | throw std::runtime_error("Base32エンコードした文字の中に不正な文字があります。"); |
| 39 | } |
| 40 | |
| 41 | buffer <<= 5; |
| 42 | buffer |= val; |
| 43 | bits_left += 5; |
| 44 | |
| 45 | if (bits_left >= 8) { |
| 46 | decoded[count++] = static_cast<unsigned char>(buffer >> (bits_left - 8)); |
| 47 | bits_left -= 8; |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | decoded.resize(count); |
| 52 | return decoded; |
| 53 | } |