Skip to content

Instantly share code, notes, and snippets.

@debuggor
Created August 9, 2020 09:15
Show Gist options
  • Save debuggor/04d67089c78a644921c5a975936401fa to your computer and use it in GitHub Desktop.
Save debuggor/04d67089c78a644921c5a975936401fa to your computer and use it in GitHub Desktop.
import java.math.BigInteger;
import java.util.Arrays;
/**
* @Author:yong.huang
* @Date:2020-08-09 15:48
*/
public class Base58 {
private static final char[] ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".toCharArray();
private static int[] INDEXS = new int[128];
static {
Arrays.fill(INDEXS, -1);
for (int i = 0; i < ALPHABET.length; i++) {
INDEXS[ALPHABET[i]] = i;
}
}
/**
* 辗转相除
*
* @param input
* @return
*/
public static String encode(byte[] input) {
char[] encoded = new char[input.length * 2];
BigInteger x = new BigInteger(input);
BigInteger base = BigInteger.valueOf(ALPHABET.length);
BigInteger mod;
int index = 0;
while (x.compareTo(BigInteger.ZERO) > 0) {
mod = x.mod(base);
x = x.divide(base);
encoded[index++] = ALPHABET[mod.intValue()];
}
// https://en.bitcoin.it/wiki/Base58Check_encoding#Version_bytes
if (input[0] == 0x00) {
encoded[index++] = ALPHABET[0];
}
// reverse
for (int i = 0; i < index / 2; i++) {
char tmp = encoded[i];
encoded[i] = encoded[index - 1 - i];
encoded[index - 1 - i] = tmp;
}
return new String(encoded, 0, index);
}
public static byte[] decode(String message) {
BigInteger x = BigInteger.ZERO;
BigInteger base = BigInteger.valueOf(ALPHABET.length);
for (int i = 0; i < message.length(); i++) {
char c = message.charAt(i);
int digit = INDEXS[c];
x = x.multiply(base).add(BigInteger.valueOf(digit));
}
byte[] out = x.toByteArray();
if (message.charAt(0) == ALPHABET[0]) {
byte[] tmp = new byte[out.length + 1];
tmp[0] = 0x00;
System.arraycopy(out, 0, tmp, 1, out.length);
out = tmp;
}
return out;
}
public static void main(String[] args) {
String address = "1CtymYoZEknYgehNT4vdDXedPY3GfPR5by";
byte[] decode = decode(address);
String encode = encode(decode);
System.out.println(encode);
}
}
@debuggor
Copy link
Author

debuggor commented Aug 9, 2020

base58

辗转相除;余数做下标到ALPHABET表中取对应的字母;

不使用数字 "0",字母大写"O",字母大写 "I",和字母小写 "l",以及 "+" 和 "/" 符号

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment