signature.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  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. "crypto"
  7. "crypto/dsa"
  8. "crypto/rsa"
  9. "encoding/binary"
  10. "golang.org/x/crypto/openpgp/errors"
  11. "golang.org/x/crypto/openpgp/s2k"
  12. "hash"
  13. "io"
  14. "strconv"
  15. "time"
  16. )
  17. const (
  18. // See RFC 4880, section 5.2.3.21 for details.
  19. KeyFlagCertify = 1 << iota
  20. KeyFlagSign
  21. KeyFlagEncryptCommunications
  22. KeyFlagEncryptStorage
  23. )
  24. // Signature represents a signature. See RFC 4880, section 5.2.
  25. type Signature struct {
  26. SigType SignatureType
  27. PubKeyAlgo PublicKeyAlgorithm
  28. Hash crypto.Hash
  29. // HashSuffix is extra data that is hashed in after the signed data.
  30. HashSuffix []byte
  31. // HashTag contains the first two bytes of the hash for fast rejection
  32. // of bad signed data.
  33. HashTag [2]byte
  34. CreationTime time.Time
  35. RSASignature parsedMPI
  36. DSASigR, DSASigS parsedMPI
  37. ECDSASigR, ECDSASigS parsedMPI
  38. // rawSubpackets contains the unparsed subpackets, in order.
  39. rawSubpackets []outputSubpacket
  40. // The following are optional so are nil when not included in the
  41. // signature.
  42. SigLifetimeSecs, KeyLifetimeSecs *uint32
  43. PreferredSymmetric, PreferredHash, PreferredCompression []uint8
  44. IssuerKeyId *uint64
  45. IsPrimaryId *bool
  46. // FlagsValid is set if any flags were given. See RFC 4880, section
  47. // 5.2.3.21 for details.
  48. FlagsValid bool
  49. FlagCertify, FlagSign, FlagEncryptCommunications, FlagEncryptStorage bool
  50. // RevocationReason is set if this signature has been revoked.
  51. // See RFC 4880, section 5.2.3.23 for details.
  52. RevocationReason *uint8
  53. RevocationReasonText string
  54. outSubpackets []outputSubpacket
  55. }
  56. func (sig *Signature) parse(r io.Reader) (err error) {
  57. // RFC 4880, section 5.2.3
  58. var buf [5]byte
  59. _, err = readFull(r, buf[:1])
  60. if err != nil {
  61. return
  62. }
  63. if buf[0] != 4 {
  64. err = errors.UnsupportedError("signature packet version " + strconv.Itoa(int(buf[0])))
  65. return
  66. }
  67. _, err = readFull(r, buf[:5])
  68. if err != nil {
  69. return
  70. }
  71. sig.SigType = SignatureType(buf[0])
  72. sig.PubKeyAlgo = PublicKeyAlgorithm(buf[1])
  73. switch sig.PubKeyAlgo {
  74. case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly, PubKeyAlgoDSA, PubKeyAlgoECDSA:
  75. default:
  76. err = errors.UnsupportedError("public key algorithm " + strconv.Itoa(int(sig.PubKeyAlgo)))
  77. return
  78. }
  79. var ok bool
  80. sig.Hash, ok = s2k.HashIdToHash(buf[2])
  81. if !ok {
  82. return errors.UnsupportedError("hash function " + strconv.Itoa(int(buf[2])))
  83. }
  84. hashedSubpacketsLength := int(buf[3])<<8 | int(buf[4])
  85. l := 6 + hashedSubpacketsLength
  86. sig.HashSuffix = make([]byte, l+6)
  87. sig.HashSuffix[0] = 4
  88. copy(sig.HashSuffix[1:], buf[:5])
  89. hashedSubpackets := sig.HashSuffix[6:l]
  90. _, err = readFull(r, hashedSubpackets)
  91. if err != nil {
  92. return
  93. }
  94. // See RFC 4880, section 5.2.4
  95. trailer := sig.HashSuffix[l:]
  96. trailer[0] = 4
  97. trailer[1] = 0xff
  98. trailer[2] = uint8(l >> 24)
  99. trailer[3] = uint8(l >> 16)
  100. trailer[4] = uint8(l >> 8)
  101. trailer[5] = uint8(l)
  102. err = parseSignatureSubpackets(sig, hashedSubpackets, true)
  103. if err != nil {
  104. return
  105. }
  106. _, err = readFull(r, buf[:2])
  107. if err != nil {
  108. return
  109. }
  110. unhashedSubpacketsLength := int(buf[0])<<8 | int(buf[1])
  111. unhashedSubpackets := make([]byte, unhashedSubpacketsLength)
  112. _, err = readFull(r, unhashedSubpackets)
  113. if err != nil {
  114. return
  115. }
  116. err = parseSignatureSubpackets(sig, unhashedSubpackets, false)
  117. if err != nil {
  118. return
  119. }
  120. _, err = readFull(r, sig.HashTag[:2])
  121. if err != nil {
  122. return
  123. }
  124. switch sig.PubKeyAlgo {
  125. case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly:
  126. sig.RSASignature.bytes, sig.RSASignature.bitLength, err = readMPI(r)
  127. case PubKeyAlgoDSA:
  128. sig.DSASigR.bytes, sig.DSASigR.bitLength, err = readMPI(r)
  129. if err == nil {
  130. sig.DSASigS.bytes, sig.DSASigS.bitLength, err = readMPI(r)
  131. }
  132. case PubKeyAlgoECDSA:
  133. sig.ECDSASigR.bytes, sig.ECDSASigR.bitLength, err = readMPI(r)
  134. if err == nil {
  135. sig.ECDSASigS.bytes, sig.ECDSASigS.bitLength, err = readMPI(r)
  136. }
  137. default:
  138. panic("unreachable")
  139. }
  140. return
  141. }
  142. // parseSignatureSubpackets parses subpackets of the main signature packet. See
  143. // RFC 4880, section 5.2.3.1.
  144. func parseSignatureSubpackets(sig *Signature, subpackets []byte, isHashed bool) (err error) {
  145. for len(subpackets) > 0 {
  146. subpackets, err = parseSignatureSubpacket(sig, subpackets, isHashed)
  147. if err != nil {
  148. return
  149. }
  150. }
  151. if sig.CreationTime.IsZero() {
  152. err = errors.StructuralError("no creation time in signature")
  153. }
  154. return
  155. }
  156. type signatureSubpacketType uint8
  157. const (
  158. creationTimeSubpacket signatureSubpacketType = 2
  159. signatureExpirationSubpacket signatureSubpacketType = 3
  160. keyExpirationSubpacket signatureSubpacketType = 9
  161. prefSymmetricAlgosSubpacket signatureSubpacketType = 11
  162. issuerSubpacket signatureSubpacketType = 16
  163. prefHashAlgosSubpacket signatureSubpacketType = 21
  164. prefCompressionSubpacket signatureSubpacketType = 22
  165. primaryUserIdSubpacket signatureSubpacketType = 25
  166. keyFlagsSubpacket signatureSubpacketType = 27
  167. reasonForRevocationSubpacket signatureSubpacketType = 29
  168. )
  169. // parseSignatureSubpacket parses a single subpacket. len(subpacket) is >= 1.
  170. func parseSignatureSubpacket(sig *Signature, subpacket []byte, isHashed bool) (rest []byte, err error) {
  171. // RFC 4880, section 5.2.3.1
  172. var (
  173. length uint32
  174. packetType signatureSubpacketType
  175. isCritical bool
  176. )
  177. switch {
  178. case subpacket[0] < 192:
  179. length = uint32(subpacket[0])
  180. subpacket = subpacket[1:]
  181. case subpacket[0] < 255:
  182. if len(subpacket) < 2 {
  183. goto Truncated
  184. }
  185. length = uint32(subpacket[0]-192)<<8 + uint32(subpacket[1]) + 192
  186. subpacket = subpacket[2:]
  187. default:
  188. if len(subpacket) < 5 {
  189. goto Truncated
  190. }
  191. length = uint32(subpacket[1])<<24 |
  192. uint32(subpacket[2])<<16 |
  193. uint32(subpacket[3])<<8 |
  194. uint32(subpacket[4])
  195. subpacket = subpacket[5:]
  196. }
  197. if length > uint32(len(subpacket)) {
  198. goto Truncated
  199. }
  200. rest = subpacket[length:]
  201. subpacket = subpacket[:length]
  202. if len(subpacket) == 0 {
  203. err = errors.StructuralError("zero length signature subpacket")
  204. return
  205. }
  206. packetType = signatureSubpacketType(subpacket[0] & 0x7f)
  207. isCritical = subpacket[0]&0x80 == 0x80
  208. subpacket = subpacket[1:]
  209. sig.rawSubpackets = append(sig.rawSubpackets, outputSubpacket{isHashed, packetType, isCritical, subpacket})
  210. switch packetType {
  211. case creationTimeSubpacket:
  212. if !isHashed {
  213. err = errors.StructuralError("signature creation time in non-hashed area")
  214. return
  215. }
  216. if len(subpacket) != 4 {
  217. err = errors.StructuralError("signature creation time not four bytes")
  218. return
  219. }
  220. t := binary.BigEndian.Uint32(subpacket)
  221. sig.CreationTime = time.Unix(int64(t), 0)
  222. case signatureExpirationSubpacket:
  223. // Signature expiration time, section 5.2.3.10
  224. if !isHashed {
  225. return
  226. }
  227. if len(subpacket) != 4 {
  228. err = errors.StructuralError("expiration subpacket with bad length")
  229. return
  230. }
  231. sig.SigLifetimeSecs = new(uint32)
  232. *sig.SigLifetimeSecs = binary.BigEndian.Uint32(subpacket)
  233. case keyExpirationSubpacket:
  234. // Key expiration time, section 5.2.3.6
  235. if !isHashed {
  236. return
  237. }
  238. if len(subpacket) != 4 {
  239. err = errors.StructuralError("key expiration subpacket with bad length")
  240. return
  241. }
  242. sig.KeyLifetimeSecs = new(uint32)
  243. *sig.KeyLifetimeSecs = binary.BigEndian.Uint32(subpacket)
  244. case prefSymmetricAlgosSubpacket:
  245. // Preferred symmetric algorithms, section 5.2.3.7
  246. if !isHashed {
  247. return
  248. }
  249. sig.PreferredSymmetric = make([]byte, len(subpacket))
  250. copy(sig.PreferredSymmetric, subpacket)
  251. case issuerSubpacket:
  252. // Issuer, section 5.2.3.5
  253. if len(subpacket) != 8 {
  254. err = errors.StructuralError("issuer subpacket with bad length")
  255. return
  256. }
  257. sig.IssuerKeyId = new(uint64)
  258. *sig.IssuerKeyId = binary.BigEndian.Uint64(subpacket)
  259. case prefHashAlgosSubpacket:
  260. // Preferred hash algorithms, section 5.2.3.8
  261. if !isHashed {
  262. return
  263. }
  264. sig.PreferredHash = make([]byte, len(subpacket))
  265. copy(sig.PreferredHash, subpacket)
  266. case prefCompressionSubpacket:
  267. // Preferred compression algorithms, section 5.2.3.9
  268. if !isHashed {
  269. return
  270. }
  271. sig.PreferredCompression = make([]byte, len(subpacket))
  272. copy(sig.PreferredCompression, subpacket)
  273. case primaryUserIdSubpacket:
  274. // Primary User ID, section 5.2.3.19
  275. if !isHashed {
  276. return
  277. }
  278. if len(subpacket) != 1 {
  279. err = errors.StructuralError("primary user id subpacket with bad length")
  280. return
  281. }
  282. sig.IsPrimaryId = new(bool)
  283. if subpacket[0] > 0 {
  284. *sig.IsPrimaryId = true
  285. }
  286. case keyFlagsSubpacket:
  287. // Key flags, section 5.2.3.21
  288. if !isHashed {
  289. return
  290. }
  291. if len(subpacket) == 0 {
  292. err = errors.StructuralError("empty key flags subpacket")
  293. return
  294. }
  295. sig.FlagsValid = true
  296. if subpacket[0]&KeyFlagCertify != 0 {
  297. sig.FlagCertify = true
  298. }
  299. if subpacket[0]&KeyFlagSign != 0 {
  300. sig.FlagSign = true
  301. }
  302. if subpacket[0]&KeyFlagEncryptCommunications != 0 {
  303. sig.FlagEncryptCommunications = true
  304. }
  305. if subpacket[0]&KeyFlagEncryptStorage != 0 {
  306. sig.FlagEncryptStorage = true
  307. }
  308. case reasonForRevocationSubpacket:
  309. // Reason For Revocation, section 5.2.3.23
  310. if !isHashed {
  311. return
  312. }
  313. if len(subpacket) == 0 {
  314. err = errors.StructuralError("empty revocation reason subpacket")
  315. return
  316. }
  317. sig.RevocationReason = new(uint8)
  318. *sig.RevocationReason = subpacket[0]
  319. sig.RevocationReasonText = string(subpacket[1:])
  320. default:
  321. if isCritical {
  322. err = errors.UnsupportedError("unknown critical signature subpacket type " + strconv.Itoa(int(packetType)))
  323. return
  324. }
  325. }
  326. return
  327. Truncated:
  328. err = errors.StructuralError("signature subpacket truncated")
  329. return
  330. }
  331. // subpacketLengthLength returns the length, in bytes, of an encoded length value.
  332. func subpacketLengthLength(length int) int {
  333. if length < 192 {
  334. return 1
  335. }
  336. if length < 16320 {
  337. return 2
  338. }
  339. return 5
  340. }
  341. // serializeSubpacketLength marshals the given length into to.
  342. func serializeSubpacketLength(to []byte, length int) int {
  343. // RFC 4880, Section 4.2.2.
  344. if length < 192 {
  345. to[0] = byte(length)
  346. return 1
  347. }
  348. if length < 16320 {
  349. length -= 192
  350. to[0] = byte((length >> 8) + 192)
  351. to[1] = byte(length)
  352. return 2
  353. }
  354. to[0] = 255
  355. to[1] = byte(length >> 24)
  356. to[2] = byte(length >> 16)
  357. to[3] = byte(length >> 8)
  358. to[4] = byte(length)
  359. return 5
  360. }
  361. // subpacketsLength returns the serialized length, in bytes, of the given
  362. // subpackets.
  363. func subpacketsLength(subpackets []outputSubpacket, hashed bool) (length int) {
  364. for _, subpacket := range subpackets {
  365. if subpacket.hashed == hashed {
  366. length += subpacketLengthLength(len(subpacket.contents) + 1)
  367. length += 1 // type byte
  368. length += len(subpacket.contents)
  369. }
  370. }
  371. return
  372. }
  373. // serializeSubpackets marshals the given subpackets into to.
  374. func serializeSubpackets(to []byte, subpackets []outputSubpacket, hashed bool) {
  375. for _, subpacket := range subpackets {
  376. if subpacket.hashed == hashed {
  377. n := serializeSubpacketLength(to, len(subpacket.contents)+1)
  378. to[n] = byte(subpacket.subpacketType)
  379. to = to[1+n:]
  380. n = copy(to, subpacket.contents)
  381. to = to[n:]
  382. }
  383. }
  384. return
  385. }
  386. // KeyExpired returns whether sig is a self-signature of a key that has
  387. // expired.
  388. func (sig *Signature) KeyExpired(currentTime time.Time) bool {
  389. if sig.KeyLifetimeSecs == nil {
  390. return false
  391. }
  392. expiry := sig.CreationTime.Add(time.Duration(*sig.KeyLifetimeSecs) * time.Second)
  393. return currentTime.After(expiry)
  394. }
  395. // buildHashSuffix constructs the HashSuffix member of sig in preparation for signing.
  396. func (sig *Signature) buildHashSuffix() (err error) {
  397. hashedSubpacketsLen := subpacketsLength(sig.outSubpackets, true)
  398. var ok bool
  399. l := 6 + hashedSubpacketsLen
  400. sig.HashSuffix = make([]byte, l+6)
  401. sig.HashSuffix[0] = 4
  402. sig.HashSuffix[1] = uint8(sig.SigType)
  403. sig.HashSuffix[2] = uint8(sig.PubKeyAlgo)
  404. sig.HashSuffix[3], ok = s2k.HashToHashId(sig.Hash)
  405. if !ok {
  406. sig.HashSuffix = nil
  407. return errors.InvalidArgumentError("hash cannot be represented in OpenPGP: " + strconv.Itoa(int(sig.Hash)))
  408. }
  409. sig.HashSuffix[4] = byte(hashedSubpacketsLen >> 8)
  410. sig.HashSuffix[5] = byte(hashedSubpacketsLen)
  411. serializeSubpackets(sig.HashSuffix[6:l], sig.outSubpackets, true)
  412. trailer := sig.HashSuffix[l:]
  413. trailer[0] = 4
  414. trailer[1] = 0xff
  415. trailer[2] = byte(l >> 24)
  416. trailer[3] = byte(l >> 16)
  417. trailer[4] = byte(l >> 8)
  418. trailer[5] = byte(l)
  419. return
  420. }
  421. func (sig *Signature) signPrepareHash(h hash.Hash) (digest []byte, err error) {
  422. err = sig.buildHashSuffix()
  423. if err != nil {
  424. return
  425. }
  426. h.Write(sig.HashSuffix)
  427. digest = h.Sum(nil)
  428. copy(sig.HashTag[:], digest)
  429. return
  430. }
  431. // Sign signs a message with a private key. The hash, h, must contain
  432. // the hash of the message to be signed and will be mutated by this function.
  433. // On success, the signature is stored in sig. Call Serialize to write it out.
  434. // If config is nil, sensible defaults will be used.
  435. func (sig *Signature) Sign(h hash.Hash, priv *PrivateKey, config *Config) (err error) {
  436. sig.outSubpackets = sig.buildSubpackets()
  437. digest, err := sig.signPrepareHash(h)
  438. if err != nil {
  439. return
  440. }
  441. switch priv.PubKeyAlgo {
  442. case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly:
  443. sig.RSASignature.bytes, err = rsa.SignPKCS1v15(config.Random(), priv.PrivateKey.(*rsa.PrivateKey), sig.Hash, digest)
  444. sig.RSASignature.bitLength = uint16(8 * len(sig.RSASignature.bytes))
  445. case PubKeyAlgoDSA:
  446. dsaPriv := priv.PrivateKey.(*dsa.PrivateKey)
  447. // Need to truncate hashBytes to match FIPS 186-3 section 4.6.
  448. subgroupSize := (dsaPriv.Q.BitLen() + 7) / 8
  449. if len(digest) > subgroupSize {
  450. digest = digest[:subgroupSize]
  451. }
  452. r, s, err := dsa.Sign(config.Random(), dsaPriv, digest)
  453. if err == nil {
  454. sig.DSASigR.bytes = r.Bytes()
  455. sig.DSASigR.bitLength = uint16(8 * len(sig.DSASigR.bytes))
  456. sig.DSASigS.bytes = s.Bytes()
  457. sig.DSASigS.bitLength = uint16(8 * len(sig.DSASigS.bytes))
  458. }
  459. default:
  460. err = errors.UnsupportedError("public key algorithm: " + strconv.Itoa(int(sig.PubKeyAlgo)))
  461. }
  462. return
  463. }
  464. // SignUserId computes a signature from priv, asserting that pub is a valid
  465. // key for the identity id. On success, the signature is stored in sig. Call
  466. // Serialize to write it out.
  467. // If config is nil, sensible defaults will be used.
  468. func (sig *Signature) SignUserId(id string, pub *PublicKey, priv *PrivateKey, config *Config) error {
  469. h, err := userIdSignatureHash(id, pub, sig.Hash)
  470. if err != nil {
  471. return nil
  472. }
  473. return sig.Sign(h, priv, config)
  474. }
  475. // SignKey computes a signature from priv, asserting that pub is a subkey. On
  476. // success, the signature is stored in sig. Call Serialize to write it out.
  477. // If config is nil, sensible defaults will be used.
  478. func (sig *Signature) SignKey(pub *PublicKey, priv *PrivateKey, config *Config) error {
  479. h, err := keySignatureHash(&priv.PublicKey, pub, sig.Hash)
  480. if err != nil {
  481. return err
  482. }
  483. return sig.Sign(h, priv, config)
  484. }
  485. // Serialize marshals sig to w. Sign, SignUserId or SignKey must have been
  486. // called first.
  487. func (sig *Signature) Serialize(w io.Writer) (err error) {
  488. if len(sig.outSubpackets) == 0 {
  489. sig.outSubpackets = sig.rawSubpackets
  490. }
  491. if sig.RSASignature.bytes == nil && sig.DSASigR.bytes == nil && sig.ECDSASigR.bytes == nil {
  492. return errors.InvalidArgumentError("Signature: need to call Sign, SignUserId or SignKey before Serialize")
  493. }
  494. sigLength := 0
  495. switch sig.PubKeyAlgo {
  496. case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly:
  497. sigLength = 2 + len(sig.RSASignature.bytes)
  498. case PubKeyAlgoDSA:
  499. sigLength = 2 + len(sig.DSASigR.bytes)
  500. sigLength += 2 + len(sig.DSASigS.bytes)
  501. case PubKeyAlgoECDSA:
  502. sigLength = 2 + len(sig.ECDSASigR.bytes)
  503. sigLength += 2 + len(sig.ECDSASigS.bytes)
  504. default:
  505. panic("impossible")
  506. }
  507. unhashedSubpacketsLen := subpacketsLength(sig.outSubpackets, false)
  508. length := len(sig.HashSuffix) - 6 /* trailer not included */ +
  509. 2 /* length of unhashed subpackets */ + unhashedSubpacketsLen +
  510. 2 /* hash tag */ + sigLength
  511. err = serializeHeader(w, packetTypeSignature, length)
  512. if err != nil {
  513. return
  514. }
  515. _, err = w.Write(sig.HashSuffix[:len(sig.HashSuffix)-6])
  516. if err != nil {
  517. return
  518. }
  519. unhashedSubpackets := make([]byte, 2+unhashedSubpacketsLen)
  520. unhashedSubpackets[0] = byte(unhashedSubpacketsLen >> 8)
  521. unhashedSubpackets[1] = byte(unhashedSubpacketsLen)
  522. serializeSubpackets(unhashedSubpackets[2:], sig.outSubpackets, false)
  523. _, err = w.Write(unhashedSubpackets)
  524. if err != nil {
  525. return
  526. }
  527. _, err = w.Write(sig.HashTag[:])
  528. if err != nil {
  529. return
  530. }
  531. switch sig.PubKeyAlgo {
  532. case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly:
  533. err = writeMPIs(w, sig.RSASignature)
  534. case PubKeyAlgoDSA:
  535. err = writeMPIs(w, sig.DSASigR, sig.DSASigS)
  536. case PubKeyAlgoECDSA:
  537. err = writeMPIs(w, sig.ECDSASigR, sig.ECDSASigS)
  538. default:
  539. panic("impossible")
  540. }
  541. return
  542. }
  543. // outputSubpacket represents a subpacket to be marshaled.
  544. type outputSubpacket struct {
  545. hashed bool // true if this subpacket is in the hashed area.
  546. subpacketType signatureSubpacketType
  547. isCritical bool
  548. contents []byte
  549. }
  550. func (sig *Signature) buildSubpackets() (subpackets []outputSubpacket) {
  551. creationTime := make([]byte, 4)
  552. binary.BigEndian.PutUint32(creationTime, uint32(sig.CreationTime.Unix()))
  553. subpackets = append(subpackets, outputSubpacket{true, creationTimeSubpacket, false, creationTime})
  554. if sig.IssuerKeyId != nil {
  555. keyId := make([]byte, 8)
  556. binary.BigEndian.PutUint64(keyId, *sig.IssuerKeyId)
  557. subpackets = append(subpackets, outputSubpacket{true, issuerSubpacket, false, keyId})
  558. }
  559. if sig.SigLifetimeSecs != nil && *sig.SigLifetimeSecs != 0 {
  560. sigLifetime := make([]byte, 4)
  561. binary.BigEndian.PutUint32(sigLifetime, *sig.SigLifetimeSecs)
  562. subpackets = append(subpackets, outputSubpacket{true, signatureExpirationSubpacket, true, sigLifetime})
  563. }
  564. // Key flags may only appear in self-signatures or certification signatures.
  565. if sig.FlagsValid {
  566. var flags byte
  567. if sig.FlagCertify {
  568. flags |= KeyFlagCertify
  569. }
  570. if sig.FlagSign {
  571. flags |= KeyFlagSign
  572. }
  573. if sig.FlagEncryptCommunications {
  574. flags |= KeyFlagEncryptCommunications
  575. }
  576. if sig.FlagEncryptStorage {
  577. flags |= KeyFlagEncryptStorage
  578. }
  579. subpackets = append(subpackets, outputSubpacket{true, keyFlagsSubpacket, false, []byte{flags}})
  580. }
  581. // The following subpackets may only appear in self-signatures
  582. if sig.KeyLifetimeSecs != nil && *sig.KeyLifetimeSecs != 0 {
  583. keyLifetime := make([]byte, 4)
  584. binary.BigEndian.PutUint32(keyLifetime, *sig.KeyLifetimeSecs)
  585. subpackets = append(subpackets, outputSubpacket{true, keyExpirationSubpacket, true, keyLifetime})
  586. }
  587. if sig.IsPrimaryId != nil && *sig.IsPrimaryId {
  588. subpackets = append(subpackets, outputSubpacket{true, primaryUserIdSubpacket, false, []byte{1}})
  589. }
  590. if len(sig.PreferredSymmetric) > 0 {
  591. subpackets = append(subpackets, outputSubpacket{true, prefSymmetricAlgosSubpacket, false, sig.PreferredSymmetric})
  592. }
  593. if len(sig.PreferredHash) > 0 {
  594. subpackets = append(subpackets, outputSubpacket{true, prefHashAlgosSubpacket, false, sig.PreferredHash})
  595. }
  596. if len(sig.PreferredCompression) > 0 {
  597. subpackets = append(subpackets, outputSubpacket{true, prefCompressionSubpacket, false, sig.PreferredCompression})
  598. }
  599. return
  600. }