Debian Codegraph @

tpm2/policy.go

raw
1 package tpm2
2
3 import (
4 "bytes"
5 "crypto"
6 "reflect"
7 )
8
9 // PolicyCalculator represents a TPM 2.0 policy that needs to be calculated
10 // synthetically (i.e., without a TPM).
11 type PolicyCalculator struct {
12 alg TPMIAlgHash
13 hash crypto.Hash
14 state []byte
15 }
16
17 // NewPolicyCalculator creates a fresh policy using the given hash algorithm.
18 func NewPolicyCalculator(alg TPMIAlgHash) (*PolicyCalculator, error) {
19 hash, err := alg.Hash()
20 if err != nil {
21 return nil, err
22 }
23 return &PolicyCalculator{
24 alg: alg,
25 hash: hash,
26 state: make([]byte, hash.Size()),
27 }, nil
28 }
29
30 // Reset resets the internal state of the policy hash to all 0x00.
31 func (p *PolicyCalculator) Reset() {
32 p.state = make([]byte, p.hash.Size())
33 }
34
35 // Update updates the internal state of the policy hash by appending the
36 // current state with the given contents, and updating the new state to the
37 // hash of that.
38 func (p *PolicyCalculator) Update(data ...interface{}) error {
39 hash := p.hash.New()
40 hash.Write(p.state)
41 var buf bytes.Buffer
42 for _, d := range data {
43 if err := marshal(&buf, reflect.ValueOf(d)); err != nil {
44 return err
45 }
46 }
47 hash.Write(buf.Bytes())
48 p.state = hash.Sum(nil)
49 return nil
50 }
51
52 // Hash returns the current state of the policy hash.
53 func (p *PolicyCalculator) Hash() *TPMTHA {
54 result := TPMTHA{
55 HashAlg: p.alg,
56 Digest: make([]byte, len(p.state)),
57 }
58 copy(result.Digest, p.state)
59 return &result
60 }