encrypted_key.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  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. package packet
  5. import (
  6. "crypto/rsa"
  7. "encoding/binary"
  8. "golang.org/x/crypto/openpgp/elgamal"
  9. "golang.org/x/crypto/openpgp/errors"
  10. "io"
  11. "math/big"
  12. "strconv"
  13. )
  14. const encryptedKeyVersion = 3
  15. // EncryptedKey represents a public-key encrypted session key. See RFC 4880,
  16. // section 5.1.
  17. type EncryptedKey struct {
  18. KeyId uint64
  19. Algo PublicKeyAlgorithm
  20. CipherFunc CipherFunction // only valid after a successful Decrypt
  21. Key []byte // only valid after a successful Decrypt
  22. encryptedMPI1, encryptedMPI2 []byte
  23. }
  24. func (e *EncryptedKey) parse(r io.Reader) (err error) {
  25. var buf [10]byte
  26. _, err = readFull(r, buf[:])
  27. if err != nil {
  28. return
  29. }
  30. if buf[0] != encryptedKeyVersion {
  31. return errors.UnsupportedError("unknown EncryptedKey version " + strconv.Itoa(int(buf[0])))
  32. }
  33. e.KeyId = binary.BigEndian.Uint64(buf[1:9])
  34. e.Algo = PublicKeyAlgorithm(buf[9])
  35. switch e.Algo {
  36. case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly:
  37. e.encryptedMPI1, _, err = readMPI(r)
  38. case PubKeyAlgoElGamal:
  39. e.encryptedMPI1, _, err = readMPI(r)
  40. if err != nil {
  41. return
  42. }
  43. e.encryptedMPI2, _, err = readMPI(r)
  44. }
  45. _, err = consumeAll(r)
  46. return
  47. }
  48. func checksumKeyMaterial(key []byte) uint16 {
  49. var checksum uint16
  50. for _, v := range key {
  51. checksum += uint16(v)
  52. }
  53. return checksum
  54. }
  55. // Decrypt decrypts an encrypted session key with the given private key. The
  56. // private key must have been decrypted first.
  57. // If config is nil, sensible defaults will be used.
  58. func (e *EncryptedKey) Decrypt(priv *PrivateKey, config *Config) error {
  59. var err error
  60. var b []byte
  61. // TODO(agl): use session key decryption routines here to avoid
  62. // padding oracle attacks.
  63. switch priv.PubKeyAlgo {
  64. case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly:
  65. b, err = rsa.DecryptPKCS1v15(config.Random(), priv.PrivateKey.(*rsa.PrivateKey), e.encryptedMPI1)
  66. case PubKeyAlgoElGamal:
  67. c1 := new(big.Int).SetBytes(e.encryptedMPI1)
  68. c2 := new(big.Int).SetBytes(e.encryptedMPI2)
  69. b, err = elgamal.Decrypt(priv.PrivateKey.(*elgamal.PrivateKey), c1, c2)
  70. default:
  71. err = errors.InvalidArgumentError("cannot decrypted encrypted session key with private key of type " + strconv.Itoa(int(priv.PubKeyAlgo)))
  72. }
  73. if err != nil {
  74. return err
  75. }
  76. e.CipherFunc = CipherFunction(b[0])
  77. e.Key = b[1 : len(b)-2]
  78. expectedChecksum := uint16(b[len(b)-2])<<8 | uint16(b[len(b)-1])
  79. checksum := checksumKeyMaterial(e.Key)
  80. if checksum != expectedChecksum {
  81. return errors.StructuralError("EncryptedKey checksum incorrect")
  82. }
  83. return nil
  84. }
  85. // SerializeEncryptedKey serializes an encrypted key packet to w that contains
  86. // key, encrypted to pub.
  87. // If config is nil, sensible defaults will be used.
  88. func SerializeEncryptedKey(w io.Writer, pub *PublicKey, cipherFunc CipherFunction, key []byte, config *Config) error {
  89. var buf [10]byte
  90. buf[0] = encryptedKeyVersion
  91. binary.BigEndian.PutUint64(buf[1:9], pub.KeyId)
  92. buf[9] = byte(pub.PubKeyAlgo)
  93. keyBlock := make([]byte, 1 /* cipher type */ +len(key)+2 /* checksum */)
  94. keyBlock[0] = byte(cipherFunc)
  95. copy(keyBlock[1:], key)
  96. checksum := checksumKeyMaterial(key)
  97. keyBlock[1+len(key)] = byte(checksum >> 8)
  98. keyBlock[1+len(key)+1] = byte(checksum)
  99. switch pub.PubKeyAlgo {
  100. case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly:
  101. return serializeEncryptedKeyRSA(w, config.Random(), buf, pub.PublicKey.(*rsa.PublicKey), keyBlock)
  102. case PubKeyAlgoElGamal:
  103. return serializeEncryptedKeyElGamal(w, config.Random(), buf, pub.PublicKey.(*elgamal.PublicKey), keyBlock)
  104. case PubKeyAlgoDSA, PubKeyAlgoRSASignOnly:
  105. return errors.InvalidArgumentError("cannot encrypt to public key of type " + strconv.Itoa(int(pub.PubKeyAlgo)))
  106. }
  107. return errors.UnsupportedError("encrypting a key to public key of type " + strconv.Itoa(int(pub.PubKeyAlgo)))
  108. }
  109. func serializeEncryptedKeyRSA(w io.Writer, rand io.Reader, header [10]byte, pub *rsa.PublicKey, keyBlock []byte) error {
  110. cipherText, err := rsa.EncryptPKCS1v15(rand, pub, keyBlock)
  111. if err != nil {
  112. return errors.InvalidArgumentError("RSA encryption failed: " + err.Error())
  113. }
  114. packetLen := 10 /* header length */ + 2 /* mpi size */ + len(cipherText)
  115. err = serializeHeader(w, packetTypeEncryptedKey, packetLen)
  116. if err != nil {
  117. return err
  118. }
  119. _, err = w.Write(header[:])
  120. if err != nil {
  121. return err
  122. }
  123. return writeMPI(w, 8*uint16(len(cipherText)), cipherText)
  124. }
  125. func serializeEncryptedKeyElGamal(w io.Writer, rand io.Reader, header [10]byte, pub *elgamal.PublicKey, keyBlock []byte) error {
  126. c1, c2, err := elgamal.Encrypt(rand, pub, keyBlock)
  127. if err != nil {
  128. return errors.InvalidArgumentError("ElGamal encryption failed: " + err.Error())
  129. }
  130. packetLen := 10 /* header length */
  131. packetLen += 2 /* mpi size */ + (c1.BitLen()+7)/8
  132. packetLen += 2 /* mpi size */ + (c2.BitLen()+7)/8
  133. err = serializeHeader(w, packetTypeEncryptedKey, packetLen)
  134. if err != nil {
  135. return err
  136. }
  137. _, err = w.Write(header[:])
  138. if err != nil {
  139. return err
  140. }
  141. err = writeBig(w, c1)
  142. if err != nil {
  143. return err
  144. }
  145. return writeBig(w, c2)
  146. }