signature.go 19 KB

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