-
Notifications
You must be signed in to change notification settings - Fork 0
/
digest.go
137 lines (103 loc) · 2.17 KB
/
digest.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
package streebog
import (
"errors"
)
// GOST R 34.11-2012 hash function.
// RFC 6986.
const (
// hash size
Size256 = 32
Size512 = 64
BlockSize = 64
)
// digest represents the partial evaluation of a checksum.
type digest struct {
s [8]uint64
x [BlockSize]byte
nx int
len uint64
S [8]uint64
hs int
}
// newDigest returns a new *digest computing the Streebog checksum
func newDigest(hashsize int) (*digest, error) {
switch hashsize {
case 256, 512:
break
default:
return nil, errors.New("go-hash/streebog: invalid hash size")
}
d := new(digest)
d.hs = hashsize
d.Reset()
return d, nil
}
func (d *digest) Reset() {
d.nx = 0
d.len = 0
// m
d.x = [BlockSize]byte{}
// h
d.s = [8]uint64{}
if d.hs == 512 {
d.s = initIv512
} else {
d.s = initIv256
}
d.S = [8]uint64{}
}
func (d *digest) Size() int {
return d.hs / 8
}
func (d *digest) BlockSize() int {
return BlockSize
}
func (d *digest) Write(p []byte) (nn int, err error) {
nn = len(p)
plen := len(p)
var limit = BlockSize
for d.nx + plen >= limit {
xx := limit - d.nx
copy(d.x[d.nx:], p)
d.transform(false)
plen -= xx
d.len += 512
p = p[xx:]
d.nx = 0
}
copy(d.x[d.nx:], p)
d.nx += plen
return
}
func (d *digest) Sum(in []byte) []byte {
// Make a copy of d so that caller can keep writing and summing.
d0 := *d
hash := d0.checkSum()
return append(in, hash...)
}
func (d *digest) checkSum() []byte {
d.x[d.nx] = 0x01
d.nx++
zeros := [BlockSize]byte{}
copy(d.x[d.nx:], zeros[:])
d.transform(false)
d.len += uint64(d.nx - 1) * 8
copy(d.x[:], zeros[:])
PUTU64(d.x[:], d.len)
d.transform(true)
SS := uint64sToBytes(d.S[:])
copy(d.x[:], SS)
d.transform(true)
ss := uint64sToBytes(d.s[8 - d.hs/BlockSize:])
return ss[:d.hs / 8]
}
func (d *digest) transform(last bool) {
if last {
gN(&d.s, d.x[:], 0)
} else {
gN(&d.s, d.x[:], d.len)
}
if !last {
addm(d.x[:], &d.S)
}
}