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.

encrypted_key.go 7.0KB

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