Debian Codegraph @

siphash/siphash.go

raw symbols SCIP
1 // Use of this source code is governed by a license
2 // that can be found in the LICENSE file.
3
4 // Package siphash implements a hash / MAC function
5 // developed Jean-Philippe Aumasson and Daniel J Bernstein
6 // in 2012. SipHash computes 64-bit message authentication
7 // code from a variable-length message and a 128-bit secret
8 // key. It was designed to be efficient even for short inputs,
9 // with performance comparable to non-cryptographic hash
10 // functions. This package implements SipHash with the
11 // recommended parameters: c = 2 and d = 4.
12 package siphash
13
14 import "crypto/subtle"
15
16 // The size of the SipHash authentication tag in bytes.
17 const TagSize = 8
18
19 // The four initialization constants
20 const (
21 c0 = uint64(0x736f6d6570736575)
22 c1 = uint64(0x646f72616e646f6d)
23 c2 = uint64(0x6c7967656e657261)
24 c3 = uint64(0x7465646279746573)
25 )
26
27 // Verify checks whether the given sum is equal to the
28 // computed checksum of msg. This function returns true
29 // if and only if the computed checksum is equal to the
30 // given sum.
31 func Verify(sum *[TagSize]byte, msg []byte, key *[16]byte) bool {
32 var out [TagSize]byte
33 Sum(&out, msg, key)
34 return subtle.ConstantTimeCompare(sum[:], out[:]) == 1
35 }
36
37 // The siphash hash struct implementing hash.Hash
38 type hashFunc struct {
39 hVal [4]uint64
40 key [2]uint64
41 block [TagSize]byte
42 off int
43 ctr byte
44 }
45
46 func (h *hashFunc) BlockSize() int { return TagSize }
47
48 func (h *hashFunc) Size() int { return TagSize }
49
50 func (h *hashFunc) Reset() {
51 h.hVal[0] = h.key[0] ^ c0
52 h.hVal[1] = h.key[1] ^ c1
53 h.hVal[2] = h.key[0] ^ c2
54 h.hVal[3] = h.key[1] ^ c3
55
56 h.off = 0
57 h.ctr = 0
58 }
59
60 func (h *hashFunc) Write(p []byte) (int, error) {
61 n := len(p)
62 h.ctr += byte(n)
63
64 if h.off > 0 {
65 dif := TagSize - h.off
66 if n > dif {
67 h.off += copy(h.block[h.off:], p[:dif])
68 p = p[dif:]
69 core(&(h.hVal), h.block[:])
70 h.off = 0
71 } else {
72 h.off += copy(h.block[h.off:], p)
73 return n, nil
74 }
75 }
76
77 if nn := len(p); nn >= TagSize {
78 nn &= (^(TagSize - 1))
79 core(&(h.hVal), p[:nn])
80 p = p[nn:]
81 }
82
83 if len(p) > 0 {
84 h.off = copy(h.block[:], p)
85 }
86 return n, nil
87 }
88
89 func (h *hashFunc) Sum64() uint64 {
90 hVal := h.hVal
91 block := h.block
92 for i := h.off; i < TagSize-1; i++ {
93 block[i] = 0
94 }
95 block[7] = h.ctr
96 return finalize(&hVal, &block)
97 }
98
99 func (h *hashFunc) Sum(b []byte) []byte {
100 r := h.Sum64()
101
102 var out [TagSize]byte
103 out[0] = byte(r)
104 out[1] = byte(r >> 8)
105 out[2] = byte(r >> 16)
106 out[3] = byte(r >> 24)
107 out[4] = byte(r >> 32)
108 out[5] = byte(r >> 40)
109 out[6] = byte(r >> 48)
110 out[7] = byte(r >> 56)
111 return append(b, out[:]...)
112 }