private_key.go 8.6 KB

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