github.com/chain5j/chain5j-pkg@v1.0.7/crypto/base/base58/base58.go (about) 1 // Package base58 2 // 3 // @author: xwc1125 4 package base58 5 6 import ( 7 "bytes" 8 "math/big" 9 ) 10 11 var b58Alphabet = []byte("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz") 12 13 // Encode encodes a byte array to Base58 14 func Encode(input []byte) []byte { 15 var result []byte 16 17 x := big.NewInt(0).SetBytes(input) 18 19 base := big.NewInt(int64(len(b58Alphabet))) 20 zero := big.NewInt(0) 21 mod := &big.Int{} 22 23 for x.Cmp(zero) != 0 { 24 x.DivMod(x, base, mod) 25 result = append(result, b58Alphabet[mod.Int64()]) 26 } 27 28 // https://en.bitcoin.it/wiki/Base58Check_encoding#Version_bytes 29 if input[0] == 0x00 { 30 result = append(result, b58Alphabet[0]) 31 } 32 33 reverseBytes(result) 34 35 return result 36 } 37 38 // Decode decodes Base58-encoded data 39 func Decode(input []byte) []byte { 40 result := big.NewInt(0) 41 42 for _, b := range input { 43 charIndex := bytes.IndexByte(b58Alphabet, b) 44 result.Mul(result, big.NewInt(58)) 45 result.Add(result, big.NewInt(int64(charIndex))) 46 } 47 48 decoded := result.Bytes() 49 50 if input[0] == b58Alphabet[0] { 51 decoded = append([]byte{0x00}, decoded...) 52 } 53 54 return decoded 55 } 56 57 // ReverseBytes reverses a byte array 58 func reverseBytes(data []byte) { 59 for i, j := 0, len(data)-1; i < j; i, j = i+1, j-1 { 60 data[i], data[j] = data[j], data[i] 61 } 62 }