base64_tests.cpp
1 // Copyright (c) 2011-present The Bitcoin Core developers 2 // Distributed under the MIT software license, see the accompanying 3 // file COPYING or http://www.opensource.org/licenses/mit-license.php. 4 5 #include <util/strencodings.h> 6 7 #include <boost/test/unit_test.hpp> 8 9 #include <algorithm> 10 #include <string> 11 12 using namespace std::literals; 13 14 BOOST_AUTO_TEST_SUITE(base64_tests) 15 16 BOOST_AUTO_TEST_CASE(base64_testvectors) 17 { 18 static const std::string vstrIn[] = {"","f","fo","foo","foob","fooba","foobar"}; 19 static const std::string vstrOut[] = {"","Zg==","Zm8=","Zm9v","Zm9vYg==","Zm9vYmE=","Zm9vYmFy"}; 20 for (unsigned int i=0; i<std::size(vstrIn); i++) 21 { 22 std::string strEnc = EncodeBase64(vstrIn[i]); 23 BOOST_CHECK_EQUAL(strEnc, vstrOut[i]); 24 auto dec = DecodeBase64(strEnc); 25 BOOST_REQUIRE(dec); 26 BOOST_CHECK_MESSAGE(std::ranges::equal(*dec, vstrIn[i]), vstrOut[i]); 27 } 28 29 { 30 const std::vector<uint8_t> in_u{0xff, 0x01, 0xff}; 31 const std::vector<std::byte> in_b{std::byte{0xff}, std::byte{0x01}, std::byte{0xff}}; 32 const std::string in_s{"\xff\x01\xff"}; 33 const std::string out_exp{"/wH/"}; 34 BOOST_CHECK_EQUAL(EncodeBase64(in_u), out_exp); 35 BOOST_CHECK_EQUAL(EncodeBase64(in_b), out_exp); 36 BOOST_CHECK_EQUAL(EncodeBase64(in_s), out_exp); 37 } 38 39 BOOST_CHECK(DecodeBase64("nQB/pZw=")); // valid 40 41 // Decoding strings with embedded NUL characters should fail 42 BOOST_CHECK(!DecodeBase64("invalid\0"sv)); // correct size, invalid due to \0 43 BOOST_CHECK(!DecodeBase64("nQB/pZw=\0invalid"sv)); 44 BOOST_CHECK(!DecodeBase64("nQB/pZw=invalid\0"sv)); // invalid, padding only allowed at the end 45 } 46 47 BOOST_AUTO_TEST_CASE(base64_padding) 48 { 49 // Is valid without padding 50 BOOST_CHECK_EQUAL(EncodeBase64("foobar"), "Zm9vYmFy"); 51 52 // Valid size 53 BOOST_CHECK(!DecodeBase64("====")); 54 BOOST_CHECK(!DecodeBase64("a===")); 55 BOOST_CHECK( DecodeBase64("YQ==")); 56 BOOST_CHECK( DecodeBase64("YWE=")); 57 } 58 59 BOOST_AUTO_TEST_SUITE_END()