本站源代码
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.

227 lines
6.9KB

  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. var err error
  76. var b []byte
  77. // TODO(agl): use session key decryption routines here to avoid
  78. // padding oracle attacks.
  79. switch priv.PubKeyAlgo {
  80. case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly:
  81. b, err = rsa.DecryptPKCS1v15(config.Random(), priv.PrivateKey.(*rsa.PrivateKey), e.encryptedMPI1.bytes)
  82. case PubKeyAlgoElGamal:
  83. c1 := new(big.Int).SetBytes(e.encryptedMPI1.bytes)
  84. c2 := new(big.Int).SetBytes(e.encryptedMPI2.bytes)
  85. b, err = elgamal.Decrypt(priv.PrivateKey.(*elgamal.PrivateKey), c1, c2)
  86. case PubKeyAlgoECDH:
  87. // Note: Unmarshal checks if point is on the curve.
  88. c1, c2 := ecdh.Unmarshal(priv.PrivateKey.(*ecdh.PrivateKey).Curve, e.encryptedMPI1.bytes)
  89. if c1 == nil {
  90. return errors.InvalidArgumentError("failed to parse EC point for encryption key")
  91. }
  92. b, err = decryptKeyECDH(priv, c1, c2, e.ecdh_C)
  93. default:
  94. err = errors.InvalidArgumentError("cannot decrypted encrypted session key with private key of type " + strconv.Itoa(int(priv.PubKeyAlgo)))
  95. }
  96. if err != nil {
  97. return err
  98. }
  99. e.CipherFunc = CipherFunction(b[0])
  100. e.Key = b[1 : len(b)-2]
  101. expectedChecksum := uint16(b[len(b)-2])<<8 | uint16(b[len(b)-1])
  102. checksum := checksumKeyMaterial(e.Key)
  103. if checksum != expectedChecksum {
  104. return errors.StructuralError("EncryptedKey checksum incorrect")
  105. }
  106. return nil
  107. }
  108. // Serialize writes the encrypted key packet, e, to w.
  109. func (e *EncryptedKey) Serialize(w io.Writer) error {
  110. var mpiLen int
  111. switch e.Algo {
  112. case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly:
  113. mpiLen = 2 + len(e.encryptedMPI1.bytes)
  114. case PubKeyAlgoElGamal:
  115. mpiLen = 2 + len(e.encryptedMPI1.bytes) + 2 + len(e.encryptedMPI2.bytes)
  116. default:
  117. return errors.InvalidArgumentError("don't know how to serialize encrypted key type " + strconv.Itoa(int(e.Algo)))
  118. }
  119. serializeHeader(w, packetTypeEncryptedKey, 1 /* version */ +8 /* key id */ +1 /* algo */ +mpiLen)
  120. w.Write([]byte{encryptedKeyVersion})
  121. binary.Write(w, binary.BigEndian, e.KeyId)
  122. w.Write([]byte{byte(e.Algo)})
  123. switch e.Algo {
  124. case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly:
  125. writeMPIs(w, e.encryptedMPI1)
  126. case PubKeyAlgoElGamal:
  127. writeMPIs(w, e.encryptedMPI1, e.encryptedMPI2)
  128. default:
  129. panic("internal error")
  130. }
  131. return nil
  132. }
  133. // SerializeEncryptedKey serializes an encrypted key packet to w that contains
  134. // key, encrypted to pub.
  135. // If config is nil, sensible defaults will be used.
  136. func SerializeEncryptedKey(w io.Writer, pub *PublicKey, cipherFunc CipherFunction, key []byte, config *Config) error {
  137. var buf [10]byte
  138. buf[0] = encryptedKeyVersion
  139. binary.BigEndian.PutUint64(buf[1:9], pub.KeyId)
  140. buf[9] = byte(pub.PubKeyAlgo)
  141. keyBlock := make([]byte, 1 /* cipher type */ +len(key)+2 /* checksum */)
  142. keyBlock[0] = byte(cipherFunc)
  143. copy(keyBlock[1:], key)
  144. checksum := checksumKeyMaterial(key)
  145. keyBlock[1+len(key)] = byte(checksum >> 8)
  146. keyBlock[1+len(key)+1] = byte(checksum)
  147. switch pub.PubKeyAlgo {
  148. case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly:
  149. return serializeEncryptedKeyRSA(w, config.Random(), buf, pub.PublicKey.(*rsa.PublicKey), keyBlock)
  150. case PubKeyAlgoElGamal:
  151. return serializeEncryptedKeyElGamal(w, config.Random(), buf, pub.PublicKey.(*elgamal.PublicKey), keyBlock)
  152. case PubKeyAlgoECDH:
  153. return serializeEncryptedKeyECDH(w, config.Random(), buf, pub, keyBlock)
  154. case PubKeyAlgoDSA, PubKeyAlgoRSASignOnly:
  155. return errors.InvalidArgumentError("cannot encrypt to public key of type " + strconv.Itoa(int(pub.PubKeyAlgo)))
  156. }
  157. return errors.UnsupportedError("encrypting a key to public key of type " + strconv.Itoa(int(pub.PubKeyAlgo)))
  158. }
  159. func serializeEncryptedKeyRSA(w io.Writer, rand io.Reader, header [10]byte, pub *rsa.PublicKey, keyBlock []byte) error {
  160. cipherText, err := rsa.EncryptPKCS1v15(rand, pub, keyBlock)
  161. if err != nil {
  162. return errors.InvalidArgumentError("RSA encryption failed: " + err.Error())
  163. }
  164. packetLen := 10 /* header length */ + 2 /* mpi size */ + len(cipherText)
  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. return writeMPI(w, 8*uint16(len(cipherText)), cipherText)
  174. }
  175. func serializeEncryptedKeyElGamal(w io.Writer, rand io.Reader, header [10]byte, pub *elgamal.PublicKey, keyBlock []byte) error {
  176. c1, c2, err := elgamal.Encrypt(rand, pub, keyBlock)
  177. if err != nil {
  178. return errors.InvalidArgumentError("ElGamal encryption failed: " + err.Error())
  179. }
  180. packetLen := 10 /* header length */
  181. packetLen += 2 /* mpi size */ + (c1.BitLen()+7)/8
  182. packetLen += 2 /* mpi size */ + (c2.BitLen()+7)/8
  183. err = serializeHeader(w, packetTypeEncryptedKey, packetLen)
  184. if err != nil {
  185. return err
  186. }
  187. _, err = w.Write(header[:])
  188. if err != nil {
  189. return err
  190. }
  191. err = writeBig(w, c1)
  192. if err != nil {
  193. return err
  194. }
  195. return writeBig(w, c2)
  196. }
上海开阖软件有限公司 沪ICP备12045867号-1