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