private_key.go 7.2 KB

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