You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

207 lines
6.1 KiB

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