-
Notifications
You must be signed in to change notification settings - Fork 0
/
key_ecdh.go
91 lines (74 loc) · 2.07 KB
/
key_ecdh.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
// SPDX-FileCopyrightText: 2023-2024 Steffen Vogel <[email protected]>
// SPDX-License-Identifier: Apache-2.0
package openpgp
import (
"crypto"
"crypto/ecdh"
"crypto/sha1" //nolint:gosec
"encoding/binary"
"fmt"
"time"
iso "cunicu.li/go-iso7816"
"cunicu.li/go-iso7816/encoding/tlv"
)
type PrivateKeyECDH struct {
card *Card
curve Curve
key KeyRef
public *ecdh.PublicKey
}
func (k *PrivateKeyECDH) Public() crypto.PublicKey {
return k.public
}
// ECDH performs a Diffie-Hellman key agreement with the peer
// to produce a shared secret key.
//
// See: OpenPGP Smart Card Application - Section 7.2.11 PSO: DECIPHER
func (k *PrivateKeyECDH) ECDH(peer *ecdh.PublicKey) ([]byte, error) {
if peer.Curve() != k.curve.ECDH() {
return nil, ErrMismatchingAlgorithms
}
data, err := tlv.EncodeBER(
tlv.New(tagCipher,
tlv.New(tagPublicKey,
tlv.New(tagExternalPublicKey, peer.Bytes()),
),
),
)
if err != nil {
return nil, err
}
return send(k.card.tx, iso.InsPerformSecurityOperation, 0x80, 0x86, data)
}
func (k PrivateKeyECDH) fingerprint(creationTime time.Time) []byte {
buf := []byte{
0x99, // Prefix
0, 0, // Packet length
0x04, // Version
0, 0, 0, 0, // Creation timestamp
byte(AlgPubkeyECDH),
}
buf = append(buf, k.curve.OID()...)
buf = appendBytesMPI(buf, k.public.Bytes())
buf = appendKDF(buf, AlgHashSHA512, AlgSymAES256) // same default values as Sequoia
binary.BigEndian.PutUint16(buf[1:], uint16(len(buf)-3)) // Fill in packet length
binary.BigEndian.PutUint32(buf[4:], uint32(creationTime.Unix())) // Fill in generation timestamp
digest := sha1.New() //nolint:gosec
digest.Write(buf)
return digest.Sum(nil)
}
func decodePublicECDH(tvs tlv.TagValues, curve Curve) (*ecdh.PublicKey, error) {
_, tvs, ok := tvs.Get(tagPublicKey)
if !ok {
return nil, fmt.Errorf("%w: public key", errMissingTag)
}
p, _, ok := tvs.Get(tagPublicKeyEC)
if !ok {
return nil, fmt.Errorf("%w: points", errMissingTag)
}
curveECDH := curve.ECDH()
if curveECDH == nil {
return nil, ErrUnsupportedCurve
}
return curveECDH.NewPublicKey(p)
}