47 lines
810 B
Go
47 lines
810 B
Go
|
package main
|
||
|
|
||
|
import (
|
||
|
"crypto/sha1"
|
||
|
"encoding/hex"
|
||
|
"fmt"
|
||
|
"strings"
|
||
|
)
|
||
|
|
||
|
func digest(secret, publicKey []byte) (string, error) {
|
||
|
hash, err := func() (hash []byte, err error) {
|
||
|
h := sha1.New()
|
||
|
_, err = h.Write(secret)
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
_, err = h.Write(publicKey)
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
return h.Sum(nil), nil
|
||
|
}()
|
||
|
if err != nil {
|
||
|
return "", fmt.Errorf("error writing sha1: %v", err)
|
||
|
}
|
||
|
|
||
|
var s strings.Builder
|
||
|
if (hash[0] & 0x80) == 0x80 {
|
||
|
hash = twosComplement(hash)
|
||
|
s.WriteRune('-')
|
||
|
}
|
||
|
s.WriteString(strings.TrimLeft(hex.EncodeToString(hash), "0"))
|
||
|
return s.String(), nil
|
||
|
}
|
||
|
|
||
|
func twosComplement(p []byte) []byte {
|
||
|
carry := true
|
||
|
for i := len(p) - 1; i >= 0; i-- {
|
||
|
p[i] = ^p[i]
|
||
|
if carry {
|
||
|
carry = p[i] == 0xff
|
||
|
p[i]++
|
||
|
}
|
||
|
}
|
||
|
return p
|
||
|
}
|