private_key.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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. "bytes"
  7. "crypto/cipher"
  8. "crypto/dsa"
  9. "crypto/rsa"
  10. "crypto/sha1"
  11. "golang.org/x/crypto/openpgp/elgamal"
  12. "golang.org/x/crypto/openpgp/errors"
  13. "golang.org/x/crypto/openpgp/s2k"
  14. "io"
  15. "io/ioutil"
  16. "math/big"
  17. "strconv"
  18. "time"
  19. )
  20. // PrivateKey represents a possibly encrypted private key. See RFC 4880,
  21. // section 5.5.3.
  22. type PrivateKey struct {
  23. PublicKey
  24. Encrypted bool // if true then the private key is unavailable until Decrypt has been called.
  25. encryptedData []byte
  26. cipher CipherFunction
  27. s2k func(out, in []byte)
  28. PrivateKey interface{} // An *rsa.PrivateKey or *dsa.PrivateKey.
  29. sha1Checksum bool
  30. iv []byte
  31. }
  32. func NewRSAPrivateKey(currentTime time.Time, priv *rsa.PrivateKey) *PrivateKey {
  33. pk := new(PrivateKey)
  34. pk.PublicKey = *NewRSAPublicKey(currentTime, &priv.PublicKey)
  35. pk.PrivateKey = priv
  36. return pk
  37. }
  38. func NewDSAPrivateKey(currentTime time.Time, priv *dsa.PrivateKey) *PrivateKey {
  39. pk := new(PrivateKey)
  40. pk.PublicKey = *NewDSAPublicKey(currentTime, &priv.PublicKey)
  41. pk.PrivateKey = priv
  42. return pk
  43. }
  44. func (pk *PrivateKey) parse(r io.Reader) (err error) {
  45. err = (&pk.PublicKey).parse(r)
  46. if err != nil {
  47. return
  48. }
  49. var buf [1]byte
  50. _, err = readFull(r, buf[:])
  51. if err != nil {
  52. return
  53. }
  54. s2kType := buf[0]
  55. switch s2kType {
  56. case 0:
  57. pk.s2k = nil
  58. pk.Encrypted = false
  59. case 254, 255:
  60. _, err = readFull(r, buf[:])
  61. if err != nil {
  62. return
  63. }
  64. pk.cipher = CipherFunction(buf[0])
  65. pk.Encrypted = true
  66. pk.s2k, err = s2k.Parse(r)
  67. if err != nil {
  68. return
  69. }
  70. if s2kType == 254 {
  71. pk.sha1Checksum = true
  72. }
  73. default:
  74. return errors.UnsupportedError("deprecated s2k function in private key")
  75. }
  76. if pk.Encrypted {
  77. blockSize := pk.cipher.blockSize()
  78. if blockSize == 0 {
  79. return errors.UnsupportedError("unsupported cipher in private key: " + strconv.Itoa(int(pk.cipher)))
  80. }
  81. pk.iv = make([]byte, blockSize)
  82. _, err = readFull(r, pk.iv)
  83. if err != nil {
  84. return
  85. }
  86. }
  87. pk.encryptedData, err = ioutil.ReadAll(r)
  88. if err != nil {
  89. return
  90. }
  91. if !pk.Encrypted {
  92. return pk.parsePrivateKey(pk.encryptedData)
  93. }
  94. return
  95. }
  96. func mod64kHash(d []byte) uint16 {
  97. var h uint16
  98. for _, b := range d {
  99. h += uint16(b)
  100. }
  101. return h
  102. }
  103. func (pk *PrivateKey) Serialize(w io.Writer) (err error) {
  104. // TODO(agl): support encrypted private keys
  105. buf := bytes.NewBuffer(nil)
  106. err = pk.PublicKey.serializeWithoutHeaders(buf)
  107. if err != nil {
  108. return
  109. }
  110. buf.WriteByte(0 /* no encryption */)
  111. privateKeyBuf := bytes.NewBuffer(nil)
  112. switch priv := pk.PrivateKey.(type) {
  113. case *rsa.PrivateKey:
  114. err = serializeRSAPrivateKey(privateKeyBuf, priv)
  115. case *dsa.PrivateKey:
  116. err = serializeDSAPrivateKey(privateKeyBuf, priv)
  117. default:
  118. err = errors.InvalidArgumentError("unknown private key type")
  119. }
  120. if err != nil {
  121. return
  122. }
  123. ptype := packetTypePrivateKey
  124. contents := buf.Bytes()
  125. privateKeyBytes := privateKeyBuf.Bytes()
  126. if pk.IsSubkey {
  127. ptype = packetTypePrivateSubkey
  128. }
  129. err = serializeHeader(w, ptype, len(contents)+len(privateKeyBytes)+2)
  130. if err != nil {
  131. return
  132. }
  133. _, err = w.Write(contents)
  134. if err != nil {
  135. return
  136. }
  137. _, err = w.Write(privateKeyBytes)
  138. if err != nil {
  139. return
  140. }
  141. checksum := mod64kHash(privateKeyBytes)
  142. var checksumBytes [2]byte
  143. checksumBytes[0] = byte(checksum >> 8)
  144. checksumBytes[1] = byte(checksum)
  145. _, err = w.Write(checksumBytes[:])
  146. return
  147. }
  148. func serializeRSAPrivateKey(w io.Writer, priv *rsa.PrivateKey) error {
  149. err := writeBig(w, priv.D)
  150. if err != nil {
  151. return err
  152. }
  153. err = writeBig(w, priv.Primes[1])
  154. if err != nil {
  155. return err
  156. }
  157. err = writeBig(w, priv.Primes[0])
  158. if err != nil {
  159. return err
  160. }
  161. return writeBig(w, priv.Precomputed.Qinv)
  162. }
  163. func serializeDSAPrivateKey(w io.Writer, priv *dsa.PrivateKey) error {
  164. return writeBig(w, priv.X)
  165. }
  166. // Decrypt decrypts an encrypted private key using a passphrase.
  167. func (pk *PrivateKey) Decrypt(passphrase []byte) error {
  168. if !pk.Encrypted {
  169. return nil
  170. }
  171. key := make([]byte, pk.cipher.KeySize())
  172. pk.s2k(key, passphrase)
  173. block := pk.cipher.new(key)
  174. cfb := cipher.NewCFBDecrypter(block, pk.iv)
  175. data := make([]byte, len(pk.encryptedData))
  176. cfb.XORKeyStream(data, pk.encryptedData)
  177. if pk.sha1Checksum {
  178. if len(data) < sha1.Size {
  179. return errors.StructuralError("truncated private key data")
  180. }
  181. h := sha1.New()
  182. h.Write(data[:len(data)-sha1.Size])
  183. sum := h.Sum(nil)
  184. if !bytes.Equal(sum, data[len(data)-sha1.Size:]) {
  185. return errors.StructuralError("private key checksum failure")
  186. }
  187. data = data[:len(data)-sha1.Size]
  188. } else {
  189. if len(data) < 2 {
  190. return errors.StructuralError("truncated private key data")
  191. }
  192. var sum uint16
  193. for i := 0; i < len(data)-2; i++ {
  194. sum += uint16(data[i])
  195. }
  196. if data[len(data)-2] != uint8(sum>>8) ||
  197. data[len(data)-1] != uint8(sum) {
  198. return errors.StructuralError("private key checksum failure")
  199. }
  200. data = data[:len(data)-2]
  201. }
  202. return pk.parsePrivateKey(data)
  203. }
  204. func (pk *PrivateKey) parsePrivateKey(data []byte) (err error) {
  205. switch pk.PublicKey.PubKeyAlgo {
  206. case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly, PubKeyAlgoRSAEncryptOnly:
  207. return pk.parseRSAPrivateKey(data)
  208. case PubKeyAlgoDSA:
  209. return pk.parseDSAPrivateKey(data)
  210. case PubKeyAlgoElGamal:
  211. return pk.parseElGamalPrivateKey(data)
  212. }
  213. panic("impossible")
  214. }
  215. func (pk *PrivateKey) parseRSAPrivateKey(data []byte) (err error) {
  216. rsaPub := pk.PublicKey.PublicKey.(*rsa.PublicKey)
  217. rsaPriv := new(rsa.PrivateKey)
  218. rsaPriv.PublicKey = *rsaPub
  219. buf := bytes.NewBuffer(data)
  220. d, _, err := readMPI(buf)
  221. if err != nil {
  222. return
  223. }
  224. p, _, err := readMPI(buf)
  225. if err != nil {
  226. return
  227. }
  228. q, _, err := readMPI(buf)
  229. if err != nil {
  230. return
  231. }
  232. rsaPriv.D = new(big.Int).SetBytes(d)
  233. rsaPriv.Primes = make([]*big.Int, 2)
  234. rsaPriv.Primes[0] = new(big.Int).SetBytes(p)
  235. rsaPriv.Primes[1] = new(big.Int).SetBytes(q)
  236. rsaPriv.Precompute()
  237. pk.PrivateKey = rsaPriv
  238. pk.Encrypted = false
  239. pk.encryptedData = nil
  240. return nil
  241. }
  242. func (pk *PrivateKey) parseDSAPrivateKey(data []byte) (err error) {
  243. dsaPub := pk.PublicKey.PublicKey.(*dsa.PublicKey)
  244. dsaPriv := new(dsa.PrivateKey)
  245. dsaPriv.PublicKey = *dsaPub
  246. buf := bytes.NewBuffer(data)
  247. x, _, err := readMPI(buf)
  248. if err != nil {
  249. return
  250. }
  251. dsaPriv.X = new(big.Int).SetBytes(x)
  252. pk.PrivateKey = dsaPriv
  253. pk.Encrypted = false
  254. pk.encryptedData = nil
  255. return nil
  256. }
  257. func (pk *PrivateKey) parseElGamalPrivateKey(data []byte) (err error) {
  258. pub := pk.PublicKey.PublicKey.(*elgamal.PublicKey)
  259. priv := new(elgamal.PrivateKey)
  260. priv.PublicKey = *pub
  261. buf := bytes.NewBuffer(data)
  262. x, _, err := readMPI(buf)
  263. if err != nil {
  264. return
  265. }
  266. priv.X = new(big.Int).SetBytes(x)
  267. pk.PrivateKey = priv
  268. pk.Encrypted = false
  269. pk.encryptedData = nil
  270. return nil
  271. }