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.

public_key.go 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753
  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/dsa"
  9. "crypto/ecdsa"
  10. "crypto/elliptic"
  11. "crypto/rsa"
  12. "crypto/sha1"
  13. _ "crypto/sha256"
  14. _ "crypto/sha512"
  15. "encoding/binary"
  16. "fmt"
  17. "hash"
  18. "io"
  19. "math/big"
  20. "strconv"
  21. "time"
  22. "golang.org/x/crypto/openpgp/elgamal"
  23. "golang.org/x/crypto/openpgp/errors"
  24. )
  25. var (
  26. // NIST curve P-256
  27. oidCurveP256 []byte = []byte{0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07}
  28. // NIST curve P-384
  29. oidCurveP384 []byte = []byte{0x2B, 0x81, 0x04, 0x00, 0x22}
  30. // NIST curve P-521
  31. oidCurveP521 []byte = []byte{0x2B, 0x81, 0x04, 0x00, 0x23}
  32. )
  33. const maxOIDLength = 8
  34. // ecdsaKey stores the algorithm-specific fields for ECDSA keys.
  35. // as defined in RFC 6637, Section 9.
  36. type ecdsaKey struct {
  37. // oid contains the OID byte sequence identifying the elliptic curve used
  38. oid []byte
  39. // p contains the elliptic curve point that represents the public key
  40. p parsedMPI
  41. }
  42. // parseOID reads the OID for the curve as defined in RFC 6637, Section 9.
  43. func parseOID(r io.Reader) (oid []byte, err error) {
  44. buf := make([]byte, maxOIDLength)
  45. if _, err = readFull(r, buf[:1]); err != nil {
  46. return
  47. }
  48. oidLen := buf[0]
  49. if int(oidLen) > len(buf) {
  50. err = errors.UnsupportedError("invalid oid length: " + strconv.Itoa(int(oidLen)))
  51. return
  52. }
  53. oid = buf[:oidLen]
  54. _, err = readFull(r, oid)
  55. return
  56. }
  57. func (f *ecdsaKey) parse(r io.Reader) (err error) {
  58. if f.oid, err = parseOID(r); err != nil {
  59. return err
  60. }
  61. f.p.bytes, f.p.bitLength, err = readMPI(r)
  62. return
  63. }
  64. func (f *ecdsaKey) serialize(w io.Writer) (err error) {
  65. buf := make([]byte, maxOIDLength+1)
  66. buf[0] = byte(len(f.oid))
  67. copy(buf[1:], f.oid)
  68. if _, err = w.Write(buf[:len(f.oid)+1]); err != nil {
  69. return
  70. }
  71. return writeMPIs(w, f.p)
  72. }
  73. func (f *ecdsaKey) newECDSA() (*ecdsa.PublicKey, error) {
  74. var c elliptic.Curve
  75. if bytes.Equal(f.oid, oidCurveP256) {
  76. c = elliptic.P256()
  77. } else if bytes.Equal(f.oid, oidCurveP384) {
  78. c = elliptic.P384()
  79. } else if bytes.Equal(f.oid, oidCurveP521) {
  80. c = elliptic.P521()
  81. } else {
  82. return nil, errors.UnsupportedError(fmt.Sprintf("unsupported oid: %x", f.oid))
  83. }
  84. x, y := elliptic.Unmarshal(c, f.p.bytes)
  85. if x == nil {
  86. return nil, errors.UnsupportedError("failed to parse EC point")
  87. }
  88. return &ecdsa.PublicKey{Curve: c, X: x, Y: y}, nil
  89. }
  90. func (f *ecdsaKey) byteLen() int {
  91. return 1 + len(f.oid) + 2 + len(f.p.bytes)
  92. }
  93. type kdfHashFunction byte
  94. type kdfAlgorithm byte
  95. // ecdhKdf stores key derivation function parameters
  96. // used for ECDH encryption. See RFC 6637, Section 9.
  97. type ecdhKdf struct {
  98. KdfHash kdfHashFunction
  99. KdfAlgo kdfAlgorithm
  100. }
  101. func (f *ecdhKdf) parse(r io.Reader) (err error) {
  102. buf := make([]byte, 1)
  103. if _, err = readFull(r, buf); err != nil {
  104. return
  105. }
  106. kdfLen := int(buf[0])
  107. if kdfLen < 3 {
  108. return errors.UnsupportedError("Unsupported ECDH KDF length: " + strconv.Itoa(kdfLen))
  109. }
  110. buf = make([]byte, kdfLen)
  111. if _, err = readFull(r, buf); err != nil {
  112. return
  113. }
  114. reserved := int(buf[0])
  115. f.KdfHash = kdfHashFunction(buf[1])
  116. f.KdfAlgo = kdfAlgorithm(buf[2])
  117. if reserved != 0x01 {
  118. return errors.UnsupportedError("Unsupported KDF reserved field: " + strconv.Itoa(reserved))
  119. }
  120. return
  121. }
  122. func (f *ecdhKdf) serialize(w io.Writer) (err error) {
  123. buf := make([]byte, 4)
  124. // See RFC 6637, Section 9, Algorithm-Specific Fields for ECDH keys.
  125. buf[0] = byte(0x03) // Length of the following fields
  126. buf[1] = byte(0x01) // Reserved for future extensions, must be 1 for now
  127. buf[2] = byte(f.KdfHash)
  128. buf[3] = byte(f.KdfAlgo)
  129. _, err = w.Write(buf[:])
  130. return
  131. }
  132. func (f *ecdhKdf) byteLen() int {
  133. return 4
  134. }
  135. // PublicKey represents an OpenPGP public key. See RFC 4880, section 5.5.2.
  136. type PublicKey struct {
  137. CreationTime time.Time
  138. PubKeyAlgo PublicKeyAlgorithm
  139. PublicKey interface{} // *rsa.PublicKey, *dsa.PublicKey or *ecdsa.PublicKey
  140. Fingerprint [20]byte
  141. KeyId uint64
  142. IsSubkey bool
  143. n, e, p, q, g, y parsedMPI
  144. // RFC 6637 fields
  145. ec *ecdsaKey
  146. ecdh *ecdhKdf
  147. }
  148. // signingKey provides a convenient abstraction over signature verification
  149. // for v3 and v4 public keys.
  150. type signingKey interface {
  151. SerializeSignaturePrefix(io.Writer)
  152. serializeWithoutHeaders(io.Writer) error
  153. }
  154. func fromBig(n *big.Int) parsedMPI {
  155. return parsedMPI{
  156. bytes: n.Bytes(),
  157. bitLength: uint16(n.BitLen()),
  158. }
  159. }
  160. // NewRSAPublicKey returns a PublicKey that wraps the given rsa.PublicKey.
  161. func NewRSAPublicKey(creationTime time.Time, pub *rsa.PublicKey) *PublicKey {
  162. pk := &PublicKey{
  163. CreationTime: creationTime,
  164. PubKeyAlgo: PubKeyAlgoRSA,
  165. PublicKey: pub,
  166. n: fromBig(pub.N),
  167. e: fromBig(big.NewInt(int64(pub.E))),
  168. }
  169. pk.setFingerPrintAndKeyId()
  170. return pk
  171. }
  172. // NewDSAPublicKey returns a PublicKey that wraps the given dsa.PublicKey.
  173. func NewDSAPublicKey(creationTime time.Time, pub *dsa.PublicKey) *PublicKey {
  174. pk := &PublicKey{
  175. CreationTime: creationTime,
  176. PubKeyAlgo: PubKeyAlgoDSA,
  177. PublicKey: pub,
  178. p: fromBig(pub.P),
  179. q: fromBig(pub.Q),
  180. g: fromBig(pub.G),
  181. y: fromBig(pub.Y),
  182. }
  183. pk.setFingerPrintAndKeyId()
  184. return pk
  185. }
  186. // NewElGamalPublicKey returns a PublicKey that wraps the given elgamal.PublicKey.
  187. func NewElGamalPublicKey(creationTime time.Time, pub *elgamal.PublicKey) *PublicKey {
  188. pk := &PublicKey{
  189. CreationTime: creationTime,
  190. PubKeyAlgo: PubKeyAlgoElGamal,
  191. PublicKey: pub,
  192. p: fromBig(pub.P),
  193. g: fromBig(pub.G),
  194. y: fromBig(pub.Y),
  195. }
  196. pk.setFingerPrintAndKeyId()
  197. return pk
  198. }
  199. func NewECDSAPublicKey(creationTime time.Time, pub *ecdsa.PublicKey) *PublicKey {
  200. pk := &PublicKey{
  201. CreationTime: creationTime,
  202. PubKeyAlgo: PubKeyAlgoECDSA,
  203. PublicKey: pub,
  204. ec: new(ecdsaKey),
  205. }
  206. switch pub.Curve {
  207. case elliptic.P256():
  208. pk.ec.oid = oidCurveP256
  209. case elliptic.P384():
  210. pk.ec.oid = oidCurveP384
  211. case elliptic.P521():
  212. pk.ec.oid = oidCurveP521
  213. default:
  214. panic("unknown elliptic curve")
  215. }
  216. pk.ec.p.bytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y)
  217. // The bit length is 3 (for the 0x04 specifying an uncompressed key)
  218. // plus two field elements (for x and y), which are rounded up to the
  219. // nearest byte. See https://tools.ietf.org/html/rfc6637#section-6
  220. fieldBytes := (pub.Curve.Params().BitSize + 7) & ^7
  221. pk.ec.p.bitLength = uint16(3 + fieldBytes + fieldBytes)
  222. pk.setFingerPrintAndKeyId()
  223. return pk
  224. }
  225. func (pk *PublicKey) parse(r io.Reader) (err error) {
  226. // RFC 4880, section 5.5.2
  227. var buf [6]byte
  228. _, err = readFull(r, buf[:])
  229. if err != nil {
  230. return
  231. }
  232. if buf[0] != 4 {
  233. return errors.UnsupportedError("public key version")
  234. }
  235. pk.CreationTime = time.Unix(int64(uint32(buf[1])<<24|uint32(buf[2])<<16|uint32(buf[3])<<8|uint32(buf[4])), 0)
  236. pk.PubKeyAlgo = PublicKeyAlgorithm(buf[5])
  237. switch pk.PubKeyAlgo {
  238. case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly:
  239. err = pk.parseRSA(r)
  240. case PubKeyAlgoDSA:
  241. err = pk.parseDSA(r)
  242. case PubKeyAlgoElGamal:
  243. err = pk.parseElGamal(r)
  244. case PubKeyAlgoECDSA:
  245. pk.ec = new(ecdsaKey)
  246. if err = pk.ec.parse(r); err != nil {
  247. return err
  248. }
  249. pk.PublicKey, err = pk.ec.newECDSA()
  250. case PubKeyAlgoECDH:
  251. pk.ec = new(ecdsaKey)
  252. if err = pk.ec.parse(r); err != nil {
  253. return
  254. }
  255. pk.ecdh = new(ecdhKdf)
  256. if err = pk.ecdh.parse(r); err != nil {
  257. return
  258. }
  259. // The ECDH key is stored in an ecdsa.PublicKey for convenience.
  260. pk.PublicKey, err = pk.ec.newECDSA()
  261. default:
  262. err = errors.UnsupportedError("public key type: " + strconv.Itoa(int(pk.PubKeyAlgo)))
  263. }
  264. if err != nil {
  265. return
  266. }
  267. pk.setFingerPrintAndKeyId()
  268. return
  269. }
  270. func (pk *PublicKey) setFingerPrintAndKeyId() {
  271. // RFC 4880, section 12.2
  272. fingerPrint := sha1.New()
  273. pk.SerializeSignaturePrefix(fingerPrint)
  274. pk.serializeWithoutHeaders(fingerPrint)
  275. copy(pk.Fingerprint[:], fingerPrint.Sum(nil))
  276. pk.KeyId = binary.BigEndian.Uint64(pk.Fingerprint[12:20])
  277. }
  278. // parseRSA parses RSA public key material from the given Reader. See RFC 4880,
  279. // section 5.5.2.
  280. func (pk *PublicKey) parseRSA(r io.Reader) (err error) {
  281. pk.n.bytes, pk.n.bitLength, err = readMPI(r)
  282. if err != nil {
  283. return
  284. }
  285. pk.e.bytes, pk.e.bitLength, err = readMPI(r)
  286. if err != nil {
  287. return
  288. }
  289. if len(pk.e.bytes) > 3 {
  290. err = errors.UnsupportedError("large public exponent")
  291. return
  292. }
  293. rsa := &rsa.PublicKey{
  294. N: new(big.Int).SetBytes(pk.n.bytes),
  295. E: 0,
  296. }
  297. for i := 0; i < len(pk.e.bytes); i++ {
  298. rsa.E <<= 8
  299. rsa.E |= int(pk.e.bytes[i])
  300. }
  301. pk.PublicKey = rsa
  302. return
  303. }
  304. // parseDSA parses DSA public key material from the given Reader. See RFC 4880,
  305. // section 5.5.2.
  306. func (pk *PublicKey) parseDSA(r io.Reader) (err error) {
  307. pk.p.bytes, pk.p.bitLength, err = readMPI(r)
  308. if err != nil {
  309. return
  310. }
  311. pk.q.bytes, pk.q.bitLength, err = readMPI(r)
  312. if err != nil {
  313. return
  314. }
  315. pk.g.bytes, pk.g.bitLength, err = readMPI(r)
  316. if err != nil {
  317. return
  318. }
  319. pk.y.bytes, pk.y.bitLength, err = readMPI(r)
  320. if err != nil {
  321. return
  322. }
  323. dsa := new(dsa.PublicKey)
  324. dsa.P = new(big.Int).SetBytes(pk.p.bytes)
  325. dsa.Q = new(big.Int).SetBytes(pk.q.bytes)
  326. dsa.G = new(big.Int).SetBytes(pk.g.bytes)
  327. dsa.Y = new(big.Int).SetBytes(pk.y.bytes)
  328. pk.PublicKey = dsa
  329. return
  330. }
  331. // parseElGamal parses ElGamal public key material from the given Reader. See
  332. // RFC 4880, section 5.5.2.
  333. func (pk *PublicKey) parseElGamal(r io.Reader) (err error) {
  334. pk.p.bytes, pk.p.bitLength, err = readMPI(r)
  335. if err != nil {
  336. return
  337. }
  338. pk.g.bytes, pk.g.bitLength, err = readMPI(r)
  339. if err != nil {
  340. return
  341. }
  342. pk.y.bytes, pk.y.bitLength, err = readMPI(r)
  343. if err != nil {
  344. return
  345. }
  346. elgamal := new(elgamal.PublicKey)
  347. elgamal.P = new(big.Int).SetBytes(pk.p.bytes)
  348. elgamal.G = new(big.Int).SetBytes(pk.g.bytes)
  349. elgamal.Y = new(big.Int).SetBytes(pk.y.bytes)
  350. pk.PublicKey = elgamal
  351. return
  352. }
  353. // SerializeSignaturePrefix writes the prefix for this public key to the given Writer.
  354. // The prefix is used when calculating a signature over this public key. See
  355. // RFC 4880, section 5.2.4.
  356. func (pk *PublicKey) SerializeSignaturePrefix(h io.Writer) {
  357. var pLength uint16
  358. switch pk.PubKeyAlgo {
  359. case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly:
  360. pLength += 2 + uint16(len(pk.n.bytes))
  361. pLength += 2 + uint16(len(pk.e.bytes))
  362. case PubKeyAlgoDSA:
  363. pLength += 2 + uint16(len(pk.p.bytes))
  364. pLength += 2 + uint16(len(pk.q.bytes))
  365. pLength += 2 + uint16(len(pk.g.bytes))
  366. pLength += 2 + uint16(len(pk.y.bytes))
  367. case PubKeyAlgoElGamal:
  368. pLength += 2 + uint16(len(pk.p.bytes))
  369. pLength += 2 + uint16(len(pk.g.bytes))
  370. pLength += 2 + uint16(len(pk.y.bytes))
  371. case PubKeyAlgoECDSA:
  372. pLength += uint16(pk.ec.byteLen())
  373. case PubKeyAlgoECDH:
  374. pLength += uint16(pk.ec.byteLen())
  375. pLength += uint16(pk.ecdh.byteLen())
  376. default:
  377. panic("unknown public key algorithm")
  378. }
  379. pLength += 6
  380. h.Write([]byte{0x99, byte(pLength >> 8), byte(pLength)})
  381. return
  382. }
  383. func (pk *PublicKey) Serialize(w io.Writer) (err error) {
  384. length := 6 // 6 byte header
  385. switch pk.PubKeyAlgo {
  386. case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly:
  387. length += 2 + len(pk.n.bytes)
  388. length += 2 + len(pk.e.bytes)
  389. case PubKeyAlgoDSA:
  390. length += 2 + len(pk.p.bytes)
  391. length += 2 + len(pk.q.bytes)
  392. length += 2 + len(pk.g.bytes)
  393. length += 2 + len(pk.y.bytes)
  394. case PubKeyAlgoElGamal:
  395. length += 2 + len(pk.p.bytes)
  396. length += 2 + len(pk.g.bytes)
  397. length += 2 + len(pk.y.bytes)
  398. case PubKeyAlgoECDSA:
  399. length += pk.ec.byteLen()
  400. case PubKeyAlgoECDH:
  401. length += pk.ec.byteLen()
  402. length += pk.ecdh.byteLen()
  403. default:
  404. panic("unknown public key algorithm")
  405. }
  406. packetType := packetTypePublicKey
  407. if pk.IsSubkey {
  408. packetType = packetTypePublicSubkey
  409. }
  410. err = serializeHeader(w, packetType, length)
  411. if err != nil {
  412. return
  413. }
  414. return pk.serializeWithoutHeaders(w)
  415. }
  416. // serializeWithoutHeaders marshals the PublicKey to w in the form of an
  417. // OpenPGP public key packet, not including the packet header.
  418. func (pk *PublicKey) serializeWithoutHeaders(w io.Writer) (err error) {
  419. var buf [6]byte
  420. buf[0] = 4
  421. t := uint32(pk.CreationTime.Unix())
  422. buf[1] = byte(t >> 24)
  423. buf[2] = byte(t >> 16)
  424. buf[3] = byte(t >> 8)
  425. buf[4] = byte(t)
  426. buf[5] = byte(pk.PubKeyAlgo)
  427. _, err = w.Write(buf[:])
  428. if err != nil {
  429. return
  430. }
  431. switch pk.PubKeyAlgo {
  432. case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly:
  433. return writeMPIs(w, pk.n, pk.e)
  434. case PubKeyAlgoDSA:
  435. return writeMPIs(w, pk.p, pk.q, pk.g, pk.y)
  436. case PubKeyAlgoElGamal:
  437. return writeMPIs(w, pk.p, pk.g, pk.y)
  438. case PubKeyAlgoECDSA:
  439. return pk.ec.serialize(w)
  440. case PubKeyAlgoECDH:
  441. if err = pk.ec.serialize(w); err != nil {
  442. return
  443. }
  444. return pk.ecdh.serialize(w)
  445. }
  446. return errors.InvalidArgumentError("bad public-key algorithm")
  447. }
  448. // CanSign returns true iff this public key can generate signatures
  449. func (pk *PublicKey) CanSign() bool {
  450. return pk.PubKeyAlgo != PubKeyAlgoRSAEncryptOnly && pk.PubKeyAlgo != PubKeyAlgoElGamal
  451. }
  452. // VerifySignature returns nil iff sig is a valid signature, made by this
  453. // public key, of the data hashed into signed. signed is mutated by this call.
  454. func (pk *PublicKey) VerifySignature(signed hash.Hash, sig *Signature) (err error) {
  455. if !pk.CanSign() {
  456. return errors.InvalidArgumentError("public key cannot generate signatures")
  457. }
  458. signed.Write(sig.HashSuffix)
  459. hashBytes := signed.Sum(nil)
  460. if hashBytes[0] != sig.HashTag[0] || hashBytes[1] != sig.HashTag[1] {
  461. return errors.SignatureError("hash tag doesn't match")
  462. }
  463. if pk.PubKeyAlgo != sig.PubKeyAlgo {
  464. return errors.InvalidArgumentError("public key and signature use different algorithms")
  465. }
  466. switch pk.PubKeyAlgo {
  467. case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly:
  468. rsaPublicKey, _ := pk.PublicKey.(*rsa.PublicKey)
  469. err = rsa.VerifyPKCS1v15(rsaPublicKey, sig.Hash, hashBytes, padToKeySize(rsaPublicKey, sig.RSASignature.bytes))
  470. if err != nil {
  471. return errors.SignatureError("RSA verification failure")
  472. }
  473. return nil
  474. case PubKeyAlgoDSA:
  475. dsaPublicKey, _ := pk.PublicKey.(*dsa.PublicKey)
  476. // Need to truncate hashBytes to match FIPS 186-3 section 4.6.
  477. subgroupSize := (dsaPublicKey.Q.BitLen() + 7) / 8
  478. if len(hashBytes) > subgroupSize {
  479. hashBytes = hashBytes[:subgroupSize]
  480. }
  481. if !dsa.Verify(dsaPublicKey, hashBytes, new(big.Int).SetBytes(sig.DSASigR.bytes), new(big.Int).SetBytes(sig.DSASigS.bytes)) {
  482. return errors.SignatureError("DSA verification failure")
  483. }
  484. return nil
  485. case PubKeyAlgoECDSA:
  486. ecdsaPublicKey := pk.PublicKey.(*ecdsa.PublicKey)
  487. if !ecdsa.Verify(ecdsaPublicKey, hashBytes, new(big.Int).SetBytes(sig.ECDSASigR.bytes), new(big.Int).SetBytes(sig.ECDSASigS.bytes)) {
  488. return errors.SignatureError("ECDSA verification failure")
  489. }
  490. return nil
  491. default:
  492. return errors.SignatureError("Unsupported public key algorithm used in signature")
  493. }
  494. }
  495. // VerifySignatureV3 returns nil iff sig is a valid signature, made by this
  496. // public key, of the data hashed into signed. signed is mutated by this call.
  497. func (pk *PublicKey) VerifySignatureV3(signed hash.Hash, sig *SignatureV3) (err error) {
  498. if !pk.CanSign() {
  499. return errors.InvalidArgumentError("public key cannot generate signatures")
  500. }
  501. suffix := make([]byte, 5)
  502. suffix[0] = byte(sig.SigType)
  503. binary.BigEndian.PutUint32(suffix[1:], uint32(sig.CreationTime.Unix()))
  504. signed.Write(suffix)
  505. hashBytes := signed.Sum(nil)
  506. if hashBytes[0] != sig.HashTag[0] || hashBytes[1] != sig.HashTag[1] {
  507. return errors.SignatureError("hash tag doesn't match")
  508. }
  509. if pk.PubKeyAlgo != sig.PubKeyAlgo {
  510. return errors.InvalidArgumentError("public key and signature use different algorithms")
  511. }
  512. switch pk.PubKeyAlgo {
  513. case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly:
  514. rsaPublicKey := pk.PublicKey.(*rsa.PublicKey)
  515. if err = rsa.VerifyPKCS1v15(rsaPublicKey, sig.Hash, hashBytes, padToKeySize(rsaPublicKey, sig.RSASignature.bytes)); err != nil {
  516. return errors.SignatureError("RSA verification failure")
  517. }
  518. return
  519. case PubKeyAlgoDSA:
  520. dsaPublicKey := pk.PublicKey.(*dsa.PublicKey)
  521. // Need to truncate hashBytes to match FIPS 186-3 section 4.6.
  522. subgroupSize := (dsaPublicKey.Q.BitLen() + 7) / 8
  523. if len(hashBytes) > subgroupSize {
  524. hashBytes = hashBytes[:subgroupSize]
  525. }
  526. if !dsa.Verify(dsaPublicKey, hashBytes, new(big.Int).SetBytes(sig.DSASigR.bytes), new(big.Int).SetBytes(sig.DSASigS.bytes)) {
  527. return errors.SignatureError("DSA verification failure")
  528. }
  529. return nil
  530. default:
  531. panic("shouldn't happen")
  532. }
  533. }
  534. // keySignatureHash returns a Hash of the message that needs to be signed for
  535. // pk to assert a subkey relationship to signed.
  536. func keySignatureHash(pk, signed signingKey, hashFunc crypto.Hash) (h hash.Hash, err error) {
  537. if !hashFunc.Available() {
  538. return nil, errors.UnsupportedError("hash function")
  539. }
  540. h = hashFunc.New()
  541. // RFC 4880, section 5.2.4
  542. pk.SerializeSignaturePrefix(h)
  543. pk.serializeWithoutHeaders(h)
  544. signed.SerializeSignaturePrefix(h)
  545. signed.serializeWithoutHeaders(h)
  546. return
  547. }
  548. // VerifyKeySignature returns nil iff sig is a valid signature, made by this
  549. // public key, of signed.
  550. func (pk *PublicKey) VerifyKeySignature(signed *PublicKey, sig *Signature) error {
  551. h, err := keySignatureHash(pk, signed, sig.Hash)
  552. if err != nil {
  553. return err
  554. }
  555. if err = pk.VerifySignature(h, sig); err != nil {
  556. return err
  557. }
  558. if sig.FlagSign {
  559. // Signing subkeys must be cross-signed. See
  560. // https://www.gnupg.org/faq/subkey-cross-certify.html.
  561. if sig.EmbeddedSignature == nil {
  562. return errors.StructuralError("signing subkey is missing cross-signature")
  563. }
  564. // Verify the cross-signature. This is calculated over the same
  565. // data as the main signature, so we cannot just recursively
  566. // call signed.VerifyKeySignature(...)
  567. if h, err = keySignatureHash(pk, signed, sig.EmbeddedSignature.Hash); err != nil {
  568. return errors.StructuralError("error while hashing for cross-signature: " + err.Error())
  569. }
  570. if err := signed.VerifySignature(h, sig.EmbeddedSignature); err != nil {
  571. return errors.StructuralError("error while verifying cross-signature: " + err.Error())
  572. }
  573. }
  574. return nil
  575. }
  576. func keyRevocationHash(pk signingKey, hashFunc crypto.Hash) (h hash.Hash, err error) {
  577. if !hashFunc.Available() {
  578. return nil, errors.UnsupportedError("hash function")
  579. }
  580. h = hashFunc.New()
  581. // RFC 4880, section 5.2.4
  582. pk.SerializeSignaturePrefix(h)
  583. pk.serializeWithoutHeaders(h)
  584. return
  585. }
  586. // VerifyRevocationSignature returns nil iff sig is a valid signature, made by this
  587. // public key.
  588. func (pk *PublicKey) VerifyRevocationSignature(sig *Signature) (err error) {
  589. h, err := keyRevocationHash(pk, sig.Hash)
  590. if err != nil {
  591. return err
  592. }
  593. return pk.VerifySignature(h, sig)
  594. }
  595. // userIdSignatureHash returns a Hash of the message that needs to be signed
  596. // to assert that pk is a valid key for id.
  597. func userIdSignatureHash(id string, pk *PublicKey, hashFunc crypto.Hash) (h hash.Hash, err error) {
  598. if !hashFunc.Available() {
  599. return nil, errors.UnsupportedError("hash function")
  600. }
  601. h = hashFunc.New()
  602. // RFC 4880, section 5.2.4
  603. pk.SerializeSignaturePrefix(h)
  604. pk.serializeWithoutHeaders(h)
  605. var buf [5]byte
  606. buf[0] = 0xb4
  607. buf[1] = byte(len(id) >> 24)
  608. buf[2] = byte(len(id) >> 16)
  609. buf[3] = byte(len(id) >> 8)
  610. buf[4] = byte(len(id))
  611. h.Write(buf[:])
  612. h.Write([]byte(id))
  613. return
  614. }
  615. // VerifyUserIdSignature returns nil iff sig is a valid signature, made by this
  616. // public key, that id is the identity of pub.
  617. func (pk *PublicKey) VerifyUserIdSignature(id string, pub *PublicKey, sig *Signature) (err error) {
  618. h, err := userIdSignatureHash(id, pub, sig.Hash)
  619. if err != nil {
  620. return err
  621. }
  622. return pk.VerifySignature(h, sig)
  623. }
  624. // VerifyUserIdSignatureV3 returns nil iff sig is a valid signature, made by this
  625. // public key, that id is the identity of pub.
  626. func (pk *PublicKey) VerifyUserIdSignatureV3(id string, pub *PublicKey, sig *SignatureV3) (err error) {
  627. h, err := userIdSignatureV3Hash(id, pub, sig.Hash)
  628. if err != nil {
  629. return err
  630. }
  631. return pk.VerifySignatureV3(h, sig)
  632. }
  633. // KeyIdString returns the public key's fingerprint in capital hex
  634. // (e.g. "6C7EE1B8621CC013").
  635. func (pk *PublicKey) KeyIdString() string {
  636. return fmt.Sprintf("%X", pk.Fingerprint[12:20])
  637. }
  638. // KeyIdShortString returns the short form of public key's fingerprint
  639. // in capital hex, as shown by gpg --list-keys (e.g. "621CC013").
  640. func (pk *PublicKey) KeyIdShortString() string {
  641. return fmt.Sprintf("%X", pk.Fingerprint[16:20])
  642. }
  643. // A parsedMPI is used to store the contents of a big integer, along with the
  644. // bit length that was specified in the original input. This allows the MPI to
  645. // be reserialized exactly.
  646. type parsedMPI struct {
  647. bytes []byte
  648. bitLength uint16
  649. }
  650. // writeMPIs is a utility function for serializing several big integers to the
  651. // given Writer.
  652. func writeMPIs(w io.Writer, mpis ...parsedMPI) (err error) {
  653. for _, mpi := range mpis {
  654. err = writeMPI(w, mpi.bitLength, mpi.bytes)
  655. if err != nil {
  656. return
  657. }
  658. }
  659. return
  660. }
  661. // BitLength returns the bit length for the given public key.
  662. func (pk *PublicKey) BitLength() (bitLength uint16, err error) {
  663. switch pk.PubKeyAlgo {
  664. case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly:
  665. bitLength = pk.n.bitLength
  666. case PubKeyAlgoDSA:
  667. bitLength = pk.p.bitLength
  668. case PubKeyAlgoElGamal:
  669. bitLength = pk.p.bitLength
  670. default:
  671. err = errors.InvalidArgumentError("bad public-key algorithm")
  672. }
  673. return
  674. }