public_key.go 19 KB

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