-
Notifications
You must be signed in to change notification settings - Fork 3
/
base58.go
executable file
·101 lines (79 loc) · 2.1 KB
/
base58.go
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package main
import (
"bytes"
"math/big"
"errors"
)
var b58Alphabet = []byte("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")
const alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
// Base58Encode encodes a byte array to Base58
func Base58Encode(input []byte) []byte {
var result []byte
x := big.NewInt(0).SetBytes(input)
base := big.NewInt(int64(len(b58Alphabet)))
zero := big.NewInt(0)
mod := &big.Int{}
for x.Cmp(zero) != 0 {
x.DivMod(x, base, mod)
result = append(result, b58Alphabet[mod.Int64()])
}
ReverseBytes(result)
for b := range input {
if b == 0x00 {
result = append([]byte{b58Alphabet[0]}, result...)
} else {
break
}
}
return result
}
// Base58Decode decodes Base58-encoded data
func Base58Decode(input []byte) []byte {
result := big.NewInt(0)
zeroBytes := 0
for b := range input {
if b == 0x00 {
zeroBytes++
}
}
payload := input[zeroBytes:]
for _, b := range payload {
charIndex := bytes.IndexByte(b58Alphabet, b)
result.Mul(result, big.NewInt(58))
result.Add(result, big.NewInt(int64(charIndex)))
}
decoded := result.Bytes()
decoded = append(bytes.Repeat([]byte{byte(0x00)}, zeroBytes), decoded...)
return decoded
}
func ReverseBytes(data []byte) {
for i, j := 0, len(data)-1; i < j; i, j = i+1, j-1 {
data[i], data[j] = data[j], data[i]
}
}
func Bb58encode(data []byte) string {
var encoded string
decimalData := new(big.Int)
decimalData.SetBytes(data)
divisor, zero := big.NewInt(58), big.NewInt(0)
for decimalData.Cmp(zero) > 0 {
mod := new(big.Int)
decimalData.DivMod(decimalData, divisor, mod)
encoded = string(alphabet[mod.Int64()]) + encoded
}
return encoded
}
func Bb58decode(data string) ([]byte, error) {
decimalData := new(big.Int)
alphabetBytes := []byte(alphabet)
multiplier := big.NewInt(58)
for _, value := range data {
pos := bytes.IndexByte(alphabetBytes, byte(value))
if pos == -1 {
return nil, errors.New("Character not found in alphabet")
}
decimalData.Mul(decimalData, multiplier)
decimalData.Add(decimalData, big.NewInt(int64(pos)))
}
return decimalData.Bytes(), nil
}