Debian Codegraph @

openpgp/key_generation.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 openpgp
6
7 import (
8 "crypto"
9 "crypto/rand"
10 "crypto/rsa"
11 goerrors "errors"
12 "io"
13 "math/big"
14 "time"
15
16 "github.com/ProtonMail/go-crypto/openpgp/ecdh"
17 "github.com/ProtonMail/go-crypto/openpgp/ecdsa"
18 "github.com/ProtonMail/go-crypto/openpgp/ed25519"
19 "github.com/ProtonMail/go-crypto/openpgp/ed448"
20 "github.com/ProtonMail/go-crypto/openpgp/eddsa"
21 "github.com/ProtonMail/go-crypto/openpgp/errors"
22 "github.com/ProtonMail/go-crypto/openpgp/internal/algorithm"
23 "github.com/ProtonMail/go-crypto/openpgp/internal/ecc"
24 "github.com/ProtonMail/go-crypto/openpgp/mldsa_eddsa"
25 "github.com/ProtonMail/go-crypto/openpgp/mlkem_ecdh"
26 "github.com/ProtonMail/go-crypto/openpgp/packet"
27 "github.com/ProtonMail/go-crypto/openpgp/slhdsa"
28 "github.com/ProtonMail/go-crypto/openpgp/x25519"
29 "github.com/ProtonMail/go-crypto/openpgp/x448"
30 )
31
32 // NewEntity returns an Entity that contains a fresh RSA/RSA keypair with a
33 // single identity composed of the given full name, comment and email, any of
34 // which may be empty but must not contain any of "()<>\x00".
35 // If config is nil, sensible defaults will be used.
36 func NewEntity(name, comment, email string, config *packet.Config) (*Entity, error) {
37 creationTime := config.Now()
38 keyLifetimeSecs := config.KeyLifetime()
39
40 // Generate a primary signing key
41 primaryPrivRaw, err := newSigner(config)
42 if err != nil {
43 return nil, err
44 }
45 primary := packet.NewSignerPrivateKey(creationTime, primaryPrivRaw)
46 if config.V6() {
47 if err := primary.UpgradeToV6(); err != nil {
48 return nil, err
49 }
50 }
51
52 e := &Entity{
53 PrimaryKey: &primary.PublicKey,
54 PrivateKey: primary,
55 Identities: make(map[string]*Identity),
56 Subkeys: []Subkey{},
57 Signatures: []*packet.Signature{},
58 }
59
60 if config.V6() {
61 // In v6 keys algorithm preferences should be stored in direct key signatures
62 selfSignature := createSignaturePacket(&primary.PublicKey, packet.SigTypeDirectSignature, config)
63 err = writeKeyProperties(selfSignature, creationTime, keyLifetimeSecs, config)
64 if err != nil {
65 return nil, err
66 }
67 err = selfSignature.SignDirectKeyBinding(&primary.PublicKey, primary, config)
68 if err != nil {
69 return nil, err
70 }
71 e.Signatures = append(e.Signatures, selfSignature)
72 e.SelfSignature = selfSignature
73 }
74
75 err = e.addUserId(name, comment, email, config, creationTime, keyLifetimeSecs, !config.V6())
76 if err != nil {
77 return nil, err
78 }
79
80 // NOTE: No key expiry here, but we will not return this subkey in EncryptionKey()
81 // if the primary/master key has expired.
82 err = e.addEncryptionSubkey(config, creationTime, 0)
83 if err != nil {
84 return nil, err
85 }
86
87 return e, nil
88 }
89
90 func (t *Entity) AddUserId(name, comment, email string, config *packet.Config) error {
91 creationTime := config.Now()
92 keyLifetimeSecs := config.KeyLifetime()
93 return t.addUserId(name, comment, email, config, creationTime, keyLifetimeSecs, !config.V6())
94 }
95
96 func writeKeyProperties(selfSignature *packet.Signature, creationTime time.Time, keyLifetimeSecs uint32, config *packet.Config) error {
97 advertiseAead := config.AEAD() != nil
98
99 selfSignature.CreationTime = creationTime
100 selfSignature.KeyLifetimeSecs = &keyLifetimeSecs
101 selfSignature.FlagsValid = true
102 selfSignature.FlagSign = true
103 selfSignature.FlagCertify = true
104 selfSignature.SEIPDv1 = true // true by default, see 5.8 vs. 5.14
105 selfSignature.SEIPDv2 = advertiseAead
106
107 // Set the PreferredHash for the SelfSignature from the packet.Config.
108 // If it is not the must-implement algorithm from rfc4880bis, append that.
109 hash, ok := algorithm.HashToHashId(config.Hash())
110 if !ok {
111 return errors.UnsupportedError("unsupported preferred hash function")
112 }
113
114 selfSignature.PreferredHash = []uint8{hash}
115 if config.Hash() != crypto.SHA256 {
116 selfSignature.PreferredHash = append(selfSignature.PreferredHash, hashToHashId(crypto.SHA256))
117 }
118
119 // Likewise for DefaultCipher.
120 selfSignature.PreferredSymmetric = []uint8{uint8(config.Cipher())}
121 if config.Cipher() != packet.CipherAES128 {
122 selfSignature.PreferredSymmetric = append(selfSignature.PreferredSymmetric, uint8(packet.CipherAES128))
123 }
124
125 // We set CompressionNone as the preferred compression algorithm because
126 // of compression side channel attacks, then append the configured
127 // DefaultCompressionAlgo if any is set (to signal support for cases
128 // where the application knows that using compression is safe).
129 selfSignature.PreferredCompression = []uint8{uint8(packet.CompressionNone)}
130 if config.Compression() != packet.CompressionNone {
131 selfSignature.PreferredCompression = append(selfSignature.PreferredCompression, uint8(config.Compression()))
132 }
133
134 if advertiseAead {
135 // Get the preferred AEAD mode from the packet.Config.
136 // If it is not the must-implement algorithm from rfc9580, append that.
137 modes := []uint8{uint8(config.AEAD().Mode())}
138 if config.AEAD().Mode() != packet.AEADModeOCB {
139 modes = append(modes, uint8(packet.AEADModeOCB))
140 }
141
142 // For preferred (AES256, GCM), we'll generate (AES256, GCM), (AES256, OCB), (AES128, GCM), (AES128, OCB)
143 for _, cipher := range selfSignature.PreferredSymmetric {
144 for _, mode := range modes {
145 selfSignature.PreferredCipherSuites = append(selfSignature.PreferredCipherSuites, [2]uint8{cipher, mode})
146 }
147 }
148 }
149 return nil
150 }
151
152 func (t *Entity) addUserId(name, comment, email string, config *packet.Config, creationTime time.Time, keyLifetimeSecs uint32, writeProperties bool) error {
153 uid := packet.NewUserId(name, comment, email)
154 if uid == nil {
155 return errors.InvalidArgumentError("user id field contained invalid characters")
156 }
157
158 if _, ok := t.Identities[uid.Id]; ok {
159 return errors.InvalidArgumentError("user id exist")
160 }
161
162 primary := t.PrivateKey
163 isPrimaryId := len(t.Identities) == 0
164 selfSignature := createSignaturePacket(&primary.PublicKey, packet.SigTypePositiveCert, config)
165 if writeProperties {
166 err := writeKeyProperties(selfSignature, creationTime, keyLifetimeSecs, config)
167 if err != nil {
168 return err
169 }
170 }
171 selfSignature.IsPrimaryId = &isPrimaryId
172
173 // User ID binding signature
174 err := selfSignature.SignUserId(uid.Id, &primary.PublicKey, primary, config)
175 if err != nil {
176 return err
177 }
178 t.Identities[uid.Id] = &Identity{
179 Name: uid.Id,
180 UserId: uid,
181 SelfSignature: selfSignature,
182 Signatures: []*packet.Signature{selfSignature},
183 }
184 return nil
185 }
186
187 // AddSigningSubkey adds a signing keypair as a subkey to the Entity.
188 // If config is nil, sensible defaults will be used.
189 func (e *Entity) AddSigningSubkey(config *packet.Config) error {
190 creationTime := config.Now()
191 keyLifetimeSecs := config.KeyLifetime()
192
193 subPrivRaw, err := newSigner(config)
194 if err != nil {
195 return err
196 }
197 sub := packet.NewSignerPrivateKey(creationTime, subPrivRaw)
198 sub.IsSubkey = true
199 if config.V6() {
200 if err := sub.UpgradeToV6(); err != nil {
201 return err
202 }
203 }
204
205 subkey := Subkey{
206 PublicKey: &sub.PublicKey,
207 PrivateKey: sub,
208 }
209 subkey.Sig = createSignaturePacket(e.PrimaryKey, packet.SigTypeSubkeyBinding, config)
210 subkey.Sig.CreationTime = creationTime
211 subkey.Sig.KeyLifetimeSecs = &keyLifetimeSecs
212 subkey.Sig.FlagsValid = true
213 subkey.Sig.FlagSign = true
214 subkey.Sig.EmbeddedSignature = createSignaturePacket(subkey.PublicKey, packet.SigTypePrimaryKeyBinding, config)
215 subkey.Sig.EmbeddedSignature.CreationTime = creationTime
216
217 err = subkey.Sig.EmbeddedSignature.CrossSignKey(subkey.PublicKey, e.PrimaryKey, subkey.PrivateKey, config)
218 if err != nil {
219 return err
220 }
221
222 err = subkey.Sig.SignKey(subkey.PublicKey, e.PrivateKey, config)
223 if err != nil {
224 return err
225 }
226
227 e.Subkeys = append(e.Subkeys, subkey)
228 return nil
229 }
230
231 // AddEncryptionSubkey adds an encryption keypair as a subkey to the Entity.
232 // If config is nil, sensible defaults will be used.
233 func (e *Entity) AddEncryptionSubkey(config *packet.Config) error {
234 creationTime := config.Now()
235 keyLifetimeSecs := config.KeyLifetime()
236 return e.addEncryptionSubkey(config, creationTime, keyLifetimeSecs)
237 }
238
239 func (e *Entity) addEncryptionSubkey(config *packet.Config, creationTime time.Time, keyLifetimeSecs uint32) error {
240 subPrivRaw, err := newDecrypter(config)
241 if err != nil {
242 return err
243 }
244 sub := packet.NewDecrypterPrivateKey(creationTime, subPrivRaw)
245 sub.IsSubkey = true
246 if config.V6() {
247 if err := sub.UpgradeToV6(); err != nil {
248 return err
249 }
250 }
251
252 subkey := Subkey{
253 PublicKey: &sub.PublicKey,
254 PrivateKey: sub,
255 }
256 subkey.Sig = createSignaturePacket(e.PrimaryKey, packet.SigTypeSubkeyBinding, config)
257 subkey.Sig.CreationTime = creationTime
258 subkey.Sig.KeyLifetimeSecs = &keyLifetimeSecs
259 subkey.Sig.FlagsValid = true
260 subkey.Sig.FlagEncryptStorage = true
261 subkey.Sig.FlagEncryptCommunications = true
262
263 err = subkey.Sig.SignKey(subkey.PublicKey, e.PrivateKey, config)
264 if err != nil {
265 return err
266 }
267
268 e.Subkeys = append(e.Subkeys, subkey)
269 return nil
270 }
271
272 // Generates a signing key
273 func newSigner(config *packet.Config) (signer interface{}, err error) {
274 switch config.PublicKeyAlgorithm() {
275 case packet.PubKeyAlgoRSA:
276 bits := config.RSAModulusBits()
277 if bits < 1024 {
278 return nil, errors.InvalidArgumentError("bits must be >= 1024")
279 }
280 if config != nil && len(config.RSAPrimes) >= 2 {
281 primes := config.RSAPrimes[0:2]
282 config.RSAPrimes = config.RSAPrimes[2:]
283 return generateRSAKeyWithPrimes(config.Random(), 2, bits, primes)
284 }
285 return generateRSAKey(config.Random(), bits)
286 case packet.PubKeyAlgoEdDSA:
287 if config.V6() {
288 // Implementations MUST NOT accept or generate v6 key material
289 // using the deprecated OIDs.
290 return nil, errors.InvalidArgumentError("EdDSALegacy cannot be used for v6 keys")
291 }
292 curve := ecc.FindEdDSAByGenName(string(config.CurveName()))
293 if curve == nil {
294 return nil, errors.InvalidArgumentError("unsupported curve")
295 }
296
297 priv, err := eddsa.GenerateKey(config.Random(), curve)
298 if err != nil {
299 return nil, err
300 }
301 return priv, nil
302 case packet.PubKeyAlgoECDSA:
303 curve := ecc.FindECDSAByGenName(string(config.CurveName()))
304 if curve == nil {
305 return nil, errors.InvalidArgumentError("unsupported curve")
306 }
307
308 priv, err := ecdsa.GenerateKey(config.Random(), curve)
309 if err != nil {
310 return nil, err
311 }
312 return priv, nil
313 case packet.PubKeyAlgoEd25519:
314 priv, err := ed25519.GenerateKey(config.Random())
315 if err != nil {
316 return nil, err
317 }
318 return priv, nil
319 case packet.PubKeyAlgoEd448:
320 priv, err := ed448.GenerateKey(config.Random())
321 if err != nil {
322 return nil, err
323 }
324 return priv, nil
325 case packet.PubKeyAlgoMldsa65Ed25519, packet.PubKeyAlgoMldsa87Ed448:
326 if !config.V6() {
327 return nil, goerrors.New("openpgp: cannot create a non-v6 mldsa_eddsa key")
328 }
329
330 c, err := packet.GetEdDSACurveFromAlgID(config.PublicKeyAlgorithm())
331 if err != nil {
332 return nil, err
333 }
334 d, err := packet.GetMldsaFromAlgID(config.PublicKeyAlgorithm())
335 if err != nil {
336 return nil, err
337 }
338
339 return mldsa_eddsa.GenerateKey(config.Random(), uint8(config.PublicKeyAlgorithm()), c, d)
340 case packet.PubKeyAlgoSlhdsaShake128s, packet.PubKeyAlgoSlhdsaShake128f, packet.PubKeyAlgoSlhdsaShake256s:
341 if !config.V6() {
342 return nil, goerrors.New("openpgp: cannot create a non-v6 SLH-DSH key")
343 }
344
345 scheme, err := packet.GetSlhdsaSchemeFromAlgID(config.PublicKeyAlgorithm())
346 if err != nil {
347 return nil, err
348 }
349
350 return slhdsa.GenerateKey(config.Random(), uint8(config.PublicKeyAlgorithm()), scheme)
351 default:
352 return nil, errors.InvalidArgumentError("unsupported public key algorithm")
353 }
354 }
355
356 // Generates an encryption/decryption key
357 func newDecrypter(config *packet.Config) (decrypter interface{}, err error) {
358 pubKeyAlgo := config.PublicKeyAlgorithm()
359 switch pubKeyAlgo {
360 case packet.PubKeyAlgoRSA:
361 bits := config.RSAModulusBits()
362 if bits < 1024 {
363 return nil, errors.InvalidArgumentError("bits must be >= 1024")
364 }
365 if config != nil && len(config.RSAPrimes) >= 2 {
366 primes := config.RSAPrimes[0:2]
367 config.RSAPrimes = config.RSAPrimes[2:]
368 return generateRSAKeyWithPrimes(config.Random(), 2, bits, primes)
369 }
370 return generateRSAKey(config.Random(), bits)
371 case packet.PubKeyAlgoEdDSA, packet.PubKeyAlgoECDSA:
372 fallthrough // When passing EdDSA or ECDSA, we generate an ECDH subkey
373 case packet.PubKeyAlgoECDH:
374 if config.V6() &&
375 (config.CurveName() == packet.Curve25519 ||
376 config.CurveName() == packet.Curve448) {
377 // Implementations MUST NOT accept or generate v6 key material
378 // using the deprecated OIDs.
379 return nil, errors.InvalidArgumentError("ECDH with Curve25519/448 legacy cannot be used for v6 keys")
380 }
381 var kdf = ecdh.KDF{
382 Hash: algorithm.SHA512,
383 Cipher: algorithm.AES256,
384 }
385 curve := ecc.FindECDHByGenName(string(config.CurveName()))
386 if curve == nil {
387 return nil, errors.InvalidArgumentError("unsupported curve")
388 }
389 return ecdh.GenerateKey(config.Random(), curve, kdf)
390 case packet.PubKeyAlgoEd25519, packet.PubKeyAlgoX25519: // When passing Ed25519, we generate an x25519 subkey
391 return x25519.GenerateKey(config.Random())
392 case packet.PubKeyAlgoEd448, packet.PubKeyAlgoX448: // When passing Ed448, we generate an x448 subkey
393 return x448.GenerateKey(config.Random())
394 case packet.PubKeyAlgoMldsa65Ed25519, packet.PubKeyAlgoMldsa87Ed448,
395 packet.PubKeyAlgoSlhdsaShake128s, packet.PubKeyAlgoSlhdsaShake128f, packet.PubKeyAlgoSlhdsaShake256s:
396 if pubKeyAlgo, err = packet.GetMatchingMlkem(config.PublicKeyAlgorithm()); err != nil {
397 return nil, err
398 }
399 fallthrough // When passing ML-DSA + EdDSA or ECDSA, we generate a ML-KEM + ECDH subkey
400 case packet.PubKeyAlgoMlkem768X25519, packet.PubKeyAlgoMlkem1024X448:
401 if !config.V6() && pubKeyAlgo == packet.PubKeyAlgoMlkem1024X448 {
402 return nil, goerrors.New("openpgp: cannot create a non-v6 mlkem1024_x448 key")
403 }
404
405 c, err := packet.GetECDHCurveFromAlgID(pubKeyAlgo)
406 if err != nil {
407 return nil, err
408 }
409 k, err := packet.GetMlkemFromAlgID(pubKeyAlgo)
410 if err != nil {
411 return nil, err
412 }
413
414 return mlkem_ecdh.GenerateKey(config.Random(), uint8(pubKeyAlgo), c, k)
415 default:
416 return nil, errors.InvalidArgumentError("unsupported public key algorithm")
417 }
418 }
419
420 var bigOne = big.NewInt(1)
421
422 // generateRSAKey generates an RSA keypair and ensures that p < q as required by RFC 9580.
423 func generateRSAKey(random io.Reader, bits int) (*rsa.PrivateKey, error) {
424 key, err := rsa.GenerateKey(random, bits)
425 if err != nil {
426 return nil, err
427 }
428 enforceRSAPrimeOrder(key)
429 return key, nil
430 }
431
432 // enforceRSAPrimeOrder ensures p < q, as required by RFC 9580 section 5.5.5.1
433 // for RSA keys. The OpenPGP serialization writes Primes[1] as p and Primes[0]
434 // as q (so that Go's Qinv is u = p^-1 mod q), hence we need
435 // Primes[1] < Primes[0]. The Go standard library does not guarantee this, so we
436 // swap if needed and recompute the precomputed values.
437 func enforceRSAPrimeOrder(key *rsa.PrivateKey) {
438 if len(key.Primes) == 2 && key.Primes[0].Cmp(key.Primes[1]) < 0 {
439 key.Primes[0], key.Primes[1] = key.Primes[1], key.Primes[0]
440 key.Precomputed = rsa.PrecomputedValues{}
441 key.Precompute()
442 }
443 }
444
445 // generateRSAKeyWithPrimes generates a multi-prime RSA keypair of the
446 // given bit size, using the given random source and pre-populated primes.
447 func generateRSAKeyWithPrimes(random io.Reader, nprimes int, bits int, prepopulatedPrimes []*big.Int) (*rsa.PrivateKey, error) {
448 priv := new(rsa.PrivateKey)
449 priv.E = 65537
450
451 if nprimes < 2 {
452 return nil, goerrors.New("generateRSAKeyWithPrimes: nprimes must be >= 2")
453 }
454
455 if bits < 1024 {
456 return nil, goerrors.New("generateRSAKeyWithPrimes: bits must be >= 1024")
457 }
458
459 primes := make([]*big.Int, nprimes)
460
461 NextSetOfPrimes:
462 for {
463 todo := bits
464 // crypto/rand should set the top two bits in each prime.
465 // Thus each prime has the form
466 // p_i = 2^bitlen(p_i) × 0.11... (in base 2).
467 // And the product is:
468 // P = 2^todo × α
469 // where α is the product of nprimes numbers of the form 0.11...
470 //
471 // If α < 1/2 (which can happen for nprimes > 2), we need to
472 // shift todo to compensate for lost bits: the mean value of 0.11...
473 // is 7/8, so todo + shift - nprimes * log2(7/8) ~= bits - 1/2
474 // will give good results.
475 if nprimes >= 7 {
476 todo += (nprimes - 2) / 5
477 }
478 for i := 0; i < nprimes; i++ {
479 var err error
480 if len(prepopulatedPrimes) == 0 {
481 primes[i], err = rand.Prime(random, todo/(nprimes-i))
482 if err != nil {
483 return nil, err
484 }
485 } else {
486 primes[i] = prepopulatedPrimes[0]
487 prepopulatedPrimes = prepopulatedPrimes[1:]
488 }
489
490 todo -= primes[i].BitLen()
491 }
492
493 // Make sure that primes is pairwise unequal.
494 for i, prime := range primes {
495 for j := 0; j < i; j++ {
496 if prime.Cmp(primes[j]) == 0 {
497 continue NextSetOfPrimes
498 }
499 }
500 }
501
502 n := new(big.Int).Set(bigOne)
503 totient := new(big.Int).Set(bigOne)
504 pminus1 := new(big.Int)
505 for _, prime := range primes {
506 n.Mul(n, prime)
507 pminus1.Sub(prime, bigOne)
508 totient.Mul(totient, pminus1)
509 }
510 if n.BitLen() != bits {
511 // This should never happen for nprimes == 2 because
512 // crypto/rand should set the top two bits in each prime.
513 // For nprimes > 2 we hope it does not happen often.
514 continue NextSetOfPrimes
515 }
516
517 priv.D = new(big.Int)
518 e := big.NewInt(int64(priv.E))
519 ok := priv.D.ModInverse(e, totient)
520
521 if ok != nil {
522 priv.Primes = primes
523 priv.N = n
524 break
525 }
526 }
527
528 // RFC 9580 section 5.5.5.1 requires p < q for RSA keys.
529 // Primes[1] is serialized as p and Primes[0] as q.
530 if len(priv.Primes) == 2 && priv.Primes[0].Cmp(priv.Primes[1]) < 0 {
531 priv.Primes[0], priv.Primes[1] = priv.Primes[1], priv.Primes[0]
532 }
533
534 priv.Precompute()
535 return priv, nil
536 }