Debian Codegraph @

tpm2/child_object_crypto.go

raw
1 package tpm2
2
3 import (
4 "crypto/aes"
5 "crypto/cipher"
6 "crypto/hmac"
7 "errors"
8 "fmt"
9 )
10
11 var (
12 labelStorage = "STORAGE"
13 labelIntegrity = "INTEGRITY"
14
15 ErrUnsupportedCipher = errors.New("unsupported block cipher")
16 ErrUnsupportedMode = errors.New("unsupported block cipher mode of operation")
17 )
18
19 // deriveAndEncrypt derives a symmetric key and uses it to encrypt the plaintext.
20 func deriveAndEncrypt(pub LabeledEncapsulationKey, seed []byte, context []byte, plaintext []byte) ([]byte, error) {
21 // Only AES is supported.
22 if pub.SymmetricParameters().Algorithm != TPMAlgAES {
23 return nil, fmt.Errorf("%w %v", ErrUnsupportedCipher, pub.SymmetricParameters().Algorithm)
24 }
25 mode, err := pub.SymmetricParameters().Mode.AES()
26 if err != nil {
27 return nil, err
28 }
29 if *mode != TPMAlgCFB {
30 return nil, fmt.Errorf("%w %v", ErrUnsupportedMode, *mode)
31 }
32 bits, err := pub.SymmetricParameters().KeyBits.AES()
33 if err != nil {
34 return nil, err
35 }
36
37 hash, err := pub.NameAlg().Hash()
38 if err != nil {
39 return nil, err
40 }
41 key, err := aes.NewCipher(KDFa(hash, seed, labelStorage, context, nil, int(*bits)))
42 if err != nil {
43 return nil, err
44 }
45 ciphertext := make([]byte, len(plaintext))
46 cipher.NewCFBEncrypter(key, make([]byte, key.BlockSize())).XORKeyStream(ciphertext, plaintext)
47 return ciphertext, nil
48 }
49
50 // deriveAndHMAC derives an HMAC key and uses it to HMAC the data, which can be provided in multiple chunks.
51 func deriveAndHMAC(pub LabeledEncapsulationKey, seed []byte, data ...[]byte) ([]byte, error) {
52 hash, err := pub.NameAlg().Hash()
53 if err != nil {
54 return nil, err
55 }
56 key := KDFa(hash, seed, labelIntegrity, nil, nil, hash.Size()*8)
57 hmac := hmac.New(hash.New, key)
58 for _, data := range data {
59 hmac.Write(data)
60 }
61 return hmac.Sum(nil), nil
62 }