public_key.go 20 KB

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