Debian Codegraph @

openpgp/packet/private_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 "bytes"
9 "crypto"
10 "crypto/cipher"
11 "crypto/dsa"
12 "crypto/rsa"
13 "crypto/sha1"
14 "crypto/sha256"
15 "crypto/subtle"
16 goerrors "errors"
17 "fmt"
18 "io"
19 "math/big"
20 "strconv"
21 "time"
22
23 "github.com/ProtonMail/go-crypto/openpgp/ecdh"
24 "github.com/ProtonMail/go-crypto/openpgp/ecdsa"
25 "github.com/ProtonMail/go-crypto/openpgp/ed25519"
26 "github.com/ProtonMail/go-crypto/openpgp/ed448"
27 "github.com/ProtonMail/go-crypto/openpgp/eddsa"
28 "github.com/ProtonMail/go-crypto/openpgp/elgamal"
29 "github.com/ProtonMail/go-crypto/openpgp/errors"
30 "github.com/ProtonMail/go-crypto/openpgp/internal/encoding"
31 "github.com/ProtonMail/go-crypto/openpgp/mldsa_eddsa"
32 "github.com/ProtonMail/go-crypto/openpgp/mlkem_ecdh"
33 "github.com/ProtonMail/go-crypto/openpgp/s2k"
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 "golang.org/x/crypto/hkdf"
38 )
39
40 // PrivateKey represents a possibly encrypted private key. See RFC 4880,
41 // section 5.5.3.
42 type PrivateKey struct {
43 PublicKey
44 Encrypted bool // if true then the private key is unavailable until Decrypt has been called.
45 encryptedData []byte
46 cipher CipherFunction
47 s2k func(out, in []byte)
48 aead AEADMode // only relevant if S2KAEAD is enabled
49 // An *{rsa|dsa|elgamal|ecdh|ecdsa|ed25519|ed448}.PrivateKey or
50 // crypto.Signer/crypto.Decrypter (Decryptor RSA only).
51 PrivateKey interface{}
52 iv []byte
53
54 // Type of encryption of the S2K packet
55 // Allowed values are 0 (Not encrypted), 253 (AEAD), 254 (SHA1), or
56 // 255 (2-byte checksum)
57 s2kType S2KType
58 // Full parameters of the S2K packet
59 s2kParams *s2k.Params
60 }
61
62 // S2KType s2k packet type
63 type S2KType uint8
64
65 const (
66 // S2KNON unencrypt
67 S2KNON S2KType = 0
68 // S2KAEAD use authenticated encryption
69 S2KAEAD S2KType = 253
70 // S2KSHA1 sha1 sum check
71 S2KSHA1 S2KType = 254
72 // S2KCHECKSUM sum check
73 S2KCHECKSUM S2KType = 255
74 )
75
76 func NewRSAPrivateKey(creationTime time.Time, priv *rsa.PrivateKey) *PrivateKey {
77 pk := new(PrivateKey)
78 pk.PublicKey = *NewRSAPublicKey(creationTime, &priv.PublicKey)
79 pk.PrivateKey = priv
80 return pk
81 }
82
83 func NewDSAPrivateKey(creationTime time.Time, priv *dsa.PrivateKey) *PrivateKey {
84 pk := new(PrivateKey)
85 pk.PublicKey = *NewDSAPublicKey(creationTime, &priv.PublicKey)
86 pk.PrivateKey = priv
87 return pk
88 }
89
90 func NewElGamalPrivateKey(creationTime time.Time, priv *elgamal.PrivateKey) *PrivateKey {
91 pk := new(PrivateKey)
92 pk.PublicKey = *NewElGamalPublicKey(creationTime, &priv.PublicKey)
93 pk.PrivateKey = priv
94 return pk
95 }
96
97 func NewECDSAPrivateKey(creationTime time.Time, priv *ecdsa.PrivateKey) *PrivateKey {
98 pk := new(PrivateKey)
99 pk.PublicKey = *NewECDSAPublicKey(creationTime, &priv.PublicKey)
100 pk.PrivateKey = priv
101 return pk
102 }
103
104 func NewEdDSAPrivateKey(creationTime time.Time, priv *eddsa.PrivateKey) *PrivateKey {
105 pk := new(PrivateKey)
106 pk.PublicKey = *NewEdDSAPublicKey(creationTime, &priv.PublicKey)
107 pk.PrivateKey = priv
108 return pk
109 }
110
111 func NewECDHPrivateKey(creationTime time.Time, priv *ecdh.PrivateKey) *PrivateKey {
112 pk := new(PrivateKey)
113 pk.PublicKey = *NewECDHPublicKey(creationTime, &priv.PublicKey)
114 pk.PrivateKey = priv
115 return pk
116 }
117
118 func NewX25519PrivateKey(creationTime time.Time, priv *x25519.PrivateKey) *PrivateKey {
119 pk := new(PrivateKey)
120 pk.PublicKey = *NewX25519PublicKey(creationTime, &priv.PublicKey)
121 pk.PrivateKey = priv
122 return pk
123 }
124
125 func NewX448PrivateKey(creationTime time.Time, priv *x448.PrivateKey) *PrivateKey {
126 pk := new(PrivateKey)
127 pk.PublicKey = *NewX448PublicKey(creationTime, &priv.PublicKey)
128 pk.PrivateKey = priv
129 return pk
130 }
131
132 func NewEd25519PrivateKey(creationTime time.Time, priv *ed25519.PrivateKey) *PrivateKey {
133 pk := new(PrivateKey)
134 pk.PublicKey = *NewEd25519PublicKey(creationTime, &priv.PublicKey)
135 pk.PrivateKey = priv
136 return pk
137 }
138
139 func NewEd448PrivateKey(creationTime time.Time, priv *ed448.PrivateKey) *PrivateKey {
140 pk := new(PrivateKey)
141 pk.PublicKey = *NewEd448PublicKey(creationTime, &priv.PublicKey)
142 pk.PrivateKey = priv
143 return pk
144 }
145
146 // NewSignerPrivateKey creates a PrivateKey from a crypto.Signer that
147 // implements RSA, ECDSA or EdDSA.
148 func NewSignerPrivateKey(creationTime time.Time, signer interface{}) *PrivateKey {
149 pk := new(PrivateKey)
150 // In general, the public Keys should be used as pointers. We still
151 // type-switch on the values, for backwards-compatibility.
152 switch pubkey := signer.(type) {
153 case *rsa.PrivateKey:
154 pk.PublicKey = *NewRSAPublicKey(creationTime, &pubkey.PublicKey)
155 case rsa.PrivateKey:
156 pk.PublicKey = *NewRSAPublicKey(creationTime, &pubkey.PublicKey)
157 case *ecdsa.PrivateKey:
158 pk.PublicKey = *NewECDSAPublicKey(creationTime, &pubkey.PublicKey)
159 case ecdsa.PrivateKey:
160 pk.PublicKey = *NewECDSAPublicKey(creationTime, &pubkey.PublicKey)
161 case *eddsa.PrivateKey:
162 pk.PublicKey = *NewEdDSAPublicKey(creationTime, &pubkey.PublicKey)
163 case eddsa.PrivateKey:
164 pk.PublicKey = *NewEdDSAPublicKey(creationTime, &pubkey.PublicKey)
165 case *ed25519.PrivateKey:
166 pk.PublicKey = *NewEd25519PublicKey(creationTime, &pubkey.PublicKey)
167 case ed25519.PrivateKey:
168 pk.PublicKey = *NewEd25519PublicKey(creationTime, &pubkey.PublicKey)
169 case *ed448.PrivateKey:
170 pk.PublicKey = *NewEd448PublicKey(creationTime, &pubkey.PublicKey)
171 case ed448.PrivateKey:
172 pk.PublicKey = *NewEd448PublicKey(creationTime, &pubkey.PublicKey)
173 case *mldsa_eddsa.PrivateKey:
174 pk.PublicKey = *NewMldsaEddsaPublicKey(creationTime, &pubkey.PublicKey)
175 case *slhdsa.PrivateKey:
176 pk.PublicKey = *NewSlhdsaPublicKey(creationTime, &pubkey.PublicKey)
177 default:
178 panic("openpgp: unknown signer type in NewSignerPrivateKey")
179 }
180 pk.PrivateKey = signer
181 return pk
182 }
183
184 // NewDecrypterPrivateKey creates a PrivateKey from a *{rsa|elgamal|ecdh|x25519|x448|mlkem_ecdh}.PrivateKey.
185 func NewDecrypterPrivateKey(creationTime time.Time, decrypter interface{}) *PrivateKey {
186 pk := new(PrivateKey)
187 switch priv := decrypter.(type) {
188 case *rsa.PrivateKey:
189 pk.PublicKey = *NewRSAPublicKey(creationTime, &priv.PublicKey)
190 case *elgamal.PrivateKey:
191 pk.PublicKey = *NewElGamalPublicKey(creationTime, &priv.PublicKey)
192 case *ecdh.PrivateKey:
193 pk.PublicKey = *NewECDHPublicKey(creationTime, &priv.PublicKey)
194 case *x25519.PrivateKey:
195 pk.PublicKey = *NewX25519PublicKey(creationTime, &priv.PublicKey)
196 case *x448.PrivateKey:
197 pk.PublicKey = *NewX448PublicKey(creationTime, &priv.PublicKey)
198 case *mlkem_ecdh.PrivateKey:
199 pk.PublicKey = *NewMlkemEcdhPublicKey(creationTime, &priv.PublicKey)
200 default:
201 panic("openpgp: unknown decrypter type in NewDecrypterPrivateKey")
202 }
203 pk.PrivateKey = decrypter
204 return pk
205 }
206
207 func (pk *PrivateKey) parse(r io.Reader) (err error) {
208 err = (&pk.PublicKey).parse(r)
209 if err != nil {
210 return
211 }
212 v5 := pk.PublicKey.Version == 5
213 v6 := pk.PublicKey.Version == 6
214
215 if V5Disabled && v5 {
216 return errors.UnsupportedError("support for parsing v5 entities is disabled; build with `-tags v5` if needed")
217 }
218
219 var buf [1]byte
220 _, err = readFull(r, buf[:])
221 if err != nil {
222 return
223 }
224 pk.s2kType = S2KType(buf[0])
225 var optCount [1]byte
226 if v5 || (v6 && pk.s2kType != S2KNON) {
227 if _, err = readFull(r, optCount[:]); err != nil {
228 return
229 }
230 }
231
232 switch pk.s2kType {
233 case S2KNON:
234 pk.s2k = nil
235 pk.Encrypted = false
236 case S2KSHA1, S2KCHECKSUM, S2KAEAD:
237 if (v5 || v6) && pk.s2kType == S2KCHECKSUM {
238 return errors.StructuralError(fmt.Sprintf("wrong s2k identifier for version %d", pk.Version))
239 }
240 _, err = readFull(r, buf[:])
241 if err != nil {
242 return
243 }
244 pk.cipher = CipherFunction(buf[0])
245 if pk.cipher != 0 && !pk.cipher.IsSupported() {
246 return errors.UnsupportedError("unsupported cipher function in private key")
247 }
248 // [Optional] If string-to-key usage octet was 253,
249 // a one-octet AEAD algorithm.
250 if pk.s2kType == S2KAEAD {
251 _, err = readFull(r, buf[:])
252 if err != nil {
253 return
254 }
255 pk.aead = AEADMode(buf[0])
256 if !pk.aead.IsSupported() {
257 return errors.UnsupportedError("unsupported aead mode in private key")
258 }
259 }
260
261 // [Optional] Only for a version 6 packet,
262 // and if string-to-key usage octet was 255, 254, or 253,
263 // an one-octet count of the following field.
264 if v6 {
265 _, err = readFull(r, buf[:])
266 if err != nil {
267 return
268 }
269 }
270
271 pk.s2kParams, err = s2k.ParseIntoParams(r)
272 if err != nil {
273 return
274 }
275 if pk.s2kParams.Dummy() {
276 return
277 }
278 if !pk.cipher.IsSupported() {
279 return errors.UnsupportedError("unsupported cipher function in private key")
280 }
281 if pk.s2kParams.Mode() == s2k.Argon2S2K && pk.s2kType != S2KAEAD {
282 return errors.StructuralError("using Argon2 S2K without AEAD is not allowed")
283 }
284 if pk.s2kParams.Mode() == s2k.SimpleS2K && pk.Version == 6 {
285 return errors.StructuralError("using Simple S2K with version 6 keys is not allowed")
286 }
287 pk.s2k, err = pk.s2kParams.Function()
288 if err != nil {
289 return
290 }
291 pk.Encrypted = true
292 default:
293 return errors.UnsupportedError("deprecated s2k function in private key")
294 }
295
296 if pk.Encrypted {
297 var ivSize int
298 // If the S2K usage octet was 253, the IV is of the size expected by the AEAD mode,
299 // unless it's a version 5 key, in which case it's the size of the symmetric cipher's block size.
300 // For all other S2K modes, it's always the block size.
301 if !v5 && pk.s2kType == S2KAEAD {
302 ivSize = pk.aead.IvLength()
303 } else {
304 ivSize = pk.cipher.blockSize()
305 }
306
307 if ivSize == 0 {
308 return errors.UnsupportedError("unsupported cipher in private key: " + strconv.Itoa(int(pk.cipher)))
309 }
310 pk.iv = make([]byte, ivSize)
311 _, err = readFull(r, pk.iv)
312 if err != nil {
313 return
314 }
315 if v5 && pk.s2kType == S2KAEAD {
316 if pk.aead.IvLength() > len(pk.iv) {
317 return errors.StructuralError("invalid aead IV length for v5 private key")
318 }
319 pk.iv = pk.iv[:pk.aead.IvLength()]
320 }
321 }
322
323 var privateKeyData []byte
324 if v5 {
325 var n [4]byte /* secret material four octet count */
326 _, err = readFull(r, n[:])
327 if err != nil {
328 return
329 }
330 count := uint32(uint32(n[0])<<24 | uint32(n[1])<<16 | uint32(n[2])<<8 | uint32(n[3]))
331 if !pk.Encrypted {
332 count = count + 2 /* two octet checksum */
333 }
334 privateKeyData = make([]byte, count)
335 _, err = readFull(r, privateKeyData)
336 if err != nil {
337 return
338 }
339 } else {
340 privateKeyData, err = io.ReadAll(r)
341 if err != nil {
342 return
343 }
344 }
345 if !pk.Encrypted {
346 if len(privateKeyData) < 2 {
347 return errors.StructuralError("truncated private key data")
348 }
349 if pk.Version != 6 {
350 // checksum
351 var sum uint16
352 for i := 0; i < len(privateKeyData)-2; i++ {
353 sum += uint16(privateKeyData[i])
354 }
355 if privateKeyData[len(privateKeyData)-2] != uint8(sum>>8) ||
356 privateKeyData[len(privateKeyData)-1] != uint8(sum) {
357 return errors.StructuralError("private key checksum failure")
358 }
359 privateKeyData = privateKeyData[:len(privateKeyData)-2]
360 return pk.parsePrivateKey(privateKeyData)
361 } else {
362 // No checksum
363 return pk.parsePrivateKey(privateKeyData)
364 }
365 }
366
367 pk.encryptedData = privateKeyData
368 return
369 }
370
371 // Dummy returns true if the private key is a dummy key. This is a GNU extension.
372 func (pk *PrivateKey) Dummy() bool {
373 return pk.s2kParams.Dummy()
374 }
375
376 func mod64kHash(d []byte) uint16 {
377 var h uint16
378 for _, b := range d {
379 h += uint16(b)
380 }
381 return h
382 }
383
384 func (pk *PrivateKey) Serialize(w io.Writer) (err error) {
385 contents := bytes.NewBuffer(nil)
386 err = pk.PublicKey.serializeWithoutHeaders(contents)
387 if err != nil {
388 return
389 }
390 if _, err = contents.Write([]byte{uint8(pk.s2kType)}); err != nil {
391 return
392 }
393
394 optional := bytes.NewBuffer(nil)
395 if pk.Encrypted || pk.Dummy() {
396 // [Optional] If string-to-key usage octet was 255, 254, or 253,
397 // a one-octet symmetric encryption algorithm.
398 if _, err = optional.Write([]byte{uint8(pk.cipher)}); err != nil {
399 return
400 }
401 // [Optional] If string-to-key usage octet was 253,
402 // a one-octet AEAD algorithm.
403 if pk.s2kType == S2KAEAD {
404 if _, err = optional.Write([]byte{uint8(pk.aead)}); err != nil {
405 return
406 }
407 }
408
409 s2kBuffer := bytes.NewBuffer(nil)
410 if err := pk.s2kParams.Serialize(s2kBuffer); err != nil {
411 return err
412 }
413 // [Optional] Only for a version 6 packet, and if string-to-key
414 // usage octet was 255, 254, or 253, an one-octet
415 // count of the following field.
416 if pk.Version == 6 {
417 if _, err = optional.Write([]byte{uint8(s2kBuffer.Len())}); err != nil {
418 return
419 }
420 }
421 // [Optional] If string-to-key usage octet was 255, 254, or 253,
422 // a string-to-key (S2K) specifier. The length of the string-to-key specifier
423 // depends on its type
424 if _, err = io.Copy(optional, s2kBuffer); err != nil {
425 return
426 }
427
428 // IV
429 if pk.Encrypted {
430 if _, err = optional.Write(pk.iv); err != nil {
431 return
432 }
433 if pk.Version == 5 && pk.s2kType == S2KAEAD {
434 // Add padding for version 5
435 padding := make([]byte, pk.cipher.blockSize()-len(pk.iv))
436 if _, err = optional.Write(padding); err != nil {
437 return
438 }
439 }
440 }
441 }
442 if pk.Version == 5 || (pk.Version == 6 && pk.s2kType != S2KNON) {
443 contents.Write([]byte{uint8(optional.Len())})
444 }
445
446 if _, err := io.Copy(contents, optional); err != nil {
447 return err
448 }
449
450 if !pk.Dummy() {
451 l := 0
452 var priv []byte
453 if !pk.Encrypted {
454 buf := bytes.NewBuffer(nil)
455 err = pk.serializePrivateKey(buf)
456 if err != nil {
457 return err
458 }
459 l = buf.Len()
460 if pk.Version != 6 {
461 checksum := mod64kHash(buf.Bytes())
462 buf.Write([]byte{byte(checksum >> 8), byte(checksum)})
463 }
464 priv = buf.Bytes()
465 } else {
466 priv, l = pk.encryptedData, len(pk.encryptedData)
467 }
468
469 if pk.Version == 5 {
470 contents.Write([]byte{byte(l >> 24), byte(l >> 16), byte(l >> 8), byte(l)})
471 }
472 contents.Write(priv)
473 }
474
475 ptype := packetTypePrivateKey
476 if pk.IsSubkey {
477 ptype = packetTypePrivateSubkey
478 }
479 err = serializeHeader(w, ptype, contents.Len())
480 if err != nil {
481 return
482 }
483 _, err = io.Copy(w, contents)
484 if err != nil {
485 return
486 }
487 return
488 }
489
490 func serializeRSAPrivateKey(w io.Writer, priv *rsa.PrivateKey) error {
491 if _, err := w.Write(new(encoding.MPI).SetBig(priv.D).EncodedBytes()); err != nil {
492 return err
493 }
494 if _, err := w.Write(new(encoding.MPI).SetBig(priv.Primes[1]).EncodedBytes()); err != nil {
495 return err
496 }
497 if _, err := w.Write(new(encoding.MPI).SetBig(priv.Primes[0]).EncodedBytes()); err != nil {
498 return err
499 }
500 _, err := w.Write(new(encoding.MPI).SetBig(priv.Precomputed.Qinv).EncodedBytes())
501 return err
502 }
503
504 func serializeDSAPrivateKey(w io.Writer, priv *dsa.PrivateKey) error {
505 _, err := w.Write(new(encoding.MPI).SetBig(priv.X).EncodedBytes())
506 return err
507 }
508
509 func serializeElGamalPrivateKey(w io.Writer, priv *elgamal.PrivateKey) error {
510 _, err := w.Write(new(encoding.MPI).SetBig(priv.X).EncodedBytes())
511 return err
512 }
513
514 func serializeECDSAPrivateKey(w io.Writer, priv *ecdsa.PrivateKey) error {
515 _, err := w.Write(encoding.NewMPI(priv.MarshalIntegerSecret()).EncodedBytes())
516 return err
517 }
518
519 func serializeEdDSAPrivateKey(w io.Writer, priv *eddsa.PrivateKey) error {
520 _, err := w.Write(encoding.NewMPI(priv.MarshalByteSecret()).EncodedBytes())
521 return err
522 }
523
524 func serializeECDHPrivateKey(w io.Writer, priv *ecdh.PrivateKey) error {
525 _, err := w.Write(encoding.NewMPI(priv.MarshalByteSecret()).EncodedBytes())
526 return err
527 }
528
529 func serializeX25519PrivateKey(w io.Writer, priv *x25519.PrivateKey) error {
530 _, err := w.Write(priv.Secret)
531 return err
532 }
533
534 func serializeX448PrivateKey(w io.Writer, priv *x448.PrivateKey) error {
535 _, err := w.Write(priv.Secret)
536 return err
537 }
538
539 func serializeEd25519PrivateKey(w io.Writer, priv *ed25519.PrivateKey) error {
540 _, err := w.Write(priv.MarshalByteSecret())
541 return err
542 }
543
544 func serializeEd448PrivateKey(w io.Writer, priv *ed448.PrivateKey) error {
545 _, err := w.Write(priv.MarshalByteSecret())
546 return err
547 }
548
549 // serializeMlkemPrivateKey serializes a ML-KEM + ECC private key according to
550 // https://www.rfc-editor.org/rfc/rfc9980.html#name-key-material-packets
551 func serializeMlkemPrivateKey(w io.Writer, priv *mlkem_ecdh.PrivateKey) (err error) {
552 if _, err = w.Write(priv.SecretEc); err != nil {
553 return err
554 }
555 _, err = w.Write(priv.SecretMlkemSeed)
556 return err
557 }
558
559 // serializeMldsaEddsaPrivateKey serializes a ML-DSA + EdDSA private key according to
560 // https://www.rfc-editor.org/rfc/rfc9980.html#name-key-material-packets-2
561 func serializeMldsaEddsaPrivateKey(w io.Writer, priv *mldsa_eddsa.PrivateKey) error {
562 if _, err := w.Write(priv.SecretEc); err != nil {
563 return err
564 }
565 if _, err := w.Write(priv.SecretMldsaSeed); err != nil {
566 return err
567 }
568 return nil
569 }
570
571 // serializeSlhDsaPrivateKey serializes a SLH-DSA private key.
572 func serializeSlhDsaPrivateKey(w io.Writer, priv *slhdsa.PrivateKey) error {
573 marshalledKey, err := priv.SecretSlhdsa.MarshalBinary()
574 if err != nil {
575 return err
576 }
577 if _, err := w.Write(marshalledKey); err != nil {
578 return err
579 }
580 return nil
581 }
582
583 // decrypt decrypts an encrypted private key using a decryption key.
584 func (pk *PrivateKey) decrypt(decryptionKey []byte) error {
585 if pk.Dummy() {
586 return errors.ErrDummyPrivateKey("dummy key found")
587 }
588 if !pk.Encrypted {
589 return nil
590 }
591 block := pk.cipher.new(decryptionKey)
592 var data []byte
593 switch pk.s2kType {
594 case S2KAEAD:
595 aead, err := pk.aead.new(block)
596 if err != nil {
597 return err
598 }
599 additionalData, err := pk.additionalData()
600 if err != nil {
601 return err
602 }
603 // Decrypt the encrypted key material with aead
604 data, err = aead.Open(nil, pk.iv, pk.encryptedData, additionalData)
605 if err != nil {
606 return err
607 }
608 case S2KSHA1, S2KCHECKSUM:
609 cfb := cipher.NewCFBDecrypter(block, pk.iv)
610 data = make([]byte, len(pk.encryptedData))
611 cfb.XORKeyStream(data, pk.encryptedData)
612 if pk.s2kType == S2KSHA1 {
613 if len(data) < sha1.Size {
614 return errors.StructuralError("truncated private key data")
615 }
616 h := sha1.New()
617 h.Write(data[:len(data)-sha1.Size])
618 sum := h.Sum(nil)
619 if !bytes.Equal(sum, data[len(data)-sha1.Size:]) {
620 return errors.StructuralError("private key checksum failure")
621 }
622 data = data[:len(data)-sha1.Size]
623 } else {
624 if len(data) < 2 {
625 return errors.StructuralError("truncated private key data")
626 }
627 var sum uint16
628 for i := 0; i < len(data)-2; i++ {
629 sum += uint16(data[i])
630 }
631 if data[len(data)-2] != uint8(sum>>8) ||
632 data[len(data)-1] != uint8(sum) {
633 return errors.StructuralError("private key checksum failure")
634 }
635 data = data[:len(data)-2]
636 }
637 default:
638 return errors.InvalidArgumentError("invalid s2k type")
639 }
640
641 err := pk.parsePrivateKey(data)
642 if _, ok := err.(errors.KeyInvalidError); ok {
643 return errors.KeyInvalidError("invalid key parameters")
644 }
645 if err != nil {
646 return err
647 }
648
649 // Mark key as unencrypted
650 pk.s2kType = S2KNON
651 pk.s2k = nil
652 pk.Encrypted = false
653 pk.encryptedData = nil
654 return nil
655 }
656
657 func (pk *PrivateKey) decryptWithCache(passphrase []byte, keyCache *s2k.Cache) error {
658 if pk.Dummy() {
659 return errors.ErrDummyPrivateKey("dummy key found")
660 }
661 if !pk.Encrypted {
662 return nil
663 }
664
665 key, err := keyCache.GetOrComputeDerivedKey(passphrase, pk.s2kParams, pk.cipher.KeySize())
666 if err != nil {
667 return err
668 }
669 if pk.s2kType == S2KAEAD {
670 key = pk.applyHKDF(key)
671 }
672 return pk.decrypt(key)
673 }
674
675 // Decrypt decrypts an encrypted private key using a passphrase.
676 func (pk *PrivateKey) Decrypt(passphrase []byte) error {
677 if pk.Dummy() {
678 return errors.ErrDummyPrivateKey("dummy key found")
679 }
680 if !pk.Encrypted {
681 return nil
682 }
683
684 key := make([]byte, pk.cipher.KeySize())
685 pk.s2k(key, passphrase)
686 if pk.s2kType == S2KAEAD {
687 key = pk.applyHKDF(key)
688 }
689 return pk.decrypt(key)
690 }
691
692 // DecryptPrivateKeys decrypts all encrypted keys with the given config and passphrase.
693 // Avoids recomputation of similar s2k key derivations.
694 func DecryptPrivateKeys(keys []*PrivateKey, passphrase []byte) error {
695 // Create a cache to avoid recomputation of key derviations for the same passphrase.
696 s2kCache := &s2k.Cache{}
697 for _, key := range keys {
698 if key != nil && !key.Dummy() && key.Encrypted {
699 err := key.decryptWithCache(passphrase, s2kCache)
700 if err != nil {
701 return err
702 }
703 }
704 }
705 return nil
706 }
707
708 // encrypt encrypts an unencrypted private key.
709 func (pk *PrivateKey) encrypt(key []byte, params *s2k.Params, s2kType S2KType, cipherFunction CipherFunction, rand io.Reader) error {
710 if pk.Dummy() {
711 return errors.ErrDummyPrivateKey("dummy key found")
712 }
713 if pk.Encrypted {
714 return nil
715 }
716 // check if encryptionKey has the correct size
717 if len(key) != cipherFunction.KeySize() {
718 return errors.InvalidArgumentError("supplied encryption key has the wrong size")
719 }
720
721 if params.Mode() == s2k.Argon2S2K && s2kType != S2KAEAD {
722 return errors.InvalidArgumentError("using Argon2 S2K without AEAD is not allowed")
723 }
724 if params.Mode() != s2k.Argon2S2K && params.Mode() != s2k.IteratedSaltedS2K &&
725 params.Mode() != s2k.SaltedS2K { // only allowed for high-entropy passphrases
726 return errors.InvalidArgumentError("insecure S2K mode")
727 }
728
729 priv := bytes.NewBuffer(nil)
730 err := pk.serializePrivateKey(priv)
731 if err != nil {
732 return err
733 }
734
735 pk.cipher = cipherFunction
736 pk.s2kParams = params
737 pk.s2k, err = pk.s2kParams.Function()
738 if err != nil {
739 return err
740 }
741
742 privateKeyBytes := priv.Bytes()
743 pk.s2kType = s2kType
744 block := pk.cipher.new(key)
745 switch s2kType {
746 case S2KAEAD:
747 if pk.aead == 0 {
748 return errors.StructuralError("aead mode is not set on key")
749 }
750 aead, err := pk.aead.new(block)
751 if err != nil {
752 return err
753 }
754 additionalData, err := pk.additionalData()
755 if err != nil {
756 return err
757 }
758 pk.iv = make([]byte, aead.NonceSize())
759 _, err = io.ReadFull(rand, pk.iv)
760 if err != nil {
761 return err
762 }
763 // Decrypt the encrypted key material with aead
764 pk.encryptedData = aead.Seal(nil, pk.iv, privateKeyBytes, additionalData)
765 case S2KSHA1, S2KCHECKSUM:
766 pk.iv = make([]byte, pk.cipher.blockSize())
767 _, err = io.ReadFull(rand, pk.iv)
768 if err != nil {
769 return err
770 }
771 cfb := cipher.NewCFBEncrypter(block, pk.iv)
772 if s2kType == S2KSHA1 {
773 h := sha1.New()
774 h.Write(privateKeyBytes)
775 sum := h.Sum(nil)
776 privateKeyBytes = append(privateKeyBytes, sum...)
777 } else {
778 var sum uint16
779 for _, b := range privateKeyBytes {
780 sum += uint16(b)
781 }
782 privateKeyBytes = append(privateKeyBytes, []byte{uint8(sum >> 8), uint8(sum)}...)
783 }
784 pk.encryptedData = make([]byte, len(privateKeyBytes))
785 cfb.XORKeyStream(pk.encryptedData, privateKeyBytes)
786 default:
787 return errors.InvalidArgumentError("invalid s2k type for encryption")
788 }
789
790 pk.Encrypted = true
791 pk.PrivateKey = nil
792 return err
793 }
794
795 // EncryptWithConfig encrypts an unencrypted private key using the passphrase and the config.
796 func (pk *PrivateKey) EncryptWithConfig(passphrase []byte, config *Config) error {
797 params, err := s2k.Generate(config.Random(), config.S2K())
798 if err != nil {
799 return err
800 }
801 // Derive an encryption key with the configured s2k function.
802 key := make([]byte, config.Cipher().KeySize())
803 s2k, err := params.Function()
804 if err != nil {
805 return err
806 }
807 s2k(key, passphrase)
808 s2kType := S2KSHA1
809 if config.AEAD() != nil {
810 s2kType = S2KAEAD
811 pk.aead = config.AEAD().Mode()
812 pk.cipher = config.Cipher()
813 key = pk.applyHKDF(key)
814 }
815 // Encrypt the private key with the derived encryption key.
816 return pk.encrypt(key, params, s2kType, config.Cipher(), config.Random())
817 }
818
819 // EncryptPrivateKeys encrypts all unencrypted keys with the given config and passphrase.
820 // Only derives one key from the passphrase, which is then used to encrypt each key.
821 func EncryptPrivateKeys(keys []*PrivateKey, passphrase []byte, config *Config) error {
822 params, err := s2k.Generate(config.Random(), config.S2K())
823 if err != nil {
824 return err
825 }
826 // Derive an encryption key with the configured s2k function.
827 encryptionKey := make([]byte, config.Cipher().KeySize())
828 s2k, err := params.Function()
829 if err != nil {
830 return err
831 }
832 s2k(encryptionKey, passphrase)
833 for _, key := range keys {
834 if key != nil && !key.Dummy() && !key.Encrypted {
835 s2kType := S2KSHA1
836 if config.AEAD() != nil {
837 s2kType = S2KAEAD
838 key.aead = config.AEAD().Mode()
839 key.cipher = config.Cipher()
840 derivedKey := key.applyHKDF(encryptionKey)
841 err = key.encrypt(derivedKey, params, s2kType, config.Cipher(), config.Random())
842 } else {
843 err = key.encrypt(encryptionKey, params, s2kType, config.Cipher(), config.Random())
844 }
845 if err != nil {
846 return err
847 }
848 }
849 }
850 return nil
851 }
852
853 // Encrypt encrypts an unencrypted private key using a passphrase.
854 func (pk *PrivateKey) Encrypt(passphrase []byte) error {
855 // Default config of private key encryption
856 config := &Config{
857 S2KConfig: &s2k.Config{
858 S2KMode: s2k.IteratedSaltedS2K,
859 S2KCount: 65536,
860 Hash: crypto.SHA256,
861 },
862 DefaultCipher: CipherAES256,
863 }
864 return pk.EncryptWithConfig(passphrase, config)
865 }
866
867 func (pk *PrivateKey) serializePrivateKey(w io.Writer) (err error) {
868 switch priv := pk.PrivateKey.(type) {
869 case *rsa.PrivateKey:
870 err = serializeRSAPrivateKey(w, priv)
871 case *dsa.PrivateKey:
872 err = serializeDSAPrivateKey(w, priv)
873 case *elgamal.PrivateKey:
874 err = serializeElGamalPrivateKey(w, priv)
875 case *ecdsa.PrivateKey:
876 err = serializeECDSAPrivateKey(w, priv)
877 case *eddsa.PrivateKey:
878 err = serializeEdDSAPrivateKey(w, priv)
879 case *ecdh.PrivateKey:
880 err = serializeECDHPrivateKey(w, priv)
881 case *x25519.PrivateKey:
882 err = serializeX25519PrivateKey(w, priv)
883 case *x448.PrivateKey:
884 err = serializeX448PrivateKey(w, priv)
885 case *ed25519.PrivateKey:
886 err = serializeEd25519PrivateKey(w, priv)
887 case *ed448.PrivateKey:
888 err = serializeEd448PrivateKey(w, priv)
889 case *mlkem_ecdh.PrivateKey:
890 err = serializeMlkemPrivateKey(w, priv)
891 case *mldsa_eddsa.PrivateKey:
892 err = serializeMldsaEddsaPrivateKey(w, priv)
893 case *slhdsa.PrivateKey:
894 err = serializeSlhDsaPrivateKey(w, priv)
895 default:
896 err = errors.InvalidArgumentError("unknown private key type")
897 }
898 return
899 }
900
901 func (pk *PrivateKey) parsePrivateKey(data []byte) (err error) {
902 switch pk.PublicKey.PubKeyAlgo {
903 case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly, PubKeyAlgoRSAEncryptOnly:
904 return pk.parseRSAPrivateKey(data)
905 case PubKeyAlgoDSA:
906 return pk.parseDSAPrivateKey(data)
907 case PubKeyAlgoElGamal:
908 return pk.parseElGamalPrivateKey(data)
909 case PubKeyAlgoECDSA:
910 return pk.parseECDSAPrivateKey(data)
911 case PubKeyAlgoECDH:
912 return pk.parseECDHPrivateKey(data)
913 case PubKeyAlgoEdDSA:
914 return pk.parseEdDSAPrivateKey(data)
915 case PubKeyAlgoX25519:
916 return pk.parseX25519PrivateKey(data)
917 case PubKeyAlgoX448:
918 return pk.parseX448PrivateKey(data)
919 case PubKeyAlgoEd25519:
920 return pk.parseEd25519PrivateKey(data)
921 case PubKeyAlgoEd448:
922 return pk.parseEd448PrivateKey(data)
923 case PubKeyAlgoMlkem768X25519:
924 if !(pk.Version == 4 || pk.Version >= 6) {
925 return goerrors.New("openpgp: ML-KEM-768+X25519 may only be used with v4 or v6+")
926 }
927 return pk.parseMlkemEcdhPrivateKey(data, 32, mlkem_ecdh.MlKemSeedLen)
928 case PubKeyAlgoMlkem1024X448:
929 if pk.Version < 6 {
930 return goerrors.New("openpgp: ML-KEM-1024+X448 may only be used with v6+")
931 }
932 return pk.parseMlkemEcdhPrivateKey(data, 56, mlkem_ecdh.MlKemSeedLen)
933 case PubKeyAlgoMldsa65Ed25519:
934 if pk.Version < 6 {
935 return goerrors.New("openpgp: ML-DSA-65+Ed25519 may only be used with v6+")
936 }
937 return pk.parseMldsaEddsaPrivateKey(data, 32, mldsa_eddsa.MlDsaSeedLen)
938 case PubKeyAlgoMldsa87Ed448:
939 if pk.Version < 6 {
940 return goerrors.New("openpgp: ML-DSA-87+Ed448 may only be used with v6+")
941 }
942 return pk.parseMldsaEddsaPrivateKey(data, 57, mldsa_eddsa.MlDsaSeedLen)
943 case PubKeyAlgoSlhdsaShake128s, PubKeyAlgoSlhdsaShake128f, PubKeyAlgoSlhdsaShake256s:
944 if pk.Version < 6 {
945 return goerrors.New("openpgp: SLH-DSA may only be used with v6+")
946 }
947 return pk.parseSlhdsaPrivateKey(data)
948 default:
949 err = errors.StructuralError("unknown private key type")
950 return
951 }
952 }
953
954 func (pk *PrivateKey) parseRSAPrivateKey(data []byte) (err error) {
955 rsaPub := pk.PublicKey.PublicKey.(*rsa.PublicKey)
956 rsaPriv := new(rsa.PrivateKey)
957 rsaPriv.PublicKey = *rsaPub
958
959 buf := bytes.NewBuffer(data)
960 d := new(encoding.MPI)
961 if _, err := d.ReadFrom(buf); err != nil {
962 return err
963 }
964
965 p := new(encoding.MPI)
966 if _, err := p.ReadFrom(buf); err != nil {
967 return err
968 }
969
970 q := new(encoding.MPI)
971 if _, err := q.ReadFrom(buf); err != nil {
972 return err
973 }
974
975 rsaPriv.D = new(big.Int).SetBytes(d.Bytes())
976 rsaPriv.Primes = make([]*big.Int, 2)
977 // Mirror serializeRSAPrivateKey: Primes[1] is p and Primes[0] is q, so that
978 // Go's Qinv matches u = p^-1 mod q.
979 rsaPriv.Primes[0] = new(big.Int).SetBytes(q.Bytes())
980 rsaPriv.Primes[1] = new(big.Int).SetBytes(p.Bytes())
981 if err := rsaPriv.Validate(); err != nil {
982 return errors.KeyInvalidError(err.Error())
983 }
984 rsaPriv.Precompute()
985 pk.PrivateKey = rsaPriv
986
987 return nil
988 }
989
990 func (pk *PrivateKey) parseDSAPrivateKey(data []byte) (err error) {
991 dsaPub := pk.PublicKey.PublicKey.(*dsa.PublicKey)
992 dsaPriv := new(dsa.PrivateKey)
993 dsaPriv.PublicKey = *dsaPub
994
995 buf := bytes.NewBuffer(data)
996 x := new(encoding.MPI)
997 if _, err := x.ReadFrom(buf); err != nil {
998 return err
999 }
1000
1001 dsaPriv.X = new(big.Int).SetBytes(x.Bytes())
1002 if err := validateDSAParameters(dsaPriv); err != nil {
1003 return err
1004 }
1005 pk.PrivateKey = dsaPriv
1006
1007 return nil
1008 }
1009
1010 func (pk *PrivateKey) parseElGamalPrivateKey(data []byte) (err error) {
1011 pub := pk.PublicKey.PublicKey.(*elgamal.PublicKey)
1012 priv := new(elgamal.PrivateKey)
1013 priv.PublicKey = *pub
1014
1015 buf := bytes.NewBuffer(data)
1016 x := new(encoding.MPI)
1017 if _, err := x.ReadFrom(buf); err != nil {
1018 return err
1019 }
1020
1021 priv.X = new(big.Int).SetBytes(x.Bytes())
1022 if err := validateElGamalParameters(priv); err != nil {
1023 return err
1024 }
1025 pk.PrivateKey = priv
1026
1027 return nil
1028 }
1029
1030 func (pk *PrivateKey) parseECDSAPrivateKey(data []byte) (err error) {
1031 ecdsaPub := pk.PublicKey.PublicKey.(*ecdsa.PublicKey)
1032 ecdsaPriv := ecdsa.NewPrivateKey(*ecdsaPub)
1033
1034 buf := bytes.NewBuffer(data)
1035 d := new(encoding.MPI)
1036 if _, err := d.ReadFrom(buf); err != nil {
1037 return err
1038 }
1039
1040 if err := ecdsaPriv.UnmarshalIntegerSecret(d.Bytes()); err != nil {
1041 return err
1042 }
1043 if err := ecdsa.Validate(ecdsaPriv); err != nil {
1044 return err
1045 }
1046 pk.PrivateKey = ecdsaPriv
1047
1048 return nil
1049 }
1050
1051 func (pk *PrivateKey) parseECDHPrivateKey(data []byte) (err error) {
1052 ecdhPub := pk.PublicKey.PublicKey.(*ecdh.PublicKey)
1053 ecdhPriv := ecdh.NewPrivateKey(*ecdhPub)
1054
1055 buf := bytes.NewBuffer(data)
1056 d := new(encoding.MPI)
1057 if _, err := d.ReadFrom(buf); err != nil {
1058 return err
1059 }
1060
1061 if err := ecdhPriv.UnmarshalByteSecret(d.Bytes()); err != nil {
1062 return err
1063 }
1064
1065 if err := ecdh.Validate(ecdhPriv); err != nil {
1066 return err
1067 }
1068
1069 pk.PrivateKey = ecdhPriv
1070
1071 return nil
1072 }
1073
1074 func (pk *PrivateKey) parseX25519PrivateKey(data []byte) (err error) {
1075 publicKey := pk.PublicKey.PublicKey.(*x25519.PublicKey)
1076 privateKey := x25519.NewPrivateKey(*publicKey)
1077 privateKey.PublicKey = *publicKey
1078
1079 privateKey.Secret = make([]byte, x25519.KeySize)
1080
1081 if len(data) != x25519.KeySize {
1082 err = errors.StructuralError("wrong x25519 key size")
1083 return err
1084 }
1085 subtle.ConstantTimeCopy(1, privateKey.Secret, data)
1086 if err = x25519.Validate(privateKey); err != nil {
1087 return err
1088 }
1089 pk.PrivateKey = privateKey
1090 return nil
1091 }
1092
1093 func (pk *PrivateKey) parseX448PrivateKey(data []byte) (err error) {
1094 publicKey := pk.PublicKey.PublicKey.(*x448.PublicKey)
1095 privateKey := x448.NewPrivateKey(*publicKey)
1096 privateKey.PublicKey = *publicKey
1097
1098 privateKey.Secret = make([]byte, x448.KeySize)
1099
1100 if len(data) != x448.KeySize {
1101 err = errors.StructuralError("wrong x448 key size")
1102 return err
1103 }
1104 subtle.ConstantTimeCopy(1, privateKey.Secret, data)
1105 if err = x448.Validate(privateKey); err != nil {
1106 return err
1107 }
1108 pk.PrivateKey = privateKey
1109 return nil
1110 }
1111
1112 func (pk *PrivateKey) parseEd25519PrivateKey(data []byte) (err error) {
1113 publicKey := pk.PublicKey.PublicKey.(*ed25519.PublicKey)
1114 privateKey := ed25519.NewPrivateKey(*publicKey)
1115 privateKey.PublicKey = *publicKey
1116
1117 if len(data) != ed25519.SeedSize {
1118 err = errors.StructuralError("wrong ed25519 key size")
1119 return err
1120 }
1121 err = privateKey.UnmarshalByteSecret(data)
1122 if err != nil {
1123 return err
1124 }
1125 err = ed25519.Validate(privateKey)
1126 if err != nil {
1127 return err
1128 }
1129 pk.PrivateKey = privateKey
1130 return nil
1131 }
1132
1133 func (pk *PrivateKey) parseEd448PrivateKey(data []byte) (err error) {
1134 publicKey := pk.PublicKey.PublicKey.(*ed448.PublicKey)
1135 privateKey := ed448.NewPrivateKey(*publicKey)
1136 privateKey.PublicKey = *publicKey
1137
1138 if len(data) != ed448.SeedSize {
1139 err = errors.StructuralError("wrong ed448 key size")
1140 return err
1141 }
1142 err = privateKey.UnmarshalByteSecret(data)
1143 if err != nil {
1144 return err
1145 }
1146 err = ed448.Validate(privateKey)
1147 if err != nil {
1148 return err
1149 }
1150 pk.PrivateKey = privateKey
1151 return nil
1152 }
1153
1154 func (pk *PrivateKey) parseEdDSAPrivateKey(data []byte) (err error) {
1155 eddsaPub := pk.PublicKey.PublicKey.(*eddsa.PublicKey)
1156 eddsaPriv := eddsa.NewPrivateKey(*eddsaPub)
1157 eddsaPriv.PublicKey = *eddsaPub
1158
1159 buf := bytes.NewBuffer(data)
1160 d := new(encoding.MPI)
1161 if _, err := d.ReadFrom(buf); err != nil {
1162 return err
1163 }
1164
1165 if err = eddsaPriv.UnmarshalByteSecret(d.Bytes()); err != nil {
1166 return err
1167 }
1168
1169 if err := eddsa.Validate(eddsaPriv); err != nil {
1170 return err
1171 }
1172
1173 pk.PrivateKey = eddsaPriv
1174
1175 return nil
1176 }
1177
1178 func (pk *PrivateKey) additionalData() ([]byte, error) {
1179 additionalData := bytes.NewBuffer(nil)
1180 // Write additional data prefix based on packet type
1181 var packetByte byte
1182 if pk.PublicKey.IsSubkey {
1183 packetByte = 0xc7
1184 } else {
1185 packetByte = 0xc5
1186 }
1187 // Write public key to additional data
1188 _, err := additionalData.Write([]byte{packetByte})
1189 if err != nil {
1190 return nil, err
1191 }
1192 err = pk.PublicKey.serializeWithoutHeaders(additionalData)
1193 if err != nil {
1194 return nil, err
1195 }
1196 return additionalData.Bytes(), nil
1197 }
1198
1199 func (pk *PrivateKey) applyHKDF(inputKey []byte) []byte {
1200 var packetByte byte
1201 if pk.PublicKey.IsSubkey {
1202 packetByte = 0xc7
1203 } else {
1204 packetByte = 0xc5
1205 }
1206 associatedData := []byte{packetByte, byte(pk.Version), byte(pk.cipher), byte(pk.aead)}
1207 hkdfReader := hkdf.New(sha256.New, inputKey, []byte{}, associatedData)
1208 encryptionKey := make([]byte, pk.cipher.KeySize())
1209 _, _ = readFull(hkdfReader, encryptionKey)
1210 return encryptionKey
1211 }
1212
1213 // parseMldsaEddsaPrivateKey parses a ML-DSA + EdDSA private key as specified in
1214 // https://www.rfc-editor.org/rfc/rfc9980.html#name-key-material-packets-2
1215 func (pk *PrivateKey) parseMldsaEddsaPrivateKey(data []byte, ecLen, seedLen int) (err error) {
1216 if pk.Version != 6 {
1217 return goerrors.New("openpgp: cannot parse non-v6 ML-DSA + EdDSA key")
1218 }
1219 pub := pk.PublicKey.PublicKey.(*mldsa_eddsa.PublicKey)
1220 priv := new(mldsa_eddsa.PrivateKey)
1221 priv.PublicKey = *pub
1222
1223 if len(data) != ecLen + seedLen {
1224 return errors.StructuralError("wrong ML-DSA+EdDSA key size")
1225 }
1226
1227 ecKey := make([]byte, ecLen)
1228 copy(ecKey, data[:ecLen])
1229 priv.SecretEc = ecKey
1230
1231 seed := make([]byte, seedLen)
1232 copy(seed, data[ecLen:ecLen+seedLen])
1233 if err = priv.DeriveMlDsaKeys(seed, false); err != nil {
1234 return err
1235 }
1236
1237 if err := mldsa_eddsa.Validate(priv); err != nil {
1238 return err
1239 }
1240 pk.PrivateKey = priv
1241
1242 return nil
1243 }
1244
1245 // parseMlkemEcdhPrivateKey parses a ML-KEM + ECC private key as specified in
1246 // https://www.rfc-editor.org/rfc/rfc9980.html#name-key-material-packets
1247 func (pk *PrivateKey) parseMlkemEcdhPrivateKey(data []byte, ecLen, seedLen int) (err error) {
1248 pub := pk.PublicKey.PublicKey.(*mlkem_ecdh.PublicKey)
1249 priv := new(mlkem_ecdh.PrivateKey)
1250 priv.PublicKey = *pub
1251
1252 if len(data) != ecLen + seedLen {
1253 return errors.StructuralError("wrong ML-KEM+ECDH key size")
1254 }
1255
1256 ecKey := make([]byte, ecLen)
1257 copy(ecKey, data[:ecLen])
1258 priv.SecretEc = ecKey
1259
1260 seed := make([]byte, seedLen)
1261 copy(seed, data[ecLen:ecLen+seedLen])
1262 if err = priv.DeriveMlKemKeys(seed, false); err != nil {
1263 return err
1264 }
1265
1266 if err := mlkem_ecdh.Validate(priv); err != nil {
1267 return err
1268 }
1269 pk.PrivateKey = priv
1270
1271 return nil
1272 }
1273
1274 // parseSlhdsaPrivateKey parses a SLH-DSA private key.
1275 func (pk *PrivateKey) parseSlhdsaPrivateKey(data []byte) (err error) {
1276 if pk.Version != 6 {
1277 return goerrors.New("openpgp: cannot parse non-v6 SLH-DSA key")
1278 }
1279 parsedPublicKey := pk.PublicKey.PublicKey.(*slhdsa.PublicKey)
1280 parsedPrivateKey := new(slhdsa.PrivateKey)
1281 parsedPrivateKey.PublicKey = *parsedPublicKey
1282 parsedPrivateKey.SecretSlhdsa, err = parsedPrivateKey.Slhdsa.UnmarshalBinaryPrivateKey(data)
1283 if err != nil {
1284 return goerrors.New("openpgp: failed to unmarshal SLH-DSA key")
1285 }
1286
1287 if err := slhdsa.Validate(parsedPrivateKey); err != nil {
1288 return err
1289 }
1290 pk.PrivateKey = parsedPrivateKey
1291
1292 return nil
1293 }
1294
1295 func validateDSAParameters(priv *dsa.PrivateKey) error {
1296 p := priv.P // group prime
1297 q := priv.Q // subgroup order
1298 g := priv.G // g has order q mod p
1299 x := priv.X // secret
1300 y := priv.Y // y == g**x mod p
1301 one := big.NewInt(1)
1302 // expect g, y >= 2 and g < p
1303 if g.Cmp(one) <= 0 || y.Cmp(one) <= 0 || g.Cmp(p) > 0 {
1304 return errors.KeyInvalidError("dsa: invalid group")
1305 }
1306 // expect p > q
1307 if p.Cmp(q) <= 0 {
1308 return errors.KeyInvalidError("dsa: invalid group prime")
1309 }
1310 // q should be large enough and divide p-1
1311 pSub1 := new(big.Int).Sub(p, one)
1312 if q.BitLen() < 150 || new(big.Int).Mod(pSub1, q).Cmp(big.NewInt(0)) != 0 {
1313 return errors.KeyInvalidError("dsa: invalid order")
1314 }
1315 // confirm that g has order q mod p
1316 if !q.ProbablyPrime(32) || new(big.Int).Exp(g, q, p).Cmp(one) != 0 {
1317 return errors.KeyInvalidError("dsa: invalid order")
1318 }
1319 // check y
1320 if new(big.Int).Exp(g, x, p).Cmp(y) != 0 {
1321 return errors.KeyInvalidError("dsa: mismatching values")
1322 }
1323
1324 return nil
1325 }
1326
1327 func validateElGamalParameters(priv *elgamal.PrivateKey) error {
1328 p := priv.P // group prime
1329 g := priv.G // g has order p-1 mod p
1330 x := priv.X // secret
1331 y := priv.Y // y == g**x mod p
1332 one := big.NewInt(1)
1333 // Expect g, y >= 2 and g < p
1334 if g.Cmp(one) <= 0 || y.Cmp(one) <= 0 || g.Cmp(p) > 0 {
1335 return errors.KeyInvalidError("elgamal: invalid group")
1336 }
1337 if p.BitLen() < 1024 {
1338 return errors.KeyInvalidError("elgamal: group order too small")
1339 }
1340 pSub1 := new(big.Int).Sub(p, one)
1341 if new(big.Int).Exp(g, pSub1, p).Cmp(one) != 0 {
1342 return errors.KeyInvalidError("elgamal: invalid group")
1343 }
1344 // Since p-1 is not prime, g might have a smaller order that divides p-1.
1345 // We cannot confirm the exact order of g, but we make sure it is not too small.
1346 gExpI := new(big.Int).Set(g)
1347 i := 1
1348 threshold := 2 << 17 // we want order > threshold
1349 for i < threshold {
1350 i++ // we check every order to make sure key validation is not easily bypassed by guessing y'
1351 gExpI.Mod(new(big.Int).Mul(gExpI, g), p)
1352 if gExpI.Cmp(one) == 0 {
1353 return errors.KeyInvalidError("elgamal: order too small")
1354 }
1355 }
1356 // Check y
1357 if new(big.Int).Exp(g, x, p).Cmp(y) != 0 {
1358 return errors.KeyInvalidError("elgamal: mismatching values")
1359 }
1360
1361 return nil
1362 }