-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcrc24.go
64 lines (53 loc) · 911 Bytes
/
crc24.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
// Package crc24 implements OpenPGP RFC4880 CRC-24
package crc24
import "hash"
const (
initial = 0x0b704ce
polynom = 0x1864cfb
)
type digest struct {
sum uint32
}
func (d *digest) Write(p []byte) (n int, err error) {
for _, v := range p {
d.sum ^= uint32(v) << 16
for i := 0; i < 8; i++ {
d.sum <<= 1
if d.sum&0x1000000 != 0 {
d.sum ^= polynom
}
}
}
return len(p), nil
}
func (d *digest) Sum(b []byte) []byte {
v := d.Sum32()
for i := d.Size() - 1; i >= 0; i-- {
b = append(b, byte(v>>uint(8*i)))
}
return b
}
func (d *digest) Reset() {
d.sum = initial
}
func (d *digest) Size() int {
return 4
}
func (d *digest) BlockSize() int {
return 1
}
func (d *digest) Sum32() uint32 {
return d.sum & 0xffffff
}
// New hash32
func New() hash.Hash32 {
d := &digest{}
d.Reset()
return d
}
// Sum bytes
func Sum(b []byte) uint32 {
d := New()
d.Write(b)
return d.Sum32()
}