Skip to content
Snippets Groups Projects
Commit 266e48c4 authored by Nicolas Werner's avatar Nicolas Werner
Browse files

Add base58 decoding

parent 68e043e1
No related branches found
No related tags found
No related merge requests found
......@@ -106,5 +106,8 @@ bin2base64_urlsafe_unpadded(const std::string &bin);
std::string
bin2base58(const std::string &bin);
std::string
base582bin(const std::string &bin);
} // namespace crypto
} // namespace mtx
......@@ -641,4 +641,3 @@ mtx::crypto::decrypt_exported_sessions(const std::string &data, std::string pass
std::string plaintext(decrypted.begin(), decrypted.end());
return json::parse(plaintext);
}
#include <algorithm>
#include <array>
#include <string>
#include <vector>
......@@ -87,6 +88,43 @@ encode_base58(const std::array<char, 58> &alphabet, const std::string &input)
return result;
}
inline std::string
decode_base58(const std::array<uint8_t, 256> &reverse_alphabet, const std::string &input)
{
std::string result;
if (input.empty())
return result;
result.reserve(input.size() * 733 / 1000 + 1);
// result.push_back(0);
for (uint8_t b : input) {
if (b == ' ')
continue;
if (b == 0xff)
return "";
uint32_t carry = reverse_alphabet[b];
for (std::size_t j = 0; j < result.size(); j++) {
carry += static_cast<uint8_t>(result[j]) * 58;
result[j] = static_cast<uint8_t>(carry % 0x100);
carry /= 0x100;
}
while (carry > 0) {
result.push_back(static_cast<uint8_t>(carry % 0x100));
carry /= 0x100;
}
}
for (size_t i = 0; i < input.length() && input[i] == '1'; i++)
result.push_back(0);
std::reverse(result.begin(), result.end());
return result;
}
template<bool pad>
inline std::string
encode_base64(const std::array<char, 64> &alphabet, std::string input)
......@@ -210,5 +248,11 @@ bin2base58(const std::string &bin)
{
return encode_base58(base58_alphabet, bin);
}
std::string
base582bin(const std::string &bin)
{
return decode_base58(base58_to_int, bin);
}
}
}
......@@ -184,6 +184,14 @@ TEST(Base58, EncodingDecoding)
EXPECT_EQ(bin2base58("foob"), "3csAg9");
EXPECT_EQ(bin2base58("fooba"), "CZJRhmz");
EXPECT_EQ(bin2base58("foobar"), "t1Zv2yaZ");
EXPECT_EQ("", base582bin(""));
EXPECT_EQ("f", base582bin("2m"));
EXPECT_EQ("fo", base582bin("8o8"));
EXPECT_EQ("foo", base582bin("bQbp"));
EXPECT_EQ("foob", base582bin("3csAg9"));
EXPECT_EQ("fooba", base582bin("CZJRhmz"));
EXPECT_EQ("foobar", base582bin("t1Zv2yaZ"));
}
TEST(ExportSessions, EncryptDecrypt)
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment