Debian Codegraph @

openpgp/packet/public_key.go

raw
1 // Copyright 2011 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package packet
6
7 import (
8 "crypto/dsa"
9 "crypto/rsa"
10 "crypto/sha1"
11 "crypto/sha256"
12 _ "crypto/sha512"
13 "encoding/binary"
14 goerrors "errors"
15 "fmt"
16 "hash"
17 "io"
18 "math/big"
19 "strconv"
20 "time"
21
22 "github.com/ProtonMail/go-crypto/openpgp/ecdh"
23 "github.com/ProtonMail/go-crypto/openpgp/ecdsa"
24 "github.com/ProtonMail/go-crypto/openpgp/ed25519"
25 "github.com/ProtonMail/go-crypto/openpgp/ed448"
26 "github.com/ProtonMail/go-crypto/openpgp/eddsa"
27 "github.com/ProtonMail/go-crypto/openpgp/elgamal"
28 "github.com/ProtonMail/go-crypto/openpgp/errors"
29 "github.com/ProtonMail/go-crypto/openpgp/internal/algorithm"
30 "github.com/ProtonMail/go-crypto/openpgp/internal/ecc"
31 "github.com/ProtonMail/go-crypto/openpgp/internal/encoding"
32 "github.com/ProtonMail/go-crypto/openpgp/mldsa_eddsa"
33 "github.com/ProtonMail/go-crypto/openpgp/mlkem_ecdh"
34 "github.com/ProtonMail/go-crypto/openpgp/slhdsa"
35 "github.com/ProtonMail/go-crypto/openpgp/x25519"
36 "github.com/ProtonMail/go-crypto/openpgp/x448"
37 "github.com/cloudflare/circl/kem"
38 "github.com/cloudflare/circl/kem/mlkem/mlkem1024"
39 "github.com/cloudflare/circl/kem/mlkem/mlkem768"
40 "github.com/cloudflare/circl/sign"
41 "github.com/cloudflare/circl/sign/mldsa/mldsa65"
42 "github.com/cloudflare/circl/sign/mldsa/mldsa87"
43 slhdsaCircl "github.com/cloudflare/circl/sign/slhdsa"
44 )
45
46 // PublicKey represents an OpenPGP public key. See RFC 4880, section 5.5.2.
47 type PublicKey struct {
48 Version int
49 CreationTime time.Time
50 PubKeyAlgo PublicKeyAlgorithm
51 PublicKey interface{} // *rsa.PublicKey, *dsa.PublicKey, *ecdsa.PublicKey or *eddsa.PublicKey, *x25519.PublicKey, *x448.PublicKey, *ed25519.PublicKey, *ed448.PublicKey, or *mlkem_ecdh.PublicKey
52 Fingerprint []byte
53 KeyId uint64
54 IsSubkey bool
55
56 // RFC 4880 fields
57 n, e, p, q, g, y encoding.Field
58
59 // RFC 6637 fields
60 // oid contains the OID byte sequence identifying the elliptic curve used
61 oid encoding.Field
62
63 // kdf stores key derivation function parameters
64 // used for ECDH encryption. See RFC 6637, Section 9.
65 kdf encoding.Field
66 }
67
68 // UpgradeToV5 updates the version of the key to v5, and updates all necessary
69 // fields.
70 func (pk *PublicKey) UpgradeToV5() {
71 pk.Version = 5
72 pk.setFingerprintAndKeyId()
73 }
74
75 // UpgradeToV6 updates the version of the key to v6, and updates all necessary
76 // fields.
77 func (pk *PublicKey) UpgradeToV6() error {
78 pk.Version = 6
79 pk.setFingerprintAndKeyId()
80 return pk.checkV6Compatibility()
81 }
82
83 // signingKey provides a convenient abstraction over signature verification
84 // for v3 and v4 public keys.
85 type signingKey interface {
86 SerializeForHash(io.Writer) error
87 SerializeSignaturePrefix(io.Writer) error
88 serializeWithoutHeaders(io.Writer) error
89 }
90
91 // NewRSAPublicKey returns a PublicKey that wraps the given rsa.PublicKey.
92 func NewRSAPublicKey(creationTime time.Time, pub *rsa.PublicKey) *PublicKey {
93 pk := &PublicKey{
94 Version: 4,
95 CreationTime: creationTime,
96 PubKeyAlgo: PubKeyAlgoRSA,
97 PublicKey: pub,
98 n: new(encoding.MPI).SetBig(pub.N),
99 e: new(encoding.MPI).SetBig(big.NewInt(int64(pub.E))),
100 }
101
102 pk.setFingerprintAndKeyId()
103 return pk
104 }
105
106 // NewDSAPublicKey returns a PublicKey that wraps the given dsa.PublicKey.
107 func NewDSAPublicKey(creationTime time.Time, pub *dsa.PublicKey) *PublicKey {
108 pk := &PublicKey{
109 Version: 4,
110 CreationTime: creationTime,
111 PubKeyAlgo: PubKeyAlgoDSA,
112 PublicKey: pub,
113 p: new(encoding.MPI).SetBig(pub.P),
114 q: new(encoding.MPI).SetBig(pub.Q),
115 g: new(encoding.MPI).SetBig(pub.G),
116 y: new(encoding.MPI).SetBig(pub.Y),
117 }
118
119 pk.setFingerprintAndKeyId()
120 return pk
121 }
122
123 // NewElGamalPublicKey returns a PublicKey that wraps the given elgamal.PublicKey.
124 func NewElGamalPublicKey(creationTime time.Time, pub *elgamal.PublicKey) *PublicKey {
125 pk := &PublicKey{
126 Version: 4,
127 CreationTime: creationTime,
128 PubKeyAlgo: PubKeyAlgoElGamal,
129 PublicKey: pub,
130 p: new(encoding.MPI).SetBig(pub.P),
131 g: new(encoding.MPI).SetBig(pub.G),
132 y: new(encoding.MPI).SetBig(pub.Y),
133 }
134
135 pk.setFingerprintAndKeyId()
136 return pk
137 }
138
139 func NewECDSAPublicKey(creationTime time.Time, pub *ecdsa.PublicKey) *PublicKey {
140 pk := &PublicKey{
141 Version: 4,
142 CreationTime: creationTime,
143 PubKeyAlgo: PubKeyAlgoECDSA,
144 PublicKey: pub,
145 p: encoding.NewMPI(pub.MarshalPoint()),
146 }
147
148 curveInfo := ecc.FindByCurve(pub.GetCurve())
149 if curveInfo == nil {
150 panic("unknown elliptic curve")
151 }
152 pk.oid = curveInfo.Oid
153 pk.setFingerprintAndKeyId()
154 return pk
155 }
156
157 func NewECDHPublicKey(creationTime time.Time, pub *ecdh.PublicKey) *PublicKey {
158 var pk *PublicKey
159 var kdf = encoding.NewOID([]byte{0x1, pub.Hash.Id(), pub.Cipher.Id()})
160 pk = &PublicKey{
161 Version: 4,
162 CreationTime: creationTime,
163 PubKeyAlgo: PubKeyAlgoECDH,
164 PublicKey: pub,
165 p: encoding.NewMPI(pub.MarshalPoint()),
166 kdf: kdf,
167 }
168
169 curveInfo := ecc.FindByCurve(pub.GetCurve())
170
171 if curveInfo == nil {
172 panic("unknown elliptic curve")
173 }
174
175 pk.oid = curveInfo.Oid
176 pk.setFingerprintAndKeyId()
177 return pk
178 }
179
180 func NewEdDSAPublicKey(creationTime time.Time, pub *eddsa.PublicKey) *PublicKey {
181 curveInfo := ecc.FindByCurve(pub.GetCurve())
182 pk := &PublicKey{
183 Version: 4,
184 CreationTime: creationTime,
185 PubKeyAlgo: PubKeyAlgoEdDSA,
186 PublicKey: pub,
187 oid: curveInfo.Oid,
188 // Native point format, see draft-koch-eddsa-for-openpgp-04, Appendix B
189 p: encoding.NewMPI(pub.MarshalPoint()),
190 }
191
192 pk.setFingerprintAndKeyId()
193 return pk
194 }
195
196 func NewX25519PublicKey(creationTime time.Time, pub *x25519.PublicKey) *PublicKey {
197 pk := &PublicKey{
198 Version: 4,
199 CreationTime: creationTime,
200 PubKeyAlgo: PubKeyAlgoX25519,
201 PublicKey: pub,
202 }
203
204 pk.setFingerprintAndKeyId()
205 return pk
206 }
207
208 func NewX448PublicKey(creationTime time.Time, pub *x448.PublicKey) *PublicKey {
209 pk := &PublicKey{
210 Version: 4,
211 CreationTime: creationTime,
212 PubKeyAlgo: PubKeyAlgoX448,
213 PublicKey: pub,
214 }
215
216 pk.setFingerprintAndKeyId()
217 return pk
218 }
219
220 func NewEd25519PublicKey(creationTime time.Time, pub *ed25519.PublicKey) *PublicKey {
221 pk := &PublicKey{
222 Version: 4,
223 CreationTime: creationTime,
224 PubKeyAlgo: PubKeyAlgoEd25519,
225 PublicKey: pub,
226 }
227
228 pk.setFingerprintAndKeyId()
229 return pk
230 }
231
232 func NewEd448PublicKey(creationTime time.Time, pub *ed448.PublicKey) *PublicKey {
233 pk := &PublicKey{
234 Version: 4,
235 CreationTime: creationTime,
236 PubKeyAlgo: PubKeyAlgoEd448,
237 PublicKey: pub,
238 }
239
240 pk.setFingerprintAndKeyId()
241 return pk
242 }
243
244 func NewMlkemEcdhPublicKey(creationTime time.Time, pub *mlkem_ecdh.PublicKey) *PublicKey {
245 pk := &PublicKey{
246 Version: 4,
247 CreationTime: creationTime,
248 PubKeyAlgo: PublicKeyAlgorithm(pub.AlgId),
249 PublicKey: pub,
250 }
251
252 pk.setFingerprintAndKeyId()
253 return pk
254 }
255
256 func NewMldsaEddsaPublicKey(creationTime time.Time, pub *mldsa_eddsa.PublicKey) *PublicKey {
257 pk := &PublicKey{
258 Version: 6,
259 CreationTime: creationTime,
260 PubKeyAlgo: PublicKeyAlgorithm(pub.AlgId),
261 PublicKey: pub,
262 }
263
264 pk.setFingerprintAndKeyId()
265 return pk
266 }
267
268 func NewSlhdsaPublicKey(creationTime time.Time, pub *slhdsa.PublicKey) *PublicKey {
269 pk := &PublicKey{
270 Version: 6,
271 CreationTime: creationTime,
272 PubKeyAlgo: PublicKeyAlgorithm(pub.AlgId),
273 PublicKey: pub,
274 }
275
276 pk.setFingerprintAndKeyId()
277 return pk
278 }
279
280 func (pk *PublicKey) parse(r io.Reader) (err error) {
281 // RFC 4880, section 5.5.2
282 var buf [6]byte
283 _, err = readFull(r, buf[:])
284 if err != nil {
285 return
286 }
287
288 pk.Version = int(buf[0])
289 if pk.Version != 4 && pk.Version != 5 && pk.Version != 6 {
290 return errors.UnsupportedError("public key version " + strconv.Itoa(int(buf[0])))
291 }
292
293 if V5Disabled && pk.Version == 5 {
294 return errors.UnsupportedError("support for parsing v5 entities is disabled; build with `-tags v5` if needed")
295 }
296
297 if pk.Version >= 5 {
298 // Read the four-octet scalar octet count
299 // The count is not used in this implementation
300 var n [4]byte
301 _, err = readFull(r, n[:])
302 if err != nil {
303 return
304 }
305 }
306 pk.CreationTime = time.Unix(int64(uint32(buf[1])<<24|uint32(buf[2])<<16|uint32(buf[3])<<8|uint32(buf[4])), 0)
307 pk.PubKeyAlgo = PublicKeyAlgorithm(buf[5])
308 // Ignore four-octet length
309 switch pk.PubKeyAlgo {
310 case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly:
311 err = pk.parseRSA(r)
312 case PubKeyAlgoDSA:
313 err = pk.parseDSA(r)
314 case PubKeyAlgoElGamal:
315 err = pk.parseElGamal(r)
316 case PubKeyAlgoECDSA:
317 err = pk.parseECDSA(r)
318 case PubKeyAlgoECDH:
319 err = pk.parseECDH(r)
320 case PubKeyAlgoEdDSA:
321 err = pk.parseEdDSA(r)
322 case PubKeyAlgoX25519:
323 err = pk.parseX25519(r)
324 case PubKeyAlgoX448:
325 err = pk.parseX448(r)
326 case PubKeyAlgoEd25519:
327 err = pk.parseEd25519(r)
328 case PubKeyAlgoEd448:
329 err = pk.parseEd448(r)
330 case PubKeyAlgoMlkem768X25519:
331 if !(pk.Version == 4 || pk.Version >= 6) {
332 return goerrors.New("openpgp: ML-KEM-768+X25519 may only be used with v4 or v6+")
333 }
334 err = pk.parseMlkemEcdh(r, 32, mlkem768.PublicKeySize)
335 case PubKeyAlgoMlkem1024X448:
336 if pk.Version < 6 {
337 return goerrors.New("openpgp: ML-KEM-1024+X448 may only be used with v6+")
338 }
339 err = pk.parseMlkemEcdh(r, 56, mlkem1024.PublicKeySize)
340 case PubKeyAlgoMldsa65Ed25519:
341 if pk.Version < 6 {
342 return goerrors.New("openpgp: ML-DSA-65+Ed25519 may only be used with v6+")
343 }
344 err = pk.parseMldsaEddsa(r, 32, mldsa65.PublicKeySize)
345 case PubKeyAlgoMldsa87Ed448:
346 if pk.Version < 6 {
347 return goerrors.New("openpgp: ML-DSA-87+Ed448 may only be used with v6+")
348 }
349 err = pk.parseMldsaEddsa(r, 57, mldsa87.PublicKeySize)
350 case PubKeyAlgoSlhdsaShake128s, PubKeyAlgoSlhdsaShake128f, PubKeyAlgoSlhdsaShake256s:
351 if pk.Version < 6 {
352 return goerrors.New("openpgp: SLH-DSA may only be used with v6+")
353 }
354 err = pk.parseSlhDsa(r)
355 default:
356 err = errors.UnsupportedError("public key type: " + strconv.Itoa(int(pk.PubKeyAlgo)))
357 }
358 if err != nil {
359 return
360 }
361
362 pk.setFingerprintAndKeyId()
363 return
364 }
365
366 func (pk *PublicKey) setFingerprintAndKeyId() {
367 // RFC 4880, section 12.2
368 if pk.Version >= 5 {
369 fingerprint := sha256.New()
370 if err := pk.SerializeForHash(fingerprint); err != nil {
371 // Should not happen for a hash.
372 panic(err)
373 }
374 pk.Fingerprint = make([]byte, 32)
375 copy(pk.Fingerprint, fingerprint.Sum(nil))
376 pk.KeyId = binary.BigEndian.Uint64(pk.Fingerprint[:8])
377 } else {
378 fingerprint := sha1.New()
379 if err := pk.SerializeForHash(fingerprint); err != nil {
380 // Should not happen for a hash.
381 panic(err)
382 }
383 pk.Fingerprint = make([]byte, 20)
384 copy(pk.Fingerprint, fingerprint.Sum(nil))
385 pk.KeyId = binary.BigEndian.Uint64(pk.Fingerprint[12:20])
386 }
387 }
388
389 func (pk *PublicKey) checkV6Compatibility() error {
390 // Implementations MUST NOT accept or generate version 6 key material using the deprecated OIDs.
391 switch pk.PubKeyAlgo {
392 case PubKeyAlgoECDH:
393 curveInfo := ecc.FindByOid(pk.oid)
394 if curveInfo == nil {
395 return errors.UnsupportedError(fmt.Sprintf("unknown oid: %x", pk.oid))
396 }
397 if curveInfo.GenName == ecc.Curve25519GenName {
398 return errors.StructuralError("cannot generate v6 key with deprecated OID: Curve25519Legacy")
399 }
400 case PubKeyAlgoEdDSA:
401 return errors.StructuralError("cannot generate v6 key with deprecated algorithm: EdDSALegacy")
402 }
403 return nil
404 }
405
406 // parseRSA parses RSA public key material from the given Reader. See RFC 4880,
407 // section 5.5.2.
408 func (pk *PublicKey) parseRSA(r io.Reader) (err error) {
409 pk.n = new(encoding.MPI)
410 if _, err = pk.n.ReadFrom(r); err != nil {
411 return
412 }
413 pk.e = new(encoding.MPI)
414 if _, err = pk.e.ReadFrom(r); err != nil {
415 return
416 }
417
418 if len(pk.e.Bytes()) > 3 {
419 err = errors.UnsupportedError("large public exponent")
420 return
421 }
422 rsa := &rsa.PublicKey{
423 N: new(big.Int).SetBytes(pk.n.Bytes()),
424 E: 0,
425 }
426 for i := 0; i < len(pk.e.Bytes()); i++ {
427 rsa.E <<= 8
428 rsa.E |= int(pk.e.Bytes()[i])
429 }
430 pk.PublicKey = rsa
431 return
432 }
433
434 // parseDSA parses DSA public key material from the given Reader. See RFC 4880,
435 // section 5.5.2.
436 func (pk *PublicKey) parseDSA(r io.Reader) (err error) {
437 pk.p = new(encoding.MPI)
438 if _, err = pk.p.ReadFrom(r); err != nil {
439 return
440 }
441 pk.q = new(encoding.MPI)
442 if _, err = pk.q.ReadFrom(r); err != nil {
443 return
444 }
445 pk.g = new(encoding.MPI)
446 if _, err = pk.g.ReadFrom(r); err != nil {
447 return
448 }
449 pk.y = new(encoding.MPI)
450 if _, err = pk.y.ReadFrom(r); err != nil {
451 return
452 }
453
454 dsa := new(dsa.PublicKey)
455 dsa.P = new(big.Int).SetBytes(pk.p.Bytes())
456 dsa.Q = new(big.Int).SetBytes(pk.q.Bytes())
457 dsa.G = new(big.Int).SetBytes(pk.g.Bytes())
458 dsa.Y = new(big.Int).SetBytes(pk.y.Bytes())
459 pk.PublicKey = dsa
460 return
461 }
462
463 // parseElGamal parses ElGamal public key material from the given Reader. See
464 // RFC 4880, section 5.5.2.
465 func (pk *PublicKey) parseElGamal(r io.Reader) (err error) {
466 pk.p = new(encoding.MPI)
467 if _, err = pk.p.ReadFrom(r); err != nil {
468 return
469 }
470 pk.g = new(encoding.MPI)
471 if _, err = pk.g.ReadFrom(r); err != nil {
472 return
473 }
474 pk.y = new(encoding.MPI)
475 if _, err = pk.y.ReadFrom(r); err != nil {
476 return
477 }
478
479 elgamal := new(elgamal.PublicKey)
480 elgamal.P = new(big.Int).SetBytes(pk.p.Bytes())
481 elgamal.G = new(big.Int).SetBytes(pk.g.Bytes())
482 elgamal.Y = new(big.Int).SetBytes(pk.y.Bytes())
483 pk.PublicKey = elgamal
484 return
485 }
486
487 // parseECDSA parses ECDSA public key material from the given Reader. See
488 // RFC 6637, Section 9.
489 func (pk *PublicKey) parseECDSA(r io.Reader) (err error) {
490 pk.oid = new(encoding.OID)
491 if _, err = pk.oid.ReadFrom(r); err != nil {
492 return
493 }
494
495 curveInfo := ecc.FindByOid(pk.oid)
496 if curveInfo == nil {
497 return errors.UnsupportedError(fmt.Sprintf("unknown oid: %x", pk.oid))
498 }
499
500 pk.p = new(encoding.MPI)
501 if _, err = pk.p.ReadFrom(r); err != nil {
502 return
503 }
504
505 c, ok := curveInfo.Curve.(ecc.ECDSACurve)
506 if !ok {
507 return errors.UnsupportedError(fmt.Sprintf("unsupported oid: %x", pk.oid))
508 }
509
510 ecdsaKey := ecdsa.NewPublicKey(c)
511 err = ecdsaKey.UnmarshalPoint(pk.p.Bytes())
512 pk.PublicKey = ecdsaKey
513
514 return
515 }
516
517 // parseECDH parses ECDH public key material from the given Reader. See
518 // RFC 6637, Section 9.
519 func (pk *PublicKey) parseECDH(r io.Reader) (err error) {
520 pk.oid = new(encoding.OID)
521 if _, err = pk.oid.ReadFrom(r); err != nil {
522 return
523 }
524
525 curveInfo := ecc.FindByOid(pk.oid)
526 if curveInfo == nil {
527 return errors.UnsupportedError(fmt.Sprintf("unknown oid: %x", pk.oid))
528 }
529
530 if pk.Version == 6 && curveInfo.GenName == ecc.Curve25519GenName {
531 // Implementations MUST NOT accept or generate version 6 key material using the deprecated OIDs.
532 return errors.StructuralError("cannot read v6 key with deprecated OID: Curve25519Legacy")
533 }
534
535 pk.p = new(encoding.MPI)
536 if _, err = pk.p.ReadFrom(r); err != nil {
537 return
538 }
539 pk.kdf = new(encoding.OID)
540 if _, err = pk.kdf.ReadFrom(r); err != nil {
541 return
542 }
543
544 c, ok := curveInfo.Curve.(ecc.ECDHCurve)
545 if !ok {
546 return errors.UnsupportedError(fmt.Sprintf("unsupported oid: %x", pk.oid))
547 }
548
549 if kdfLen := len(pk.kdf.Bytes()); kdfLen < 3 {
550 return errors.UnsupportedError("unsupported ECDH KDF length: " + strconv.Itoa(kdfLen))
551 }
552 if reserved := pk.kdf.Bytes()[0]; reserved != 0x01 {
553 return errors.UnsupportedError("unsupported KDF reserved field: " + strconv.Itoa(int(reserved)))
554 }
555 kdfHash, ok := algorithm.HashById[pk.kdf.Bytes()[1]]
556 if !ok {
557 return errors.UnsupportedError("unsupported ECDH KDF hash: " + strconv.Itoa(int(pk.kdf.Bytes()[1])))
558 }
559 kdfCipher, ok := algorithm.CipherById[pk.kdf.Bytes()[2]]
560 if !ok {
561 return errors.UnsupportedError("unsupported ECDH KDF cipher: " + strconv.Itoa(int(pk.kdf.Bytes()[2])))
562 }
563 // RFC 6637, section 7: the KDF hash must be at least as long as the KEK.
564 if kdfHash.HashFunc().Size() < kdfCipher.KeySize() {
565 return errors.StructuralError("ECDH KDF hash output is shorter than the KDF cipher key size")
566 }
567
568 ecdhKey := ecdh.NewPublicKey(c, kdfHash, kdfCipher)
569 err = ecdhKey.UnmarshalPoint(pk.p.Bytes())
570 pk.PublicKey = ecdhKey
571
572 return
573 }
574
575 func (pk *PublicKey) parseEdDSA(r io.Reader) (err error) {
576 if pk.Version == 6 {
577 // Implementations MUST NOT accept or generate version 6 key material using the deprecated OIDs.
578 return errors.StructuralError("cannot generate v6 key with deprecated algorithm: EdDSALegacy")
579 }
580
581 pk.oid = new(encoding.OID)
582 if _, err = pk.oid.ReadFrom(r); err != nil {
583 return
584 }
585
586 curveInfo := ecc.FindByOid(pk.oid)
587 if curveInfo == nil {
588 return errors.UnsupportedError(fmt.Sprintf("unknown oid: %x", pk.oid))
589 }
590
591 c, ok := curveInfo.Curve.(ecc.EdDSACurve)
592 if !ok {
593 return errors.UnsupportedError(fmt.Sprintf("unsupported oid: %x", pk.oid))
594 }
595
596 pk.p = new(encoding.MPI)
597 if _, err = pk.p.ReadFrom(r); err != nil {
598 return
599 }
600
601 if len(pk.p.Bytes()) == 0 {
602 return errors.StructuralError("empty EdDSA public key")
603 }
604
605 pub := eddsa.NewPublicKey(c)
606
607 switch flag := pk.p.Bytes()[0]; flag {
608 case 0x04:
609 // TODO: see _grcy_ecc_eddsa_ensure_compact in grcypt
610 return errors.UnsupportedError("unsupported EdDSA compression: " + strconv.Itoa(int(flag)))
611 case 0x40:
612 err = pub.UnmarshalPoint(pk.p.Bytes())
613 default:
614 return errors.UnsupportedError("unsupported EdDSA compression: " + strconv.Itoa(int(flag)))
615 }
616
617 pk.PublicKey = pub
618 return
619 }
620
621 func (pk *PublicKey) parseX25519(r io.Reader) (err error) {
622 point := make([]byte, x25519.KeySize)
623 _, err = io.ReadFull(r, point)
624 if err != nil {
625 return
626 }
627 pub := &x25519.PublicKey{
628 Point: point,
629 }
630 pk.PublicKey = pub
631 return
632 }
633
634 func (pk *PublicKey) parseX448(r io.Reader) (err error) {
635 point := make([]byte, x448.KeySize)
636 _, err = io.ReadFull(r, point)
637 if err != nil {
638 return
639 }
640 pub := &x448.PublicKey{
641 Point: point,
642 }
643 pk.PublicKey = pub
644 return
645 }
646
647 func (pk *PublicKey) parseEd25519(r io.Reader) (err error) {
648 point := make([]byte, ed25519.PublicKeySize)
649 _, err = io.ReadFull(r, point)
650 if err != nil {
651 return
652 }
653 pub := &ed25519.PublicKey{
654 Point: point,
655 }
656 pk.PublicKey = pub
657 return
658 }
659
660 func (pk *PublicKey) parseEd448(r io.Reader) (err error) {
661 point := make([]byte, ed448.PublicKeySize)
662 _, err = io.ReadFull(r, point)
663 if err != nil {
664 return
665 }
666 pub := &ed448.PublicKey{
667 Point: point,
668 }
669 pk.PublicKey = pub
670 return
671 }
672
673 // parseMlkemEcdh parses a ML-KEM + ECC public key as specified in
674 // https://www.rfc-editor.org/rfc/rfc9980.html#name-key-material-packets
675 func (pk *PublicKey) parseMlkemEcdh(r io.Reader, ecLen, kLen int) (err error) {
676 ecKey := make([]byte, ecLen)
677 if _, err = io.ReadFull(r, ecKey); err != nil {
678 return
679 }
680
681 mlkemKey := make([]byte, kLen)
682 if _, err = io.ReadFull(r, mlkemKey); err != nil {
683 return
684 }
685
686 pub := &mlkem_ecdh.PublicKey{
687 AlgId: uint8(pk.PubKeyAlgo),
688 PublicPoint: ecKey,
689 }
690
691 if pub.Curve, err = GetECDHCurveFromAlgID(pk.PubKeyAlgo); err != nil {
692 return err
693 }
694
695 if pub.Mlkem, err = GetMlkemFromAlgID(pk.PubKeyAlgo); err != nil {
696 return err
697 }
698
699 if pub.PublicMlkem, err = pub.Mlkem.UnmarshalBinaryPublicKey(mlkemKey); err != nil {
700 return err
701 }
702
703 pk.PublicKey = pub
704
705 return
706 }
707
708 // parseMldsaEddsa parses a ML-DSA + EdDSA public key as specified in
709 // https://www.rfc-editor.org/rfc/rfc9980.html#name-key-material-packets-2
710 func (pk *PublicKey) parseMldsaEddsa(r io.Reader, ecLen, dLen int) (err error) {
711 ecKey := make([]byte, ecLen)
712 if _, err = io.ReadFull(r, ecKey); err != nil {
713 return
714 }
715
716 mldsaKey := make([]byte, dLen)
717 if _, err = io.ReadFull(r, mldsaKey); err != nil {
718 return
719 }
720
721 pub := &mldsa_eddsa.PublicKey{
722 AlgId: uint8(pk.PubKeyAlgo),
723 PublicPoint: ecKey,
724 }
725
726 if pub.Curve, err = GetEdDSACurveFromAlgID(pk.PubKeyAlgo); err != nil {
727 return err
728 }
729
730 if pub.Mldsa, err = GetMldsaFromAlgID(pk.PubKeyAlgo); err != nil {
731 return err
732 }
733
734 if pub.PublicMldsa, err = pub.Mldsa.UnmarshalBinaryPublicKey(mldsaKey); err != nil {
735 return err
736 }
737
738 pk.PublicKey = pub
739 return
740 }
741
742 func (pk *PublicKey) parseSlhDsa(r io.Reader) (err error) {
743 parsedPublicKey := &slhdsa.PublicKey{
744 AlgId: uint8(pk.PubKeyAlgo),
745 }
746
747 if parsedPublicKey.Slhdsa, err = GetSlhdsaSchemeFromAlgID(pk.PubKeyAlgo); err != nil {
748 return err
749 }
750
751 keyLen := parsedPublicKey.Slhdsa.PublicKeySize()
752 key := make([]byte, keyLen)
753 if _, err = io.ReadFull(r, key); err != nil {
754 return err
755 }
756
757 if parsedPublicKey.PublicSlhdsa, err = parsedPublicKey.Slhdsa.UnmarshalBinaryPublicKey(key); err != nil {
758 return err
759 }
760
761 pk.PublicKey = parsedPublicKey
762 return nil
763 }
764
765 // SerializeForHash serializes the PublicKey to w with the special packet
766 // header format needed for hashing.
767 func (pk *PublicKey) SerializeForHash(w io.Writer) error {
768 if err := pk.SerializeSignaturePrefix(w); err != nil {
769 return err
770 }
771 return pk.serializeWithoutHeaders(w)
772 }
773
774 // SerializeSignaturePrefix writes the prefix for this public key to the given Writer.
775 // The prefix is used when calculating a signature over this public key. See
776 // RFC 4880, section 5.2.4.
777 func (pk *PublicKey) SerializeSignaturePrefix(w io.Writer) error {
778 var pLength = pk.algorithmSpecificByteCount()
779 // version, timestamp, algorithm
780 pLength += versionSize + timestampSize + algorithmSize
781 if pk.Version >= 5 {
782 // key octet count (4).
783 pLength += 4
784 _, err := w.Write([]byte{
785 // When a v4 signature is made over a key, the hash data starts with the octet 0x99, followed by a two-octet length
786 // of the key, and then the body of the key packet. When a v6 signature is made over a key, the hash data starts
787 // with the salt, then octet 0x9B, followed by a four-octet length of the key, and then the body of the key packet.
788 0x95 + byte(pk.Version),
789 byte(pLength >> 24),
790 byte(pLength >> 16),
791 byte(pLength >> 8),
792 byte(pLength),
793 })
794 return err
795 }
796 if _, err := w.Write([]byte{0x99, byte(pLength >> 8), byte(pLength)}); err != nil {
797 return err
798 }
799 return nil
800 }
801
802 func (pk *PublicKey) Serialize(w io.Writer) (err error) {
803 length := uint32(versionSize + timestampSize + algorithmSize) // 6 byte header
804 length += pk.algorithmSpecificByteCount()
805 if pk.Version >= 5 {
806 length += 4 // octet key count
807 }
808 packetType := packetTypePublicKey
809 if pk.IsSubkey {
810 packetType = packetTypePublicSubkey
811 }
812 err = serializeHeader(w, packetType, int(length))
813 if err != nil {
814 return
815 }
816 return pk.serializeWithoutHeaders(w)
817 }
818
819 func (pk *PublicKey) algorithmSpecificByteCount() uint32 {
820 length := uint32(0)
821 switch pk.PubKeyAlgo {
822 case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly:
823 length += uint32(pk.n.EncodedLength())
824 length += uint32(pk.e.EncodedLength())
825 case PubKeyAlgoDSA:
826 length += uint32(pk.p.EncodedLength())
827 length += uint32(pk.q.EncodedLength())
828 length += uint32(pk.g.EncodedLength())
829 length += uint32(pk.y.EncodedLength())
830 case PubKeyAlgoElGamal:
831 length += uint32(pk.p.EncodedLength())
832 length += uint32(pk.g.EncodedLength())
833 length += uint32(pk.y.EncodedLength())
834 case PubKeyAlgoECDSA:
835 length += uint32(pk.oid.EncodedLength())
836 length += uint32(pk.p.EncodedLength())
837 case PubKeyAlgoECDH:
838 length += uint32(pk.oid.EncodedLength())
839 length += uint32(pk.p.EncodedLength())
840 length += uint32(pk.kdf.EncodedLength())
841 case PubKeyAlgoEdDSA:
842 length += uint32(pk.oid.EncodedLength())
843 length += uint32(pk.p.EncodedLength())
844 case PubKeyAlgoX25519:
845 length += x25519.KeySize
846 case PubKeyAlgoX448:
847 length += x448.KeySize
848 case PubKeyAlgoEd25519:
849 length += ed25519.PublicKeySize
850 case PubKeyAlgoEd448:
851 length += ed448.PublicKeySize
852 case PubKeyAlgoMlkem768X25519:
853 length += x25519.KeySize
854 length += mlkem768.PublicKeySize
855 case PubKeyAlgoMlkem1024X448:
856 length += x448.KeySize
857 length += mlkem1024.PublicKeySize
858 case PubKeyAlgoMldsa65Ed25519:
859 length += ed25519.PublicKeySize
860 length += mldsa65.PublicKeySize
861 case PubKeyAlgoMldsa87Ed448:
862 length += ed448.PublicKeySize
863 length += mldsa87.PublicKeySize
864 case PubKeyAlgoSlhdsaShake128s, PubKeyAlgoSlhdsaShake128f, PubKeyAlgoSlhdsaShake256s:
865 publicKey := pk.PublicKey.(*slhdsa.PublicKey)
866 length += uint32(publicKey.Slhdsa.PublicKeySize())
867 default:
868 panic("unknown public key algorithm")
869 }
870 return length
871 }
872
873 // serializeWithoutHeaders marshals the PublicKey to w in the form of an
874 // OpenPGP public key packet, not including the packet header.
875 func (pk *PublicKey) serializeWithoutHeaders(w io.Writer) (err error) {
876 t := uint32(pk.CreationTime.Unix())
877 if _, err = w.Write([]byte{
878 byte(pk.Version),
879 byte(t >> 24), byte(t >> 16), byte(t >> 8), byte(t),
880 byte(pk.PubKeyAlgo),
881 }); err != nil {
882 return
883 }
884
885 if pk.Version >= 5 {
886 n := pk.algorithmSpecificByteCount()
887 if _, err = w.Write([]byte{
888 byte(n >> 24), byte(n >> 16), byte(n >> 8), byte(n),
889 }); err != nil {
890 return
891 }
892 }
893
894 switch pk.PubKeyAlgo {
895 case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly:
896 if _, err = w.Write(pk.n.EncodedBytes()); err != nil {
897 return
898 }
899 _, err = w.Write(pk.e.EncodedBytes())
900 return
901 case PubKeyAlgoDSA:
902 if _, err = w.Write(pk.p.EncodedBytes()); err != nil {
903 return
904 }
905 if _, err = w.Write(pk.q.EncodedBytes()); err != nil {
906 return
907 }
908 if _, err = w.Write(pk.g.EncodedBytes()); err != nil {
909 return
910 }
911 _, err = w.Write(pk.y.EncodedBytes())
912 return
913 case PubKeyAlgoElGamal:
914 if _, err = w.Write(pk.p.EncodedBytes()); err != nil {
915 return
916 }
917 if _, err = w.Write(pk.g.EncodedBytes()); err != nil {
918 return
919 }
920 _, err = w.Write(pk.y.EncodedBytes())
921 return
922 case PubKeyAlgoECDSA:
923 if _, err = w.Write(pk.oid.EncodedBytes()); err != nil {
924 return
925 }
926 _, err = w.Write(pk.p.EncodedBytes())
927 return
928 case PubKeyAlgoECDH:
929 if _, err = w.Write(pk.oid.EncodedBytes()); err != nil {
930 return
931 }
932 if _, err = w.Write(pk.p.EncodedBytes()); err != nil {
933 return
934 }
935 _, err = w.Write(pk.kdf.EncodedBytes())
936 return
937 case PubKeyAlgoEdDSA:
938 if _, err = w.Write(pk.oid.EncodedBytes()); err != nil {
939 return
940 }
941 _, err = w.Write(pk.p.EncodedBytes())
942 return
943 case PubKeyAlgoX25519:
944 publicKey := pk.PublicKey.(*x25519.PublicKey)
945 _, err = w.Write(publicKey.Point)
946 return
947 case PubKeyAlgoX448:
948 publicKey := pk.PublicKey.(*x448.PublicKey)
949 _, err = w.Write(publicKey.Point)
950 return
951 case PubKeyAlgoEd25519:
952 publicKey := pk.PublicKey.(*ed25519.PublicKey)
953 _, err = w.Write(publicKey.Point)
954 return
955 case PubKeyAlgoEd448:
956 publicKey := pk.PublicKey.(*ed448.PublicKey)
957 _, err = w.Write(publicKey.Point)
958 return
959 case PubKeyAlgoMlkem768X25519, PubKeyAlgoMlkem1024X448:
960 publicKey := pk.PublicKey.(*mlkem_ecdh.PublicKey)
961 if _, err = w.Write(publicKey.PublicPoint); err != nil {
962 return
963 }
964 var mlkemBin []byte
965 mlkemBin, err = publicKey.PublicMlkem.MarshalBinary()
966 if err != nil {
967 return
968 }
969 _, err = w.Write(mlkemBin)
970 return
971 case PubKeyAlgoMldsa65Ed25519, PubKeyAlgoMldsa87Ed448:
972 publicKey := pk.PublicKey.(*mldsa_eddsa.PublicKey)
973 if _, err = w.Write(publicKey.PublicPoint); err != nil {
974 return
975 }
976 var mldsaBin []byte
977 mldsaBin, err = publicKey.PublicMldsa.MarshalBinary()
978 if err != nil {
979 return
980 }
981 _, err = w.Write(mldsaBin)
982 return
983 case PubKeyAlgoSlhdsaShake128s, PubKeyAlgoSlhdsaShake128f, PubKeyAlgoSlhdsaShake256s:
984 publicKey := pk.PublicKey.(*slhdsa.PublicKey)
985 var slhdsaBin []byte
986 slhdsaBin, err = publicKey.PublicSlhdsa.MarshalBinary()
987 if err != nil {
988 return
989 }
990 _, err = w.Write(slhdsaBin)
991 return
992 }
993 return errors.InvalidArgumentError("bad public-key algorithm")
994 }
995
996 // CanSign returns true iff this public key can generate signatures
997 func (pk *PublicKey) CanSign() bool {
998 return pk.PubKeyAlgo.CanSign()
999 }
1000
1001 // VerifyHashTag returns nil iff sig appears to be a plausible signature of the data
1002 // hashed into signed, based solely on its HashTag. signed is mutated by this call.
1003 func VerifyHashTag(signed hash.Hash, sig *Signature) (err error) {
1004 if sig.Version == 5 && (sig.SigType == 0x00 || sig.SigType == 0x01) {
1005 sig.AddMetadataToHashSuffix()
1006 }
1007 signed.Write(sig.HashSuffix)
1008 hashBytes := signed.Sum(nil)
1009 if hashBytes[0] != sig.HashTag[0] || hashBytes[1] != sig.HashTag[1] {
1010 return errors.SignatureError("hash tag doesn't match")
1011 }
1012 return nil
1013 }
1014
1015 // VerifySignature returns nil iff sig is a valid signature, made by this
1016 // public key, of the data hashed into signed. signed is mutated by this call.
1017 func (pk *PublicKey) VerifySignature(signed hash.Hash, sig *Signature) (err error) {
1018 if !pk.CanSign() {
1019 return errors.InvalidArgumentError("public key cannot generate signatures")
1020 }
1021 if sig.Version == 5 && (sig.SigType == 0x00 || sig.SigType == 0x01) {
1022 sig.AddMetadataToHashSuffix()
1023 }
1024 signed.Write(sig.HashSuffix)
1025 hashBytes := signed.Sum(nil)
1026 // see discussion https://github.com/ProtonMail/go-crypto/issues/107
1027 if sig.Version >= 5 && (hashBytes[0] != sig.HashTag[0] || hashBytes[1] != sig.HashTag[1]) {
1028 return errors.SignatureError("hash tag doesn't match")
1029 }
1030
1031 if pk.PubKeyAlgo != sig.PubKeyAlgo {
1032 return errors.InvalidArgumentError("public key and signature use different algorithms")
1033 }
1034
1035 switch pk.PubKeyAlgo {
1036 case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly:
1037 rsaPublicKey, _ := pk.PublicKey.(*rsa.PublicKey)
1038 err = rsa.VerifyPKCS1v15(rsaPublicKey, sig.Hash, hashBytes, padToKeySize(rsaPublicKey, sig.RSASignature.Bytes()))
1039 if err != nil {
1040 return errors.SignatureError("RSA verification failure")
1041 }
1042 return nil
1043 case PubKeyAlgoDSA:
1044 dsaPublicKey, _ := pk.PublicKey.(*dsa.PublicKey)
1045 // Need to truncate hashBytes to match FIPS 186-3 section 4.6.
1046 subgroupSize := (dsaPublicKey.Q.BitLen() + 7) / 8
1047 if len(hashBytes) > subgroupSize {
1048 hashBytes = hashBytes[:subgroupSize]
1049 }
1050 if !dsa.Verify(dsaPublicKey, hashBytes, new(big.Int).SetBytes(sig.DSASigR.Bytes()), new(big.Int).SetBytes(sig.DSASigS.Bytes())) {
1051 return errors.SignatureError("DSA verification failure")
1052 }
1053 return nil
1054 case PubKeyAlgoECDSA:
1055 ecdsaPublicKey := pk.PublicKey.(*ecdsa.PublicKey)
1056 if !ecdsa.Verify(ecdsaPublicKey, hashBytes, new(big.Int).SetBytes(sig.ECDSASigR.Bytes()), new(big.Int).SetBytes(sig.ECDSASigS.Bytes())) {
1057 return errors.SignatureError("ECDSA verification failure")
1058 }
1059 return nil
1060 case PubKeyAlgoEdDSA:
1061 eddsaPublicKey := pk.PublicKey.(*eddsa.PublicKey)
1062 if !eddsa.Verify(eddsaPublicKey, hashBytes, sig.EdDSASigR.Bytes(), sig.EdDSASigS.Bytes()) {
1063 return errors.SignatureError("EdDSA verification failure")
1064 }
1065 return nil
1066 case PubKeyAlgoEd25519:
1067 ed25519PublicKey := pk.PublicKey.(*ed25519.PublicKey)
1068 if !ed25519.Verify(ed25519PublicKey, hashBytes, sig.EdSig) {
1069 return errors.SignatureError("Ed25519 verification failure")
1070 }
1071 return nil
1072 case PubKeyAlgoEd448:
1073 ed448PublicKey := pk.PublicKey.(*ed448.PublicKey)
1074 if !ed448.Verify(ed448PublicKey, hashBytes, sig.EdSig) {
1075 return errors.SignatureError("ed448 verification failure")
1076 }
1077 return nil
1078 case PubKeyAlgoMldsa65Ed25519, PubKeyAlgoMldsa87Ed448:
1079 mldsaEddsaPublicKey := pk.PublicKey.(*mldsa_eddsa.PublicKey)
1080 if !mldsa_eddsa.Verify(mldsaEddsaPublicKey, hashBytes, sig.MldsaSig, sig.EdSig) {
1081 return errors.SignatureError("MldsaEddsa verification failure")
1082 }
1083 return nil
1084 case PubKeyAlgoSlhdsaShake128s, PubKeyAlgoSlhdsaShake128f, PubKeyAlgoSlhdsaShake256s:
1085 slhDsaPublicKey := pk.PublicKey.(*slhdsa.PublicKey)
1086 if !slhdsa.Verify(slhDsaPublicKey, hashBytes, sig.SlhdsaSig) {
1087 return errors.SignatureError("Slhdsa verification failure")
1088 }
1089 return nil
1090 default:
1091 return errors.SignatureError("Unsupported public key algorithm used in signature")
1092 }
1093 }
1094
1095 // keySignatureHash returns a Hash of the message that needs to be signed for
1096 // pk to assert a subkey relationship to signed.
1097 func keySignatureHash(pk, signed signingKey, hashFunc hash.Hash) (h hash.Hash, err error) {
1098 h = hashFunc
1099
1100 // RFC 4880, section 5.2.4
1101 err = pk.SerializeForHash(h)
1102 if err != nil {
1103 return nil, err
1104 }
1105
1106 err = signed.SerializeForHash(h)
1107 return
1108 }
1109
1110 // VerifyKeyHashTag returns nil iff sig appears to be a plausible signature over this
1111 // primary key and subkey, based solely on its HashTag.
1112 func (pk *PublicKey) VerifyKeyHashTag(signed *PublicKey, sig *Signature) error {
1113 preparedHash, err := sig.PrepareVerify()
1114 if err != nil {
1115 return err
1116 }
1117 h, err := keySignatureHash(pk, signed, preparedHash)
1118 if err != nil {
1119 return err
1120 }
1121 return VerifyHashTag(h, sig)
1122 }
1123
1124 // VerifyKeySignature returns nil iff sig is a valid signature, made by this
1125 // public key, of signed.
1126 func (pk *PublicKey) VerifyKeySignature(signed *PublicKey, sig *Signature) error {
1127 preparedHash, err := sig.PrepareVerify()
1128 if err != nil {
1129 return err
1130 }
1131 h, err := keySignatureHash(pk, signed, preparedHash)
1132 if err != nil {
1133 return err
1134 }
1135 if err = pk.VerifySignature(h, sig); err != nil {
1136 return err
1137 }
1138
1139 if sig.FlagSign {
1140 // Signing subkeys must be cross-signed. See
1141 // https://www.gnupg.org/faq/subkey-cross-certify.html.
1142 if sig.EmbeddedSignature == nil {
1143 return errors.StructuralError("signing subkey is missing cross-signature")
1144 }
1145 preparedHashEmbedded, err := sig.EmbeddedSignature.PrepareVerify()
1146 if err != nil {
1147 return err
1148 }
1149 // Verify the cross-signature. This is calculated over the same
1150 // data as the main signature, so we cannot just recursively
1151 // call signed.VerifyKeySignature(...)
1152 if h, err = keySignatureHash(pk, signed, preparedHashEmbedded); err != nil {
1153 return errors.StructuralError("error while hashing for cross-signature: " + err.Error())
1154 }
1155 if err := signed.VerifySignature(h, sig.EmbeddedSignature); err != nil {
1156 return errors.StructuralError("error while verifying cross-signature: " + err.Error())
1157 }
1158 }
1159
1160 return nil
1161 }
1162
1163 func keyRevocationHash(pk signingKey, hashFunc hash.Hash) (err error) {
1164 return pk.SerializeForHash(hashFunc)
1165 }
1166
1167 // VerifyRevocationHashTag returns nil iff sig appears to be a plausible signature
1168 // over this public key, based solely on its HashTag.
1169 func (pk *PublicKey) VerifyRevocationHashTag(sig *Signature) (err error) {
1170 preparedHash, err := sig.PrepareVerify()
1171 if err != nil {
1172 return err
1173 }
1174 if err = keyRevocationHash(pk, preparedHash); err != nil {
1175 return err
1176 }
1177 return VerifyHashTag(preparedHash, sig)
1178 }
1179
1180 // VerifyRevocationSignature returns nil iff sig is a valid signature, made by this
1181 // public key.
1182 func (pk *PublicKey) VerifyRevocationSignature(sig *Signature) (err error) {
1183 preparedHash, err := sig.PrepareVerify()
1184 if err != nil {
1185 return err
1186 }
1187 if err = keyRevocationHash(pk, preparedHash); err != nil {
1188 return err
1189 }
1190 return pk.VerifySignature(preparedHash, sig)
1191 }
1192
1193 // VerifySubkeyRevocationSignature returns nil iff sig is a valid subkey revocation signature,
1194 // made by this public key, of signed.
1195 func (pk *PublicKey) VerifySubkeyRevocationSignature(sig *Signature, signed *PublicKey) (err error) {
1196 preparedHash, err := sig.PrepareVerify()
1197 if err != nil {
1198 return err
1199 }
1200 h, err := keySignatureHash(pk, signed, preparedHash)
1201 if err != nil {
1202 return err
1203 }
1204 return pk.VerifySignature(h, sig)
1205 }
1206
1207 // userIdSignatureHash returns a Hash of the message that needs to be signed
1208 // to assert that pk is a valid key for id.
1209 func userIdSignatureHash(id string, pk *PublicKey, h hash.Hash) (err error) {
1210
1211 // RFC 4880, section 5.2.4
1212 if err := pk.SerializeSignaturePrefix(h); err != nil {
1213 return err
1214 }
1215 if err := pk.serializeWithoutHeaders(h); err != nil {
1216 return err
1217 }
1218
1219 var buf [5]byte
1220 buf[0] = 0xb4
1221 buf[1] = byte(len(id) >> 24)
1222 buf[2] = byte(len(id) >> 16)
1223 buf[3] = byte(len(id) >> 8)
1224 buf[4] = byte(len(id))
1225 h.Write(buf[:])
1226 h.Write([]byte(id))
1227
1228 return nil
1229 }
1230
1231 // directKeySignatureHash returns a Hash of the message that needs to be signed.
1232 func directKeySignatureHash(pk *PublicKey, h hash.Hash) (err error) {
1233 return pk.SerializeForHash(h)
1234 }
1235
1236 // VerifyUserIdHashTag returns nil iff sig appears to be a plausible signature over this
1237 // public key and UserId, based solely on its HashTag
1238 func (pk *PublicKey) VerifyUserIdHashTag(id string, sig *Signature) (err error) {
1239 preparedHash, err := sig.PrepareVerify()
1240 if err != nil {
1241 return err
1242 }
1243 err = userIdSignatureHash(id, pk, preparedHash)
1244 if err != nil {
1245 return err
1246 }
1247 return VerifyHashTag(preparedHash, sig)
1248 }
1249
1250 // VerifyUserIdSignature returns nil iff sig is a valid signature, made by this
1251 // public key, that id is the identity of pub.
1252 func (pk *PublicKey) VerifyUserIdSignature(id string, pub *PublicKey, sig *Signature) (err error) {
1253 h, err := sig.PrepareVerify()
1254 if err != nil {
1255 return err
1256 }
1257 if err := userIdSignatureHash(id, pub, h); err != nil {
1258 return err
1259 }
1260 return pk.VerifySignature(h, sig)
1261 }
1262
1263 // VerifyDirectKeySignature returns nil iff sig is a valid signature, made by this
1264 // public key.
1265 func (pk *PublicKey) VerifyDirectKeySignature(sig *Signature) (err error) {
1266 h, err := sig.PrepareVerify()
1267 if err != nil {
1268 return err
1269 }
1270 if err := directKeySignatureHash(pk, h); err != nil {
1271 return err
1272 }
1273 return pk.VerifySignature(h, sig)
1274 }
1275
1276 // KeyIdString returns the public key's fingerprint in capital hex
1277 // (e.g. "6C7EE1B8621CC013").
1278 func (pk *PublicKey) KeyIdString() string {
1279 return fmt.Sprintf("%016X", pk.KeyId)
1280 }
1281
1282 // KeyIdShortString returns the short form of public key's fingerprint
1283 // in capital hex, as shown by gpg --list-keys (e.g. "621CC013").
1284 // This function will return the full key id for v5 and v6 keys
1285 // since the short key id is undefined for them.
1286 func (pk *PublicKey) KeyIdShortString() string {
1287 if pk.Version >= 5 {
1288 return pk.KeyIdString()
1289 }
1290 return fmt.Sprintf("%X", pk.Fingerprint[16:20])
1291 }
1292
1293 // BitLength returns the bit length for the given public key.
1294 func (pk *PublicKey) BitLength() (bitLength uint16, err error) {
1295 switch pk.PubKeyAlgo {
1296 case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly:
1297 bitLength = pk.n.BitLength()
1298 case PubKeyAlgoDSA:
1299 bitLength = pk.p.BitLength()
1300 case PubKeyAlgoElGamal:
1301 bitLength = pk.p.BitLength()
1302 case PubKeyAlgoECDSA:
1303 bitLength = pk.p.BitLength()
1304 case PubKeyAlgoECDH:
1305 bitLength = pk.p.BitLength()
1306 case PubKeyAlgoEdDSA:
1307 bitLength = pk.p.BitLength()
1308 case PubKeyAlgoX25519:
1309 bitLength = x25519.KeySize * 8
1310 case PubKeyAlgoX448:
1311 bitLength = x448.KeySize * 8
1312 case PubKeyAlgoEd25519:
1313 bitLength = ed25519.PublicKeySize * 8
1314 case PubKeyAlgoEd448:
1315 bitLength = ed448.PublicKeySize * 8
1316 case PubKeyAlgoMlkem768X25519, PubKeyAlgoMlkem1024X448:
1317 publicKey := pk.PublicKey.(*mlkem_ecdh.PublicKey)
1318 bitLength = uint16(publicKey.Mlkem.PublicKeySize() * 8)
1319 case PubKeyAlgoMldsa65Ed25519, PubKeyAlgoMldsa87Ed448:
1320 publicKey := pk.PublicKey.(*mldsa_eddsa.PublicKey)
1321 bitLength = uint16(publicKey.Mldsa.PublicKeySize() * 8)
1322 case PubKeyAlgoSlhdsaShake128s, PubKeyAlgoSlhdsaShake128f, PubKeyAlgoSlhdsaShake256s:
1323 publicKey := pk.PublicKey.(*slhdsa.PublicKey)
1324 bitLength = uint16(publicKey.Slhdsa.PublicKeySize() * 8)
1325 default:
1326 err = errors.InvalidArgumentError("bad public-key algorithm")
1327 }
1328 return
1329 }
1330
1331 // Curve returns the used elliptic curve of this public key.
1332 // Returns an error if no elliptic curve is used.
1333 func (pk *PublicKey) Curve() (curve Curve, err error) {
1334 switch pk.PubKeyAlgo {
1335 case PubKeyAlgoECDSA, PubKeyAlgoECDH, PubKeyAlgoEdDSA:
1336 curveInfo := ecc.FindByOid(pk.oid)
1337 if curveInfo == nil {
1338 return "", errors.UnsupportedError(fmt.Sprintf("unknown oid: %x", pk.oid))
1339 }
1340 curve = Curve(curveInfo.GenName)
1341 case PubKeyAlgoEd25519, PubKeyAlgoX25519:
1342 curve = Curve25519
1343 case PubKeyAlgoEd448, PubKeyAlgoX448:
1344 curve = Curve448
1345 default:
1346 err = errors.InvalidArgumentError("public key does not operate with an elliptic curve")
1347 }
1348 return
1349 }
1350
1351 // KeyExpired returns whether sig is a self-signature of a key that has
1352 // expired or is created in the future.
1353 func (pk *PublicKey) KeyExpired(sig *Signature, currentTime time.Time) bool {
1354 if pk.CreationTime.Unix() > currentTime.Unix() {
1355 return true
1356 }
1357 if sig.KeyLifetimeSecs == nil || *sig.KeyLifetimeSecs == 0 {
1358 return false
1359 }
1360 expiry := pk.CreationTime.Add(time.Duration(*sig.KeyLifetimeSecs) * time.Second)
1361 return currentTime.Unix() > expiry.Unix()
1362 }
1363
1364 // IsPQ returns true if the algorithm of this public key is Post-Quantum safe.
1365 func (pg *PublicKey) IsPQ() bool {
1366 switch pg.PubKeyAlgo {
1367 case PubKeyAlgoMlkem768X25519, PubKeyAlgoMlkem1024X448,
1368 PubKeyAlgoMldsa65Ed25519, PubKeyAlgoMldsa87Ed448,
1369 PubKeyAlgoSlhdsaShake128s, PubKeyAlgoSlhdsaShake128f, PubKeyAlgoSlhdsaShake256s:
1370 return true
1371 default:
1372 return false
1373 }
1374 }
1375
1376 func GetMatchingMlkem(algId PublicKeyAlgorithm) (PublicKeyAlgorithm, error) {
1377 switch algId {
1378 case PubKeyAlgoMldsa65Ed25519, PubKeyAlgoSlhdsaShake128s, PubKeyAlgoSlhdsaShake128f:
1379 return PubKeyAlgoMlkem768X25519, nil
1380 case PubKeyAlgoMldsa87Ed448, PubKeyAlgoSlhdsaShake256s:
1381 return PubKeyAlgoMlkem1024X448, nil
1382 default:
1383 return 0, goerrors.New("packet: unsupported pq public key algorithm")
1384 }
1385 }
1386
1387 // GetMlkemFromAlgID returns the ML-KEM instance from the matching KEM
1388 func GetMlkemFromAlgID(algId PublicKeyAlgorithm) (kem.Scheme, error) {
1389 switch algId {
1390 case PubKeyAlgoMlkem768X25519:
1391 return mlkem768.Scheme(), nil
1392 case PubKeyAlgoMlkem1024X448:
1393 return mlkem1024.Scheme(), nil
1394 default:
1395 return nil, goerrors.New("packet: unsupported ML-KEM public key algorithm")
1396 }
1397 }
1398
1399 // GetSlhdsaSchemeFromAlgID returns the SLH-DSA instance from the matching KEM
1400 func GetSlhdsaSchemeFromAlgID(algId PublicKeyAlgorithm) (sign.Scheme, error) {
1401 switch algId {
1402 case PubKeyAlgoSlhdsaShake128s:
1403 return slhdsaCircl.SHAKE_128s.Scheme(), nil
1404 case PubKeyAlgoSlhdsaShake128f:
1405 return slhdsaCircl.SHAKE_128f.Scheme(), nil
1406 case PubKeyAlgoSlhdsaShake256s:
1407 return slhdsaCircl.SHAKE_256s.Scheme(), nil
1408 default:
1409 return nil, goerrors.New("packet: unsupported SLH-DSA public key algorithm")
1410 }
1411 }
1412
1413 // GetECDHCurveFromAlgID returns the ECDH curve instance from the matching KEM
1414 func GetECDHCurveFromAlgID(algId PublicKeyAlgorithm) (ecc.ECDHCurve, error) {
1415 switch algId {
1416 case PubKeyAlgoMlkem768X25519:
1417 return ecc.NewCurve25519(), nil
1418 case PubKeyAlgoMlkem1024X448:
1419 return ecc.NewX448(), nil
1420 default:
1421 return nil, goerrors.New("packet: unsupported ECDH public key algorithm")
1422 }
1423 }
1424
1425 func GetEdDSACurveFromAlgID(algId PublicKeyAlgorithm) (ecc.EdDSACurve, error) {
1426 switch algId {
1427 case PubKeyAlgoMldsa65Ed25519:
1428 return ecc.NewEd25519(), nil
1429 case PubKeyAlgoMldsa87Ed448:
1430 return ecc.NewEd448(), nil
1431 default:
1432 return nil, goerrors.New("packet: unsupported EdDSA public key algorithm")
1433 }
1434 }
1435
1436 func GetMldsaFromAlgID(algId PublicKeyAlgorithm) (sign.Scheme, error) {
1437 switch algId {
1438 case PubKeyAlgoMldsa65Ed25519:
1439 return mldsa65.Scheme(), nil
1440 case PubKeyAlgoMldsa87Ed448:
1441 return mldsa87.Scheme(), nil
1442 default:
1443 return nil, goerrors.New("packet: unsupported ML-DSA public key algorithm")
1444 }
1445 }