Branch data Line data Source code
1 : : // Copyright (c) 2011-2022 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 : : #include <string>
9 : :
10 : : using namespace std::literals;
11 : :
12 : : BOOST_AUTO_TEST_SUITE(base64_tests)
13 : :
14 [ + - + - : 7 : BOOST_AUTO_TEST_CASE(base64_testvectors)
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- ]
15 : : {
16 [ + - + - : 2 : static const std::string vstrIn[] = {"","f","fo","foo","foob","fooba","foobar"};
+ - + - +
- + - + -
+ - + - -
- ]
17 [ + - + - : 2 : static const std::string vstrOut[] = {"","Zg==","Zm8=","Zm9v","Zm9vYg==","Zm9vYmE=","Zm9vYmFy"};
+ - + - +
- + - + -
+ - + - -
- ]
18 [ + + ]: 8 : for (unsigned int i=0; i<std::size(vstrIn); i++)
19 : : {
20 : 7 : std::string strEnc = EncodeBase64(vstrIn[i]);
21 [ + - + - ]: 7 : BOOST_CHECK_EQUAL(strEnc, vstrOut[i]);
22 [ + - ]: 7 : auto dec = DecodeBase64(strEnc);
23 [ + - + - : 14 : BOOST_REQUIRE(dec);
+ - ]
24 [ + - + - ]: 14 : BOOST_CHECK_MESSAGE(MakeByteSpan(*dec) == MakeByteSpan(vstrIn[i]), vstrOut[i]);
25 : 7 : }
26 : :
27 : 1 : {
28 : 1 : const std::vector<uint8_t> in_u{0xff, 0x01, 0xff};
29 [ + - ]: 1 : const std::vector<std::byte> in_b{std::byte{0xff}, std::byte{0x01}, std::byte{0xff}};
30 [ + - ]: 1 : const std::string in_s{"\xff\x01\xff"};
31 [ + - ]: 1 : const std::string out_exp{"/wH/"};
32 [ + - + - : 1 : BOOST_CHECK_EQUAL(EncodeBase64(in_u), out_exp);
+ - ]
33 [ + - + - : 1 : BOOST_CHECK_EQUAL(EncodeBase64(in_b), out_exp);
+ - ]
34 [ + - + - : 2 : BOOST_CHECK_EQUAL(EncodeBase64(in_s), out_exp);
+ - ]
35 : 1 : }
36 : :
37 : : // Decoding strings with embedded NUL characters should fail
38 [ + - + - : 2 : BOOST_CHECK(!DecodeBase64("invalid\0"s));
+ - ]
39 [ + - + - : 2 : BOOST_CHECK(DecodeBase64("nQB/pZw="s));
+ - ]
40 [ + - + - : 2 : BOOST_CHECK(!DecodeBase64("nQB/pZw=\0invalid"s));
+ - ]
41 [ + - + - : 2 : BOOST_CHECK(!DecodeBase64("nQB/pZw=invalid\0"s));
+ - ]
42 : 1 : }
43 : :
44 : : BOOST_AUTO_TEST_SUITE_END()
|