encrypted_key.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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. case PubKeyAlgoElGamal:
  39. e.encryptedMPI1.bytes, e.encryptedMPI1.bitLength, err = readMPI(r)
  40. if err != nil {
  41. return
  42. }
  43. e.encryptedMPI2.bytes, e.encryptedMPI2.bitLength, 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.bytes)
  66. case PubKeyAlgoElGamal:
  67. c1 := new(big.Int).SetBytes(e.encryptedMPI1.bytes)
  68. c2 := new(big.Int).SetBytes(e.encryptedMPI2.bytes)
  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. // Serialize writes the encrypted key packet, e, to w.
  86. func (e *EncryptedKey) Serialize(w io.Writer) error {
  87. var mpiLen int
  88. switch e.Algo {
  89. case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly:
  90. mpiLen = 2 + len(e.encryptedMPI1.bytes)
  91. case PubKeyAlgoElGamal:
  92. mpiLen = 2 + len(e.encryptedMPI1.bytes) + 2 + len(e.encryptedMPI2.bytes)
  93. default:
  94. return errors.InvalidArgumentError("don't know how to serialize encrypted key type " + strconv.Itoa(int(e.Algo)))
  95. }
  96. serializeHeader(w, packetTypeEncryptedKey, 1 /* version */ +8 /* key id */ +1 /* algo */ +mpiLen)
  97. w.Write([]byte{encryptedKeyVersion})
  98. binary.Write(w, binary.BigEndian, e.KeyId)
  99. w.Write([]byte{byte(e.Algo)})
  100. switch e.Algo {
  101. case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly:
  102. writeMPIs(w, e.encryptedMPI1)
  103. case PubKeyAlgoElGamal:
  104. writeMPIs(w, e.encryptedMPI1, e.encryptedMPI2)
  105. default:
  106. panic("internal error")
  107. }
  108. return nil
  109. }
  110. // SerializeEncryptedKey serializes an encrypted key packet to w that contains
  111. // key, encrypted to pub.
  112. // If config is nil, sensible defaults will be used.
  113. func SerializeEncryptedKey(w io.Writer, pub *PublicKey, cipherFunc CipherFunction, key []byte, config *Config) error {
  114. var buf [10]byte
  115. buf[0] = encryptedKeyVersion
  116. binary.BigEndian.PutUint64(buf[1:9], pub.KeyId)
  117. buf[9] = byte(pub.PubKeyAlgo)
  118. keyBlock := make([]byte, 1 /* cipher type */ +len(key)+2 /* checksum */)
  119. keyBlock[0] = byte(cipherFunc)
  120. copy(keyBlock[1:], key)
  121. checksum := checksumKeyMaterial(key)
  122. keyBlock[1+len(key)] = byte(checksum >> 8)
  123. keyBlock[1+len(key)+1] = byte(checksum)
  124. switch pub.PubKeyAlgo {
  125. case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly:
  126. return serializeEncryptedKeyRSA(w, config.Random(), buf, pub.PublicKey.(*rsa.PublicKey), keyBlock)
  127. case PubKeyAlgoElGamal:
  128. return serializeEncryptedKeyElGamal(w, config.Random(), buf, pub.PublicKey.(*elgamal.PublicKey), keyBlock)
  129. case PubKeyAlgoDSA, PubKeyAlgoRSASignOnly:
  130. return errors.InvalidArgumentError("cannot encrypt to public key of type " + strconv.Itoa(int(pub.PubKeyAlgo)))
  131. }
  132. return errors.UnsupportedError("encrypting a key to public key of type " + strconv.Itoa(int(pub.PubKeyAlgo)))
  133. }
  134. func serializeEncryptedKeyRSA(w io.Writer, rand io.Reader, header [10]byte, pub *rsa.PublicKey, keyBlock []byte) error {
  135. cipherText, err := rsa.EncryptPKCS1v15(rand, pub, keyBlock)
  136. if err != nil {
  137. return errors.InvalidArgumentError("RSA encryption failed: " + err.Error())
  138. }
  139. packetLen := 10 /* header length */ + 2 /* mpi size */ + len(cipherText)
  140. err = serializeHeader(w, packetTypeEncryptedKey, packetLen)
  141. if err != nil {
  142. return err
  143. }
  144. _, err = w.Write(header[:])
  145. if err != nil {
  146. return err
  147. }
  148. return writeMPI(w, 8*uint16(len(cipherText)), cipherText)
  149. }
  150. func serializeEncryptedKeyElGamal(w io.Writer, rand io.Reader, header [10]byte, pub *elgamal.PublicKey, keyBlock []byte) error {
  151. c1, c2, err := elgamal.Encrypt(rand, pub, keyBlock)
  152. if err != nil {
  153. return errors.InvalidArgumentError("ElGamal encryption failed: " + err.Error())
  154. }
  155. packetLen := 10 /* header length */
  156. packetLen += 2 /* mpi size */ + (c1.BitLen()+7)/8
  157. packetLen += 2 /* mpi size */ + (c2.BitLen()+7)/8
  158. err = serializeHeader(w, packetTypeEncryptedKey, packetLen)
  159. if err != nil {
  160. return err
  161. }
  162. _, err = w.Write(header[:])
  163. if err != nil {
  164. return err
  165. }
  166. err = writeBig(w, c1)
  167. if err != nil {
  168. return err
  169. }
  170. return writeBig(w, c2)
  171. }