encrypted_key.go 6.2 KB

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