summaryrefslogtreecommitdiff
path: root/vendor/github.com/pion/stun/internal/hmac/pool.go
blob: 4db61e540080d312ad9a68b29c444d72a2bfee54 (plain)
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
package hmac

import (
	"crypto/sha1"
	"crypto/sha256"
	"hash"
	"sync"
)

// setZeroes sets all bytes from b to zeroes.
//
// See https://github.com/golang/go/issues/5373
func setZeroes(b []byte) {
	for i := range b {
		b[i] = 0
	}
}

func (h *hmac) resetTo(key []byte) {
	h.outer.Reset()
	h.inner.Reset()
	setZeroes(h.ipad)
	setZeroes(h.opad)
	if len(key) > h.blocksize {
		// If key is too big, hash it.
		h.outer.Write(key)
		key = h.outer.Sum(nil)
	}
	copy(h.ipad, key)
	copy(h.opad, key)
	for i := range h.ipad {
		h.ipad[i] ^= 0x36
	}
	for i := range h.opad {
		h.opad[i] ^= 0x5c
	}
	h.inner.Write(h.ipad)
}

var hmacSHA1Pool = &sync.Pool{
	New: func() interface{} {
		h := New(sha1.New, make([]byte, sha1.BlockSize))
		return h
	},
}

// AcquireSHA1 returns new HMAC from pool.
func AcquireSHA1(key []byte) hash.Hash {
	h := hmacSHA1Pool.Get().(*hmac)
	assertHMACSize(h, sha1.Size, sha1.BlockSize)
	h.resetTo(key)
	return h
}

// PutSHA1 puts h to pool.
func PutSHA1(h hash.Hash) {
	hm := h.(*hmac)
	assertHMACSize(hm, sha1.Size, sha1.BlockSize)
	hmacSHA1Pool.Put(hm)
}

var hmacSHA256Pool = &sync.Pool{
	New: func() interface{} {
		h := New(sha256.New, make([]byte, sha256.BlockSize))
		return h
	},
}

// AcquireSHA256 returns new HMAC from SHA256 pool.
func AcquireSHA256(key []byte) hash.Hash {
	h := hmacSHA256Pool.Get().(*hmac)
	assertHMACSize(h, sha256.Size, sha256.BlockSize)
	h.resetTo(key)
	return h
}

// PutSHA256 puts h to SHA256 pool.
func PutSHA256(h hash.Hash) {
	hm := h.(*hmac)
	assertHMACSize(hm, sha256.Size, sha256.BlockSize)
	hmacSHA256Pool.Put(hm)
}

// assertHMACSize panics if h.size != size or h.blocksize != blocksize.
//
// Put and Acquire functions are internal functions to project, so
// checking it via such assert is optimal.
func assertHMACSize(h *hmac, size, blocksize int) {
	if h.size != size || h.blocksize != blocksize {
		panic("BUG: hmac size invalid") // nolint
	}
}