File: signer.go

package info (click to toggle)
golang-github-foxboron-go-tpm-keyfiles 0.0~git20241207.04534a2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 216 kB
  • sloc: makefile: 9
file content (75 lines) | stat: -rw-r--r-- 1,701 bytes parent folder | download
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
package keyfile

import (
	"crypto"
	"fmt"
	"io"

	"github.com/google/go-tpm/tpm2"
	"github.com/google/go-tpm/tpm2/transport"
)

// TPMKeySigner implements the crypto.Signer interface for TPMKey
// It allows passing callbacks for TPM, ownerAuth and user auth.
type TPMKeySigner struct {
	key       *TPMKey
	ownerAuth func() ([]byte, error)
	tpm       func() transport.TPMCloser
	auth      func(*TPMKey) ([]byte, error)
}

var _ crypto.Signer = &TPMKeySigner{}

// Returns the crypto.PublicKey
func (t *TPMKeySigner) Public() crypto.PublicKey {
	pk, err := t.key.PublicKey()
	// This shouldn't happen!
	if err != nil {
		panic(fmt.Errorf("failed producing public: %v", err))
	}
	return pk
}

// Sign implementation
func (t *TPMKeySigner) Sign(_ io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error) {
	var digestalg tpm2.TPMAlgID

	auth := []byte("")
	if t.key.HasAuth() {
		p, err := t.auth(t.key)
		if err != nil {
			return nil, err
		}
		auth = p
	}

	switch opts.HashFunc() {
	case crypto.SHA256:
		digestalg = tpm2.TPMAlgSHA256
	case crypto.SHA384:
		digestalg = tpm2.TPMAlgSHA384
	case crypto.SHA512:
		digestalg = tpm2.TPMAlgSHA512
	default:
		return nil, fmt.Errorf("%s is not a supported hashing algorithm", opts.HashFunc())
	}

	ownerauth, err := t.ownerAuth()
	if err != nil {
		return nil, err
	}

	sess := NewTPMSession(t.tpm())
	sess.SetTPM(t.tpm())

	return SignASN1(sess, t.key, ownerauth, auth, digest, digestalg)
}

func NewTPMKeySigner(k *TPMKey, ownerAuth func() ([]byte, error), tpm func() transport.TPMCloser, auth func(*TPMKey) ([]byte, error)) *TPMKeySigner {
	return &TPMKeySigner{
		key:       k,
		ownerAuth: ownerAuth,
		tpm:       tpm,
		auth:      auth,
	}
}