signature.go 18 KB

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