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