-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathBitcoinCashBase32.java
74 lines (59 loc) · 1.77 KB
/
BitcoinCashBase32.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package main;
import java.util.HashMap;
import java.util.Map;
/**
* Copyright (c) 2018 Tobias Brandt
*
* Distributed under the MIT software license, see the accompanying file LICENSE
* or http://www.opensource.org/licenses/mit-license.php.
*/
public class BitcoinCashBase32 {
public static final String CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l";
private static final char[] CHARS = CHARSET.toCharArray();
private static Map<Character, Integer> charPositionMap;
static {
charPositionMap = new HashMap<>();
for (int i = 0; i < CHARS.length; i++) {
charPositionMap.put(CHARS[i], i);
}
if (charPositionMap.size() != 32) {
throw new RuntimeException("The charset must contain 32 unique characters.");
}
}
/**
* Encode a byte array as base32 string. This method assumes that all bytes
* are only from 0-31
*
* @param byteArray
* @return
*/
public static String encode(byte[] byteArray) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < byteArray.length; i++) {
int val = (int) byteArray[i];
if (val < 0 || val > 31) {
throw new RuntimeException("This method assumes that all bytes are only from 0-31. Was: " + val);
}
sb.append(CHARS[val]);
}
return sb.toString();
}
/**
* Decode a base32 string back to the byte array representation
*
* @param base32String
* @return
*/
public static byte[] decode(String base32String) {
byte[] bytes = new byte[base32String.length()];
char[] charArray = base32String.toCharArray();
for (int i = 0; i < charArray.length; i++) {
Integer position = charPositionMap.get(charArray[i]);
if (position == null) {
throw new RuntimeException("There seems to be an invalid char: " + charArray[i]);
}
bytes[i] = (byte) ((int) position);
}
return bytes;
}
}