public_key_v3.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. // Copyright 2013 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/md5"
  8. "crypto/rsa"
  9. "encoding/binary"
  10. "fmt"
  11. "hash"
  12. "io"
  13. "math/big"
  14. "strconv"
  15. "time"
  16. "code.google.com/p/go.crypto/openpgp/errors"
  17. )
  18. // PublicKeyV3 represents older, version 3 public keys. These keys are less secure and
  19. // should not be used for signing or encrypting. They are supported here only for
  20. // parsing version 3 key material and validating signatures.
  21. // See RFC 4880, section 5.5.2.
  22. type PublicKeyV3 struct {
  23. CreationTime time.Time
  24. DaysToExpire uint16
  25. PubKeyAlgo PublicKeyAlgorithm
  26. PublicKey *rsa.PublicKey
  27. Fingerprint [16]byte
  28. KeyId uint64
  29. IsSubkey bool
  30. n, e parsedMPI
  31. }
  32. // newRSAPublicKeyV3 returns a PublicKey that wraps the given rsa.PublicKey.
  33. // Included here for testing purposes only. RFC 4880, section 5.5.2:
  34. // "an implementation MUST NOT generate a V3 key, but MAY accept it."
  35. func newRSAPublicKeyV3(creationTime time.Time, pub *rsa.PublicKey) *PublicKeyV3 {
  36. pk := &PublicKeyV3{
  37. CreationTime: creationTime,
  38. PublicKey: pub,
  39. n: fromBig(pub.N),
  40. e: fromBig(big.NewInt(int64(pub.E))),
  41. }
  42. pk.setFingerPrintAndKeyId()
  43. return pk
  44. }
  45. func (pk *PublicKeyV3) parse(r io.Reader) (err error) {
  46. // RFC 4880, section 5.5.2
  47. var buf [8]byte
  48. if _, err = readFull(r, buf[:]); err != nil {
  49. return
  50. }
  51. if buf[0] < 2 || buf[0] > 3 {
  52. return errors.UnsupportedError("public key version")
  53. }
  54. pk.CreationTime = time.Unix(int64(uint32(buf[1])<<24|uint32(buf[2])<<16|uint32(buf[3])<<8|uint32(buf[4])), 0)
  55. pk.DaysToExpire = binary.BigEndian.Uint16(buf[5:7])
  56. pk.PubKeyAlgo = PublicKeyAlgorithm(buf[7])
  57. switch pk.PubKeyAlgo {
  58. case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly:
  59. err = pk.parseRSA(r)
  60. default:
  61. err = errors.UnsupportedError("public key type: " + strconv.Itoa(int(pk.PubKeyAlgo)))
  62. }
  63. if err != nil {
  64. return
  65. }
  66. pk.setFingerPrintAndKeyId()
  67. return
  68. }
  69. func (pk *PublicKeyV3) setFingerPrintAndKeyId() {
  70. // RFC 4880, section 12.2
  71. fingerPrint := md5.New()
  72. fingerPrint.Write(pk.n.bytes)
  73. fingerPrint.Write(pk.e.bytes)
  74. fingerPrint.Sum(pk.Fingerprint[:0])
  75. pk.KeyId = binary.BigEndian.Uint64(pk.n.bytes[len(pk.n.bytes)-8:])
  76. }
  77. // parseRSA parses RSA public key material from the given Reader. See RFC 4880,
  78. // section 5.5.2.
  79. func (pk *PublicKeyV3) parseRSA(r io.Reader) (err error) {
  80. if pk.n.bytes, pk.n.bitLength, err = readMPI(r); err != nil {
  81. return
  82. }
  83. if pk.e.bytes, pk.e.bitLength, err = readMPI(r); err != nil {
  84. return
  85. }
  86. if len(pk.e.bytes) > 3 {
  87. err = errors.UnsupportedError("large public exponent")
  88. return
  89. }
  90. rsa := &rsa.PublicKey{N: new(big.Int).SetBytes(pk.n.bytes)}
  91. for i := 0; i < len(pk.e.bytes); i++ {
  92. rsa.E <<= 8
  93. rsa.E |= int(pk.e.bytes[i])
  94. }
  95. pk.PublicKey = rsa
  96. return
  97. }
  98. // SerializeSignaturePrefix writes the prefix for this public key to the given Writer.
  99. // The prefix is used when calculating a signature over this public key. See
  100. // RFC 4880, section 5.2.4.
  101. func (pk *PublicKeyV3) SerializeSignaturePrefix(w io.Writer) {
  102. var pLength uint16
  103. switch pk.PubKeyAlgo {
  104. case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly:
  105. pLength += 2 + uint16(len(pk.n.bytes))
  106. pLength += 2 + uint16(len(pk.e.bytes))
  107. default:
  108. panic("unknown public key algorithm")
  109. }
  110. pLength += 6
  111. w.Write([]byte{0x99, byte(pLength >> 8), byte(pLength)})
  112. return
  113. }
  114. func (pk *PublicKeyV3) Serialize(w io.Writer) (err error) {
  115. length := 8 // 8 byte header
  116. switch pk.PubKeyAlgo {
  117. case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly:
  118. length += 2 + len(pk.n.bytes)
  119. length += 2 + len(pk.e.bytes)
  120. default:
  121. panic("unknown public key algorithm")
  122. }
  123. packetType := packetTypePublicKey
  124. if pk.IsSubkey {
  125. packetType = packetTypePublicSubkey
  126. }
  127. if err = serializeHeader(w, packetType, length); err != nil {
  128. return
  129. }
  130. return pk.serializeWithoutHeaders(w)
  131. }
  132. // serializeWithoutHeaders marshals the PublicKey to w in the form of an
  133. // OpenPGP public key packet, not including the packet header.
  134. func (pk *PublicKeyV3) serializeWithoutHeaders(w io.Writer) (err error) {
  135. var buf [8]byte
  136. // Version 3
  137. buf[0] = 3
  138. // Creation time
  139. t := uint32(pk.CreationTime.Unix())
  140. buf[1] = byte(t >> 24)
  141. buf[2] = byte(t >> 16)
  142. buf[3] = byte(t >> 8)
  143. buf[4] = byte(t)
  144. // Days to expire
  145. buf[5] = byte(pk.DaysToExpire >> 8)
  146. buf[6] = byte(pk.DaysToExpire)
  147. // Public key algorithm
  148. buf[7] = byte(pk.PubKeyAlgo)
  149. if _, err = w.Write(buf[:]); err != nil {
  150. return
  151. }
  152. switch pk.PubKeyAlgo {
  153. case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly:
  154. return writeMPIs(w, pk.n, pk.e)
  155. }
  156. return errors.InvalidArgumentError("bad public-key algorithm")
  157. }
  158. // CanSign returns true iff this public key can generate signatures
  159. func (pk *PublicKeyV3) CanSign() bool {
  160. return pk.PubKeyAlgo != PubKeyAlgoRSAEncryptOnly
  161. }
  162. // VerifySignatureV3 returns nil iff sig is a valid signature, made by this
  163. // public key, of the data hashed into signed. signed is mutated by this call.
  164. func (pk *PublicKeyV3) VerifySignatureV3(signed hash.Hash, sig *SignatureV3) (err error) {
  165. if !pk.CanSign() {
  166. return errors.InvalidArgumentError("public key cannot generate signatures")
  167. }
  168. suffix := make([]byte, 5)
  169. suffix[0] = byte(sig.SigType)
  170. binary.BigEndian.PutUint32(suffix[1:], uint32(sig.CreationTime.Unix()))
  171. signed.Write(suffix)
  172. hashBytes := signed.Sum(nil)
  173. if hashBytes[0] != sig.HashTag[0] || hashBytes[1] != sig.HashTag[1] {
  174. return errors.SignatureError("hash tag doesn't match")
  175. }
  176. if pk.PubKeyAlgo != sig.PubKeyAlgo {
  177. return errors.InvalidArgumentError("public key and signature use different algorithms")
  178. }
  179. switch pk.PubKeyAlgo {
  180. case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly:
  181. if err = rsa.VerifyPKCS1v15(pk.PublicKey, sig.Hash, hashBytes, sig.RSASignature.bytes); err != nil {
  182. return errors.SignatureError("RSA verification failure")
  183. }
  184. return
  185. default:
  186. // V3 public keys only support RSA.
  187. panic("shouldn't happen")
  188. }
  189. panic("unreachable")
  190. }
  191. // VerifyUserIdSignatureV3 returns nil iff sig is a valid signature, made by this
  192. // public key, of id.
  193. func (pk *PublicKeyV3) VerifyUserIdSignatureV3(id string, sig *SignatureV3) (err error) {
  194. h, err := userIdSignatureV3Hash(id, pk, sig.Hash)
  195. if err != nil {
  196. return err
  197. }
  198. return pk.VerifySignatureV3(h, sig)
  199. }
  200. // VerifyKeySignatureV3 returns nil iff sig is a valid signature, made by this
  201. // public key, of signed.
  202. func (pk *PublicKeyV3) VerifyKeySignatureV3(signed *PublicKeyV3, sig *SignatureV3) (err error) {
  203. h, err := keySignatureHash(pk, signed, sig.Hash)
  204. if err != nil {
  205. return err
  206. }
  207. return pk.VerifySignatureV3(h, sig)
  208. }
  209. // userIdSignatureV3Hash returns a Hash of the message that needs to be signed
  210. // to assert that pk is a valid key for id.
  211. func userIdSignatureV3Hash(id string, pk signingKey, hfn crypto.Hash) (h hash.Hash, err error) {
  212. if h = hfn.New(); h == nil {
  213. return nil, errors.UnsupportedError("hash function")
  214. }
  215. // RFC 4880, section 5.2.4
  216. pk.SerializeSignaturePrefix(h)
  217. pk.serializeWithoutHeaders(h)
  218. h.Write([]byte(id))
  219. return
  220. }
  221. // KeyIdString returns the public key's fingerprint in capital hex
  222. // (e.g. "6C7EE1B8621CC013").
  223. func (pk *PublicKeyV3) KeyIdString() string {
  224. return fmt.Sprintf("%X", pk.KeyId)
  225. }
  226. // KeyIdShortString returns the short form of public key's fingerprint
  227. // in capital hex, as shown by gpg --list-keys (e.g. "621CC013").
  228. func (pk *PublicKeyV3) KeyIdShortString() string {
  229. return fmt.Sprintf("%X", pk.KeyId&0xFFFFFFFF)
  230. }
  231. // BitLength returns the bit length for the given public key.
  232. func (pk *PublicKeyV3) BitLength() (bitLength uint16, err error) {
  233. switch pk.PubKeyAlgo {
  234. case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly:
  235. bitLength = pk.n.bitLength
  236. default:
  237. err = errors.InvalidArgumentError("bad public-key algorithm")
  238. }
  239. return
  240. }