github.com/yaling888/clash@v1.53.0/common/encoding/base58/base58check.go (about)

     1  package base58
     2  
     3  import (
     4  	"crypto/sha256"
     5  	"errors"
     6  )
     7  
     8  // ErrChecksum indicates that the checksum of a check-encoded string does not verify against
     9  // the checksum.
    10  var ErrChecksum = errors.New("checksum error")
    11  
    12  // ErrInvalidFormat indicates that the check-encoded string has an invalid format.
    13  var ErrInvalidFormat = errors.New("invalid format: version and/or checksum bytes missing")
    14  
    15  // checksum: first four bytes of sha256^2
    16  func checksum(input []byte) (cksum [4]byte) {
    17  	h := sha256.Sum256(input)
    18  	h2 := sha256.Sum256(h[:])
    19  	copy(cksum[:], h2[:4])
    20  	return
    21  }
    22  
    23  // CheckEncode prepends a version byte and appends a four byte checksum.
    24  func CheckEncode(input []byte, version byte) string {
    25  	b := make([]byte, 0, 1+len(input)+4)
    26  	b = append(b, version)
    27  	b = append(b, input...)
    28  	cksum := checksum(b)
    29  	b = append(b, cksum[:]...)
    30  	return Encode(b)
    31  }
    32  
    33  // CheckDecode decodes a string that was encoded with CheckEncode and verifies the checksum.
    34  func CheckDecode(input string) (result []byte, version byte, err error) {
    35  	decoded := Decode(input)
    36  	if len(decoded) < 5 {
    37  		return nil, 0, ErrInvalidFormat
    38  	}
    39  	version = decoded[0]
    40  	var cksum [4]byte
    41  	copy(cksum[:], decoded[len(decoded)-4:])
    42  	if checksum(decoded[:len(decoded)-4]) != cksum {
    43  		return nil, 0, ErrChecksum
    44  	}
    45  	payload := decoded[1 : len(decoded)-4]
    46  	result = append(result, payload...)
    47  	return
    48  }