• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright 2021 The BoringSSL Authors
2//
3// Permission to use, copy, modify, and/or distribute this software for any
4// purpose with or without fee is hereby granted, provided that the above
5// copyright notice and this permission notice appear in all copies.
6//
7// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
14
15package main
16
17import (
18	"crypto/hmac"
19	"crypto/sha256"
20)
21
22// See SP 800-90Ar1, section 10.1.2
23type HMACDRBGSHA256 struct {
24	k, v [32]byte
25}
26
27func NewHMACDRBG(entropy, nonce, personalisation []byte) *HMACDRBGSHA256 {
28	ret := new(HMACDRBGSHA256)
29	ret.init(entropy, nonce, personalisation)
30	return ret
31}
32
33func (drbg *HMACDRBGSHA256) init(entropy, nonce, personalisation []byte) {
34	for i := range drbg.k {
35		drbg.k[i] = 0
36	}
37	for i := range drbg.v {
38		drbg.v[i] = 1
39	}
40
41	seed := make([]byte, 0, len(entropy)+len(nonce)+len(personalisation))
42	seed = append(seed, entropy...)
43	seed = append(seed, nonce...)
44	seed = append(seed, personalisation...)
45	drbg.update(seed)
46}
47
48func (drbg *HMACDRBGSHA256) update(data []byte) {
49	buf := make([]byte, 0, len(drbg.v)+1+len(data))
50	buf = append(buf, drbg.v[:]...)
51	buf = append(buf, 0)
52	buf = append(buf, data...)
53
54	mac := hmac.New(sha256.New, drbg.k[:])
55	mac.Write(buf)
56	mac.Sum(drbg.k[:0])
57
58	mac = hmac.New(sha256.New, drbg.k[:])
59	mac.Write(drbg.v[:])
60	mac.Sum(drbg.v[:0])
61
62	if len(data) > 0 {
63		copy(buf, drbg.v[:])
64		buf[len(drbg.v)] = 1
65
66		mac = hmac.New(sha256.New, drbg.k[:])
67		mac.Write(buf)
68		mac.Sum(drbg.k[:0])
69
70		mac = hmac.New(sha256.New, drbg.k[:])
71		mac.Write(drbg.v[:])
72		mac.Sum(drbg.v[:0])
73	}
74}
75
76func (drbg *HMACDRBGSHA256) Reseed(entropy, additionalInput []byte) {
77	buf := make([]byte, 0, len(entropy)+len(additionalInput))
78	buf = append(buf, entropy...)
79	buf = append(buf, additionalInput...)
80	drbg.update(buf)
81}
82
83func (drbg *HMACDRBGSHA256) Generate(out []byte, additionalInput []byte) {
84	if len(additionalInput) > 0 {
85		drbg.update(additionalInput)
86	}
87
88	done := 0
89	for done < len(out) {
90		mac := hmac.New(sha256.New, drbg.k[:])
91		mac.Write(drbg.v[:])
92		mac.Sum(drbg.v[:0])
93
94		done += copy(out[done:], drbg.v[:])
95	}
96
97	drbg.update(additionalInput)
98}
99