-
Notifications
You must be signed in to change notification settings - Fork 0
/
tpm_encrypt.go
103 lines (88 loc) · 2.16 KB
/
tpm_encrypt.go
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
93
94
95
96
97
98
99
100
101
102
103
package tpm
import (
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"fmt"
"hash"
"github.com/folbricht/tpmk"
"github.com/pkg/errors"
)
// DecryptBlob decrypts a blob using a key stored in the TPM
func DecryptBlob(blob []byte, opts ...TPMOption) ([]byte, error) {
o, err := DefaultTPMOption(opts...)
if err != nil {
return []byte{}, err
}
// Open device or simulator
dev, err := getTPMDevice(o)
if err != nil {
return []byte{}, err
}
if !o.emulated {
defer dev.Close()
}
private, err := tpmk.NewRSAPrivateKey(dev, o.index, o.password)
if err != nil {
return []byte{}, fmt.Errorf("loading private key: '%w'", err)
}
return private.Decrypt(rand.Reader, blob, &rsa.OAEPOptions{Hash: o.hash})
}
func EncryptBlob(blob []byte, opts ...TPMOption) ([]byte, error) {
o, err := DefaultTPMOption(opts...)
if err != nil {
return []byte{}, err
}
// Open device or simulator
dev, err := getTPMDevice(o)
if err != nil {
return []byte{}, err
}
if !o.emulated {
defer dev.Close()
}
// Get a list of keys
keys, err := tpmk.KeyList(dev)
if err != nil {
return []byte{}, errors.Wrap(err, "reading key list")
}
exists := false
// Print the key handles in hex notation
for _, hh := range keys {
if o.index == hh {
exists = true
}
}
var pub crypto.PublicKey
if !exists {
// Generate the key if doesn't exist
pub, err = tpmk.GenRSAPrimaryKey(dev, o.index, "", o.password, o.keyAttr)
if err != nil {
return []byte{}, err
}
} else {
// Re-Use the private key in the TPM
private, err := tpmk.NewRSAPrivateKey(dev, o.index, o.password)
if err != nil {
return []byte{}, err
}
pub = private.Public()
}
p, ok := pub.(*rsa.PublicKey)
if !ok {
return nil, fmt.Errorf("keypair returned by TPM is malformed: pubkey is not an RSA public key")
}
return encryptWithPublicKey(blob, p, o.hash)
}
// encryptWithPublicKey encrypts data with public key
func encryptWithPublicKey(msg []byte, pub *rsa.PublicKey, c crypto.Hash) ([]byte, error) {
var h hash.Hash
switch c {
case crypto.SHA256:
h = sha256.New()
default:
return []byte{}, fmt.Errorf("unsupported encryption type")
}
return rsa.EncryptOAEP(h, rand.Reader, pub, msg, nil)
}