• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright (c) 2016, Google Inc.
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 runner
16
17import (
18	"crypto/hmac"
19	"hash"
20)
21
22// hkdfExtract implements HKDF-Extract from RFC 5869.
23func hkdfExtract(hash func() hash.Hash, salt, ikm []byte) []byte {
24	if salt == nil {
25		salt = make([]byte, hash().Size())
26	}
27	hmac := hmac.New(hash, salt)
28	hmac.Write(ikm)
29	return hmac.Sum(nil)
30}
31
32// hkdfExpand implements HKDF-Expand from RFC 5869.
33func hkdfExpand(hash func() hash.Hash, prk, info []byte, length int) []byte {
34	hashSize := hash().Size()
35	if length > 255*hashSize {
36		panic("hkdfExpand: length too long")
37	}
38	if len(prk) < hashSize {
39		panic("hkdfExpand: prk too short")
40	}
41	var lastBlock []byte
42	counter := byte(0)
43	okm := make([]byte, length)
44	hmac := hmac.New(hash, prk)
45	for length > 0 {
46		hmac.Reset()
47		counter++
48		hmac.Write(lastBlock)
49		hmac.Write(info)
50		hmac.Write([]byte{counter})
51		block := hmac.Sum(nil)
52		lastBlock = block
53		copy(okm[(int(counter)-1)*hashSize:], block)
54		length -= hashSize
55	}
56	return okm
57}
58