Debian Codegraph @

pkclient/pkclient.go

raw
1 package pkclient
2
3 import (
4 "crypto/ecdsa"
5 "crypto/x509"
6 "fmt"
7 "io"
8 "strconv"
9
10 "github.com/stefanberger/go-pkcs11uri"
11 )
12
13 type Client interface {
14 io.Closer
15 GetPubKey() ([]byte, error)
16 DeriveNoise(peerPubKey []byte) ([]byte, error)
17 Test() error
18 }
19
20 const NoiseKeySize = 32
21
22 func FromUrl(pkurl string) (*PKClient, error) {
23 uri := pkcs11uri.New()
24 uri.SetAllowAnyModule(true) //todo
25 err := uri.Parse(pkurl)
26 if err != nil {
27 return nil, err
28 }
29
30 module, err := uri.GetModule()
31 if err != nil {
32 return nil, err
33 }
34
35 slotid := 0
36 slot, ok := uri.GetPathAttribute("slot-id", false)
37 if !ok {
38 slotid = 0
39 } else {
40 slotid, err = strconv.Atoi(slot)
41 if err != nil {
42 return nil, err
43 }
44 }
45
46 pin, _ := uri.GetPIN()
47 id, _ := uri.GetPathAttribute("id", false)
48 label, _ := uri.GetPathAttribute("object", false)
49
50 return New(module, uint(slotid), pin, id, label)
51 }
52
53 func ecKeyToArray(key *ecdsa.PublicKey) []byte {
54 x := make([]byte, 32)
55 y := make([]byte, 32)
56 key.X.FillBytes(x)
57 key.Y.FillBytes(y)
58 return append([]byte{0x04}, append(x, y...)...)
59 }
60
61 func formatPubkeyFromPublicKeyInfoAttr(d []byte) ([]byte, error) {
62 e, err := x509.ParsePKIXPublicKey(d)
63 if err != nil {
64 return nil, err
65 }
66 switch t := e.(type) {
67 case *ecdsa.PublicKey:
68 return ecKeyToArray(e.(*ecdsa.PublicKey)), nil
69 default:
70 return nil, fmt.Errorf("unknown public key type: %T", t)
71 }
72 }
73
74 func (c *PKClient) Test() error {
75 pub, err := c.GetPubKey()
76 if err != nil {
77 return fmt.Errorf("failed to get public key: %w", err)
78 }
79 out, err := c.DeriveNoise(pub) //do an ECDH with ourselves as a quick test
80 if err != nil {
81 return err
82 }
83 if len(out) != NoiseKeySize {
84 return fmt.Errorf("got a key of %d bytes, expected %d", len(out), NoiseKeySize)
85 }
86 return nil
87 }