1
// Copyright © 2017-2020 Trust Wallet.
2
//
3
// This file is part of Trust. The full Trust copyright notice, including
4
// terms governing use, modification, and redistribution, is contained in the
5
// file LICENSE at the root of the source code distribution tree.
6

7
#pragma once
8

9
#include "Data.h"
10

11
#include <TrezorCrypto/base32.h>
12

13
#include <cassert>
14

15
namespace TW::Base32 {
16

17
/// Decode Base32 string, return bytes as Data
18
/// alphabet: Optional alphabet, if missing, default ALPHABET_RFC4648
19 1
inline bool decode(const std::string& encoded_in, Data& decoded_out, const char* alphabet_in = nullptr) {
20 1
    size_t inLen = encoded_in.size();
21
    // obtain output length first
22 1
    size_t outLen = base32_decoded_length(inLen);
23 1
    uint8_t buf[outLen];
24 1
    if (alphabet_in == nullptr) {
25 1
        alphabet_in = BASE32_ALPHABET_RFC4648;
26
    }
27
    // perform the base32 decode
28 1
    uint8_t* retval = base32_decode(encoded_in.data(), inLen, buf, outLen, alphabet_in);
29 1
    if (retval == nullptr) {
30 1
        return false;
31
    }
32 1
    decoded_out.assign(buf, buf + outLen);
33 1
    return true;
34
}
35

36
/// Encode bytes in Data to Base32 string
37
/// alphabet: Optional alphabet, if missing, default ALPHABET_RFC4648
38 1
inline std::string encode(const Data& val, const char* alphabet = nullptr) {
39 1
    size_t inLen = val.size();
40
    // obtain output length first, reserve for terminator
41 1
    size_t outLen = base32_encoded_length(inLen) + 1;
42 1
    char buf[outLen];
43 1
    if (alphabet == nullptr) {
44 1
        alphabet = BASE32_ALPHABET_RFC4648;
45
    }
46
    // perform the base32 encode
47 1
    char* retval = base32_encode(val.data(), inLen, buf, outLen, alphabet);
48 1
    if (retval == nullptr) {
49
        // return empty string if failed
50 0
        return std::string();
51
    }
52
    // make sure there is a terminator ath the end
53 1
    buf[outLen - 1] = '\0';
54 1
    return std::string(buf);
55
}
56

57
} // namespace TW::Base32

Read our documentation on viewing source code .

Loading