-
Notifications
You must be signed in to change notification settings - Fork 9
/
sha1.go
48 lines (40 loc) · 807 Bytes
/
sha1.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
package infrared
import (
"crypto/sha1"
"fmt"
"hash"
"strings"
)
type Sha1Hash struct {
hash.Hash
}
func NewSha1Hash() Sha1Hash {
return Sha1Hash{
Hash: sha1.New(),
}
}
func (h Sha1Hash) Update(b []byte) {
// This will never return an error like documented in hash.Hash
// so ignoring this error is ok
_, _ = h.Write(b)
}
func (h Sha1Hash) HexDigest() string {
hashBytes := h.Sum(nil)
negative := (hashBytes[0] & 0x80) == 0x80
if negative {
// two's compliment, big endian
carry := true
for i := len(hashBytes) - 1; i >= 0; i-- {
hashBytes[i] = ^hashBytes[i]
if carry {
carry = hashBytes[i] == 0xff
hashBytes[i]++
}
}
}
hashString := strings.TrimLeft(fmt.Sprintf("%x", hashBytes), "0")
if negative {
hashString = "-" + hashString
}
return hashString
}