rust_hdwallet/hdwallet/libs/
base32.rs1use data_encoding::BASE32;
2use thiserror::Error;
3
4pub const ALPHABET: &str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
5
6#[derive(Debug, Error)]
7pub enum Base32Error {
8 #[error("Invalid Base32 string")]
9 Invalid,
10 #[error("Invalid hex string")]
11 InvalidHex(#[from] hex::FromHexError),
12 #[error("alphabet lengths must match")]
13 AlphabetMismatch,
14}
15
16pub fn add_padding(data: &str) -> String {
17 let last_block_width = data.len() % 8;
18 if last_block_width != 0 {
19 format!("{}{}", data, "=".repeat(8 - last_block_width))
20 } else {
21 data.to_owned()
22 }
23}
24
25pub fn translate_alphabet(data: &str, from_alphabet: &str, to_alphabet: &str) -> Result<String, Base32Error> {
26 if from_alphabet.len() != to_alphabet.len() {
27 return Err(Base32Error::AlphabetMismatch);
28 }
29 let mut table: [u8; 256] = std::array::from_fn(|i| i as u8);
30 for (a, b) in from_alphabet.bytes().zip(to_alphabet.bytes()) {
31 table[a as usize] = b;
32 }
33 let out: Vec<u8> = data.bytes().map(|byte| table[byte as usize]).collect();
34 String::from_utf8(out).map_err(|_| Base32Error::Invalid)
35}
36
37pub fn decode(data: &str, custom_alphabet: Option<&str>) -> Result<String, Base32Error> {
38 let mut data_decode = add_padding(data);
39 if let Some(custom) = custom_alphabet {
40 data_decode = translate_alphabet(&data_decode, custom, ALPHABET)?;
41 }
42 let bytes = BASE32
43 .decode(data_decode.as_bytes())
44 .map_err(|_| Base32Error::Invalid)?;
45 Ok(hex::encode(bytes))
46}
47
48pub fn encode(data: &str, custom_alphabet: Option<&str>) -> Result<String, Base32Error> {
49 let bytes = hex::decode(data)?;
50 let mut b32_encode = BASE32.encode(&bytes);
51 if let Some(custom) = custom_alphabet {
52 b32_encode = translate_alphabet(&b32_encode, ALPHABET, custom)?;
53 }
54 Ok(b32_encode)
55}
56
57pub fn encode_no_padding(data: &str, custom_alphabet: Option<&str>) -> Result<String, Base32Error> {
58 Ok(encode(data, custom_alphabet)?.trim_end_matches('=').to_owned())
59}
60
61#[cfg(test)]
62mod tests {
63 use super::*;
64
65 #[test]
66 fn roundtrip_standard() {
67 let hex_in = "66";
68 let b32 = encode(hex_in, None).unwrap();
69 assert_eq!(b32, "MY======");
70 assert_eq!(decode(&b32, None).unwrap(), hex_in);
71 }
72
73 #[test]
74 fn encode_no_padding_matches() {
75 assert_eq!(encode_no_padding("66", None).unwrap(), "MY");
76 }
77
78 #[test]
79 fn custom_alphabet_roundtrip() {
80 let custom = "ZYXWVUTSRQPONMLKJIHGFEDCBA234567";
81 let hex_in = "deadbeef";
82 let enc = encode(hex_in, Some(custom)).unwrap();
83 let dec = decode(&enc, Some(custom)).unwrap();
84 assert_eq!(dec, hex_in);
85 }
86
87 #[test]
88 fn invalid_base32() {
89 assert!(matches!(decode("!!!!", None), Err(Base32Error::Invalid)));
90 }
91}