public_key.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  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. pk.ec.p.bitLength = uint16(8 * len(pk.ec.p.bytes))
  218. pk.setFingerPrintAndKeyId()
  219. return pk
  220. }
  221. func (pk *PublicKey) parse(r io.Reader) (err error) {
  222. // RFC 4880, section 5.5.2
  223. var buf [6]byte
  224. _, err = readFull(r, buf[:])
  225. if err != nil {
  226. return
  227. }
  228. if buf[0] != 4 {
  229. return errors.UnsupportedError("public key version")
  230. }
  231. pk.CreationTime = time.Unix(int64(uint32(buf[1])<<24|uint32(buf[2])<<16|uint32(buf[3])<<8|uint32(buf[4])), 0)
  232. pk.PubKeyAlgo = PublicKeyAlgorithm(buf[5])
  233. switch pk.PubKeyAlgo {
  234. case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly:
  235. err = pk.parseRSA(r)
  236. case PubKeyAlgoDSA:
  237. err = pk.parseDSA(r)
  238. case PubKeyAlgoElGamal:
  239. err = pk.parseElGamal(r)
  240. case PubKeyAlgoECDSA:
  241. pk.ec = new(ecdsaKey)
  242. if err = pk.ec.parse(r); err != nil {
  243. return err
  244. }
  245. pk.PublicKey, err = pk.ec.newECDSA()
  246. case PubKeyAlgoECDH:
  247. pk.ec = new(ecdsaKey)
  248. if err = pk.ec.parse(r); err != nil {
  249. return
  250. }
  251. pk.ecdh = new(ecdhKdf)
  252. if err = pk.ecdh.parse(r); err != nil {
  253. return
  254. }
  255. // The ECDH key is stored in an ecdsa.PublicKey for convenience.
  256. pk.PublicKey, err = pk.ec.newECDSA()
  257. default:
  258. err = errors.UnsupportedError("public key type: " + strconv.Itoa(int(pk.PubKeyAlgo)))
  259. }
  260. if err != nil {
  261. return
  262. }
  263. pk.setFingerPrintAndKeyId()
  264. return
  265. }
  266. func (pk *PublicKey) setFingerPrintAndKeyId() {
  267. // RFC 4880, section 12.2
  268. fingerPrint := sha1.New()
  269. pk.SerializeSignaturePrefix(fingerPrint)
  270. pk.serializeWithoutHeaders(fingerPrint)
  271. copy(pk.Fingerprint[:], fingerPrint.Sum(nil))
  272. pk.KeyId = binary.BigEndian.Uint64(pk.Fingerprint[12:20])
  273. }
  274. // parseRSA parses RSA public key material from the given Reader. See RFC 4880,
  275. // section 5.5.2.
  276. func (pk *PublicKey) parseRSA(r io.Reader) (err error) {
  277. pk.n.bytes, pk.n.bitLength, err = readMPI(r)
  278. if err != nil {
  279. return
  280. }
  281. pk.e.bytes, pk.e.bitLength, err = readMPI(r)
  282. if err != nil {
  283. return
  284. }
  285. if len(pk.e.bytes) > 3 {
  286. err = errors.UnsupportedError("large public exponent")
  287. return
  288. }
  289. rsa := &rsa.PublicKey{
  290. N: new(big.Int).SetBytes(pk.n.bytes),
  291. E: 0,
  292. }
  293. for i := 0; i < len(pk.e.bytes); i++ {
  294. rsa.E <<= 8
  295. rsa.E |= int(pk.e.bytes[i])
  296. }
  297. pk.PublicKey = rsa
  298. return
  299. }
  300. // parseDSA parses DSA public key material from the given Reader. See RFC 4880,
  301. // section 5.5.2.
  302. func (pk *PublicKey) parseDSA(r io.Reader) (err error) {
  303. pk.p.bytes, pk.p.bitLength, err = readMPI(r)
  304. if err != nil {
  305. return
  306. }
  307. pk.q.bytes, pk.q.bitLength, err = readMPI(r)
  308. if err != nil {
  309. return
  310. }
  311. pk.g.bytes, pk.g.bitLength, err = readMPI(r)
  312. if err != nil {
  313. return
  314. }
  315. pk.y.bytes, pk.y.bitLength, err = readMPI(r)
  316. if err != nil {
  317. return
  318. }
  319. dsa := new(dsa.PublicKey)
  320. dsa.P = new(big.Int).SetBytes(pk.p.bytes)
  321. dsa.Q = new(big.Int).SetBytes(pk.q.bytes)
  322. dsa.G = new(big.Int).SetBytes(pk.g.bytes)
  323. dsa.Y = new(big.Int).SetBytes(pk.y.bytes)
  324. pk.PublicKey = dsa
  325. return
  326. }
  327. // parseElGamal parses ElGamal public key material from the given Reader. See
  328. // RFC 4880, section 5.5.2.
  329. func (pk *PublicKey) parseElGamal(r io.Reader) (err error) {
  330. pk.p.bytes, pk.p.bitLength, err = readMPI(r)
  331. if err != nil {
  332. return
  333. }
  334. pk.g.bytes, pk.g.bitLength, err = readMPI(r)
  335. if err != nil {
  336. return
  337. }
  338. pk.y.bytes, pk.y.bitLength, err = readMPI(r)
  339. if err != nil {
  340. return
  341. }
  342. elgamal := new(elgamal.PublicKey)
  343. elgamal.P = new(big.Int).SetBytes(pk.p.bytes)
  344. elgamal.G = new(big.Int).SetBytes(pk.g.bytes)
  345. elgamal.Y = new(big.Int).SetBytes(pk.y.bytes)
  346. pk.PublicKey = elgamal
  347. return
  348. }
  349. // SerializeSignaturePrefix writes the prefix for this public key to the given Writer.
  350. // The prefix is used when calculating a signature over this public key. See
  351. // RFC 4880, section 5.2.4.
  352. func (pk *PublicKey) SerializeSignaturePrefix(h io.Writer) {
  353. var pLength uint16
  354. switch pk.PubKeyAlgo {
  355. case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly:
  356. pLength += 2 + uint16(len(pk.n.bytes))
  357. pLength += 2 + uint16(len(pk.e.bytes))
  358. case PubKeyAlgoDSA:
  359. pLength += 2 + uint16(len(pk.p.bytes))
  360. pLength += 2 + uint16(len(pk.q.bytes))
  361. pLength += 2 + uint16(len(pk.g.bytes))
  362. pLength += 2 + uint16(len(pk.y.bytes))
  363. case PubKeyAlgoElGamal:
  364. pLength += 2 + uint16(len(pk.p.bytes))
  365. pLength += 2 + uint16(len(pk.g.bytes))
  366. pLength += 2 + uint16(len(pk.y.bytes))
  367. case PubKeyAlgoECDSA:
  368. pLength += uint16(pk.ec.byteLen())
  369. case PubKeyAlgoECDH:
  370. pLength += uint16(pk.ec.byteLen())
  371. pLength += uint16(pk.ecdh.byteLen())
  372. default:
  373. panic("unknown public key algorithm")
  374. }
  375. pLength += 6
  376. h.Write([]byte{0x99, byte(pLength >> 8), byte(pLength)})
  377. return
  378. }
  379. func (pk *PublicKey) Serialize(w io.Writer) (err error) {
  380. length := 6 // 6 byte header
  381. switch pk.PubKeyAlgo {
  382. case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly:
  383. length += 2 + len(pk.n.bytes)
  384. length += 2 + len(pk.e.bytes)
  385. case PubKeyAlgoDSA:
  386. length += 2 + len(pk.p.bytes)
  387. length += 2 + len(pk.q.bytes)
  388. length += 2 + len(pk.g.bytes)
  389. length += 2 + len(pk.y.bytes)
  390. case PubKeyAlgoElGamal:
  391. length += 2 + len(pk.p.bytes)
  392. length += 2 + len(pk.g.bytes)
  393. length += 2 + len(pk.y.bytes)
  394. case PubKeyAlgoECDSA:
  395. length += pk.ec.byteLen()
  396. case PubKeyAlgoECDH:
  397. length += pk.ec.byteLen()
  398. length += pk.ecdh.byteLen()
  399. default:
  400. panic("unknown public key algorithm")
  401. }
  402. packetType := packetTypePublicKey
  403. if pk.IsSubkey {
  404. packetType = packetTypePublicSubkey
  405. }
  406. err = serializeHeader(w, packetType, length)
  407. if err != nil {
  408. return
  409. }
  410. return pk.serializeWithoutHeaders(w)
  411. }
  412. // serializeWithoutHeaders marshals the PublicKey to w in the form of an
  413. // OpenPGP public key packet, not including the packet header.
  414. func (pk *PublicKey) serializeWithoutHeaders(w io.Writer) (err error) {
  415. var buf [6]byte
  416. buf[0] = 4
  417. t := uint32(pk.CreationTime.Unix())
  418. buf[1] = byte(t >> 24)
  419. buf[2] = byte(t >> 16)
  420. buf[3] = byte(t >> 8)
  421. buf[4] = byte(t)
  422. buf[5] = byte(pk.PubKeyAlgo)
  423. _, err = w.Write(buf[:])
  424. if err != nil {
  425. return
  426. }
  427. switch pk.PubKeyAlgo {
  428. case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly:
  429. return writeMPIs(w, pk.n, pk.e)
  430. case PubKeyAlgoDSA:
  431. return writeMPIs(w, pk.p, pk.q, pk.g, pk.y)
  432. case PubKeyAlgoElGamal:
  433. return writeMPIs(w, pk.p, pk.g, pk.y)
  434. case PubKeyAlgoECDSA:
  435. return pk.ec.serialize(w)
  436. case PubKeyAlgoECDH:
  437. if err = pk.ec.serialize(w); err != nil {
  438. return
  439. }
  440. return pk.ecdh.serialize(w)
  441. }
  442. return errors.InvalidArgumentError("bad public-key algorithm")
  443. }
  444. // CanSign returns true iff this public key can generate signatures
  445. func (pk *PublicKey) CanSign() bool {
  446. return pk.PubKeyAlgo != PubKeyAlgoRSAEncryptOnly && pk.PubKeyAlgo != PubKeyAlgoElGamal
  447. }
  448. // VerifySignature returns nil iff sig is a valid signature, made by this
  449. // public key, of the data hashed into signed. signed is mutated by this call.
  450. func (pk *PublicKey) VerifySignature(signed hash.Hash, sig *Signature) (err error) {
  451. if !pk.CanSign() {
  452. return errors.InvalidArgumentError("public key cannot generate signatures")
  453. }
  454. signed.Write(sig.HashSuffix)
  455. hashBytes := signed.Sum(nil)
  456. if hashBytes[0] != sig.HashTag[0] || hashBytes[1] != sig.HashTag[1] {
  457. return errors.SignatureError("hash tag doesn't match")
  458. }
  459. if pk.PubKeyAlgo != sig.PubKeyAlgo {
  460. return errors.InvalidArgumentError("public key and signature use different algorithms")
  461. }
  462. switch pk.PubKeyAlgo {
  463. case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly:
  464. rsaPublicKey, _ := pk.PublicKey.(*rsa.PublicKey)
  465. err = rsa.VerifyPKCS1v15(rsaPublicKey, sig.Hash, hashBytes, sig.RSASignature.bytes)
  466. if err != nil {
  467. return errors.SignatureError("RSA verification failure")
  468. }
  469. return nil
  470. case PubKeyAlgoDSA:
  471. dsaPublicKey, _ := pk.PublicKey.(*dsa.PublicKey)
  472. // Need to truncate hashBytes to match FIPS 186-3 section 4.6.
  473. subgroupSize := (dsaPublicKey.Q.BitLen() + 7) / 8
  474. if len(hashBytes) > subgroupSize {
  475. hashBytes = hashBytes[:subgroupSize]
  476. }
  477. if !dsa.Verify(dsaPublicKey, hashBytes, new(big.Int).SetBytes(sig.DSASigR.bytes), new(big.Int).SetBytes(sig.DSASigS.bytes)) {
  478. return errors.SignatureError("DSA verification failure")
  479. }
  480. return nil
  481. case PubKeyAlgoECDSA:
  482. ecdsaPublicKey := pk.PublicKey.(*ecdsa.PublicKey)
  483. if !ecdsa.Verify(ecdsaPublicKey, hashBytes, new(big.Int).SetBytes(sig.ECDSASigR.bytes), new(big.Int).SetBytes(sig.ECDSASigS.bytes)) {
  484. return errors.SignatureError("ECDSA verification failure")
  485. }
  486. return nil
  487. default:
  488. return errors.SignatureError("Unsupported public key algorithm used in signature")
  489. }
  490. }
  491. // VerifySignatureV3 returns nil iff sig is a valid signature, made by this
  492. // public key, of the data hashed into signed. signed is mutated by this call.
  493. func (pk *PublicKey) VerifySignatureV3(signed hash.Hash, sig *SignatureV3) (err error) {
  494. if !pk.CanSign() {
  495. return errors.InvalidArgumentError("public key cannot generate signatures")
  496. }
  497. suffix := make([]byte, 5)
  498. suffix[0] = byte(sig.SigType)
  499. binary.BigEndian.PutUint32(suffix[1:], uint32(sig.CreationTime.Unix()))
  500. signed.Write(suffix)
  501. hashBytes := signed.Sum(nil)
  502. if hashBytes[0] != sig.HashTag[0] || hashBytes[1] != sig.HashTag[1] {
  503. return errors.SignatureError("hash tag doesn't match")
  504. }
  505. if pk.PubKeyAlgo != sig.PubKeyAlgo {
  506. return errors.InvalidArgumentError("public key and signature use different algorithms")
  507. }
  508. switch pk.PubKeyAlgo {
  509. case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly:
  510. rsaPublicKey := pk.PublicKey.(*rsa.PublicKey)
  511. if err = rsa.VerifyPKCS1v15(rsaPublicKey, sig.Hash, hashBytes, sig.RSASignature.bytes); err != nil {
  512. return errors.SignatureError("RSA verification failure")
  513. }
  514. return
  515. case PubKeyAlgoDSA:
  516. dsaPublicKey := pk.PublicKey.(*dsa.PublicKey)
  517. // Need to truncate hashBytes to match FIPS 186-3 section 4.6.
  518. subgroupSize := (dsaPublicKey.Q.BitLen() + 7) / 8
  519. if len(hashBytes) > subgroupSize {
  520. hashBytes = hashBytes[:subgroupSize]
  521. }
  522. if !dsa.Verify(dsaPublicKey, hashBytes, new(big.Int).SetBytes(sig.DSASigR.bytes), new(big.Int).SetBytes(sig.DSASigS.bytes)) {
  523. return errors.SignatureError("DSA verification failure")
  524. }
  525. return nil
  526. default:
  527. panic("shouldn't happen")
  528. }
  529. }
  530. // keySignatureHash returns a Hash of the message that needs to be signed for
  531. // pk to assert a subkey relationship to signed.
  532. func keySignatureHash(pk, signed signingKey, hashFunc crypto.Hash) (h hash.Hash, err error) {
  533. if !hashFunc.Available() {
  534. return nil, errors.UnsupportedError("hash function")
  535. }
  536. h = hashFunc.New()
  537. // RFC 4880, section 5.2.4
  538. pk.SerializeSignaturePrefix(h)
  539. pk.serializeWithoutHeaders(h)
  540. signed.SerializeSignaturePrefix(h)
  541. signed.serializeWithoutHeaders(h)
  542. return
  543. }
  544. // VerifyKeySignature returns nil iff sig is a valid signature, made by this
  545. // public key, of signed.
  546. func (pk *PublicKey) VerifyKeySignature(signed *PublicKey, sig *Signature) error {
  547. h, err := keySignatureHash(pk, signed, sig.Hash)
  548. if err != nil {
  549. return err
  550. }
  551. if err = pk.VerifySignature(h, sig); err != nil {
  552. return err
  553. }
  554. if sig.FlagSign {
  555. // Signing subkeys must be cross-signed. See
  556. // https://www.gnupg.org/faq/subkey-cross-certify.html.
  557. if sig.EmbeddedSignature == nil {
  558. return errors.StructuralError("signing subkey is missing cross-signature")
  559. }
  560. // Verify the cross-signature. This is calculated over the same
  561. // data as the main signature, so we cannot just recursively
  562. // call signed.VerifyKeySignature(...)
  563. if h, err = keySignatureHash(pk, signed, sig.EmbeddedSignature.Hash); err != nil {
  564. return errors.StructuralError("error while hashing for cross-signature: " + err.Error())
  565. }
  566. if err := signed.VerifySignature(h, sig.EmbeddedSignature); err != nil {
  567. return errors.StructuralError("error while verifying cross-signature: " + err.Error())
  568. }
  569. }
  570. return nil
  571. }
  572. func keyRevocationHash(pk signingKey, hashFunc crypto.Hash) (h hash.Hash, err error) {
  573. if !hashFunc.Available() {
  574. return nil, errors.UnsupportedError("hash function")
  575. }
  576. h = hashFunc.New()
  577. // RFC 4880, section 5.2.4
  578. pk.SerializeSignaturePrefix(h)
  579. pk.serializeWithoutHeaders(h)
  580. return
  581. }
  582. // VerifyRevocationSignature returns nil iff sig is a valid signature, made by this
  583. // public key.
  584. func (pk *PublicKey) VerifyRevocationSignature(sig *Signature) (err error) {
  585. h, err := keyRevocationHash(pk, sig.Hash)
  586. if err != nil {
  587. return err
  588. }
  589. return pk.VerifySignature(h, sig)
  590. }
  591. // userIdSignatureHash returns a Hash of the message that needs to be signed
  592. // to assert that pk is a valid key for id.
  593. func userIdSignatureHash(id string, pk *PublicKey, hashFunc crypto.Hash) (h hash.Hash, err error) {
  594. if !hashFunc.Available() {
  595. return nil, errors.UnsupportedError("hash function")
  596. }
  597. h = hashFunc.New()
  598. // RFC 4880, section 5.2.4
  599. pk.SerializeSignaturePrefix(h)
  600. pk.serializeWithoutHeaders(h)
  601. var buf [5]byte
  602. buf[0] = 0xb4
  603. buf[1] = byte(len(id) >> 24)
  604. buf[2] = byte(len(id) >> 16)
  605. buf[3] = byte(len(id) >> 8)
  606. buf[4] = byte(len(id))
  607. h.Write(buf[:])
  608. h.Write([]byte(id))
  609. return
  610. }
  611. // VerifyUserIdSignature returns nil iff sig is a valid signature, made by this
  612. // public key, that id is the identity of pub.
  613. func (pk *PublicKey) VerifyUserIdSignature(id string, pub *PublicKey, sig *Signature) (err error) {
  614. h, err := userIdSignatureHash(id, pub, sig.Hash)
  615. if err != nil {
  616. return err
  617. }
  618. return pk.VerifySignature(h, sig)
  619. }
  620. // VerifyUserIdSignatureV3 returns nil iff sig is a valid signature, made by this
  621. // public key, that id is the identity of pub.
  622. func (pk *PublicKey) VerifyUserIdSignatureV3(id string, pub *PublicKey, sig *SignatureV3) (err error) {
  623. h, err := userIdSignatureV3Hash(id, pub, sig.Hash)
  624. if err != nil {
  625. return err
  626. }
  627. return pk.VerifySignatureV3(h, sig)
  628. }
  629. // KeyIdString returns the public key's fingerprint in capital hex
  630. // (e.g. "6C7EE1B8621CC013").
  631. func (pk *PublicKey) KeyIdString() string {
  632. return fmt.Sprintf("%X", pk.Fingerprint[12:20])
  633. }
  634. // KeyIdShortString returns the short form of public key's fingerprint
  635. // in capital hex, as shown by gpg --list-keys (e.g. "621CC013").
  636. func (pk *PublicKey) KeyIdShortString() string {
  637. return fmt.Sprintf("%X", pk.Fingerprint[16:20])
  638. }
  639. // A parsedMPI is used to store the contents of a big integer, along with the
  640. // bit length that was specified in the original input. This allows the MPI to
  641. // be reserialized exactly.
  642. type parsedMPI struct {
  643. bytes []byte
  644. bitLength uint16
  645. }
  646. // writeMPIs is a utility function for serializing several big integers to the
  647. // given Writer.
  648. func writeMPIs(w io.Writer, mpis ...parsedMPI) (err error) {
  649. for _, mpi := range mpis {
  650. err = writeMPI(w, mpi.bitLength, mpi.bytes)
  651. if err != nil {
  652. return
  653. }
  654. }
  655. return
  656. }
  657. // BitLength returns the bit length for the given public key.
  658. func (pk *PublicKey) BitLength() (bitLength uint16, err error) {
  659. switch pk.PubKeyAlgo {
  660. case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly:
  661. bitLength = pk.n.bitLength
  662. case PubKeyAlgoDSA:
  663. bitLength = pk.p.bitLength
  664. case PubKeyAlgoElGamal:
  665. bitLength = pk.p.bitLength
  666. default:
  667. err = errors.InvalidArgumentError("bad public-key algorithm")
  668. }
  669. return
  670. }