You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

private_key.go 8.9KB

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