private_key.go 8.9 KB

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