write.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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 openpgp
  5. import (
  6. "code.google.com/p/go.crypto/openpgp/armor"
  7. "code.google.com/p/go.crypto/openpgp/errors"
  8. "code.google.com/p/go.crypto/openpgp/packet"
  9. "code.google.com/p/go.crypto/openpgp/s2k"
  10. "crypto"
  11. "hash"
  12. "io"
  13. "strconv"
  14. "time"
  15. )
  16. // DetachSign signs message with the private key from signer (which must
  17. // already have been decrypted) and writes the signature to w.
  18. // If config is nil, sensible defaults will be used.
  19. func DetachSign(w io.Writer, signer *Entity, message io.Reader, config *packet.Config) error {
  20. return detachSign(w, signer, message, packet.SigTypeBinary, config)
  21. }
  22. // ArmoredDetachSign signs message with the private key from signer (which
  23. // must already have been decrypted) and writes an armored signature to w.
  24. // If config is nil, sensible defaults will be used.
  25. func ArmoredDetachSign(w io.Writer, signer *Entity, message io.Reader, config *packet.Config) (err error) {
  26. return armoredDetachSign(w, signer, message, packet.SigTypeBinary, config)
  27. }
  28. // DetachSignText signs message (after canonicalising the line endings) with
  29. // the private key from signer (which must already have been decrypted) and
  30. // writes the signature to w.
  31. // If config is nil, sensible defaults will be used.
  32. func DetachSignText(w io.Writer, signer *Entity, message io.Reader, config *packet.Config) error {
  33. return detachSign(w, signer, message, packet.SigTypeText, config)
  34. }
  35. // ArmoredDetachSignText signs message (after canonicalising the line endings)
  36. // with the private key from signer (which must already have been decrypted)
  37. // and writes an armored signature to w.
  38. // If config is nil, sensible defaults will be used.
  39. func ArmoredDetachSignText(w io.Writer, signer *Entity, message io.Reader, config *packet.Config) error {
  40. return armoredDetachSign(w, signer, message, packet.SigTypeText, config)
  41. }
  42. func armoredDetachSign(w io.Writer, signer *Entity, message io.Reader, sigType packet.SignatureType, config *packet.Config) (err error) {
  43. out, err := armor.Encode(w, SignatureType, nil)
  44. if err != nil {
  45. return
  46. }
  47. err = detachSign(out, signer, message, sigType, config)
  48. if err != nil {
  49. return
  50. }
  51. return out.Close()
  52. }
  53. func detachSign(w io.Writer, signer *Entity, message io.Reader, sigType packet.SignatureType, config *packet.Config) (err error) {
  54. if signer.PrivateKey == nil {
  55. return errors.InvalidArgumentError("signing key doesn't have a private key")
  56. }
  57. if signer.PrivateKey.Encrypted {
  58. return errors.InvalidArgumentError("signing key is encrypted")
  59. }
  60. sig := new(packet.Signature)
  61. sig.SigType = sigType
  62. sig.PubKeyAlgo = signer.PrivateKey.PubKeyAlgo
  63. sig.Hash = config.Hash()
  64. sig.CreationTime = config.Now()
  65. sig.IssuerKeyId = &signer.PrivateKey.KeyId
  66. h, wrappedHash, err := hashForSignature(sig.Hash, sig.SigType)
  67. if err != nil {
  68. return
  69. }
  70. io.Copy(wrappedHash, message)
  71. err = sig.Sign(h, signer.PrivateKey, config)
  72. if err != nil {
  73. return
  74. }
  75. return sig.Serialize(w)
  76. }
  77. // FileHints contains metadata about encrypted files. This metadata is, itself,
  78. // encrypted.
  79. type FileHints struct {
  80. // IsBinary can be set to hint that the contents are binary data.
  81. IsBinary bool
  82. // FileName hints at the name of the file that should be written. It's
  83. // truncated to 255 bytes if longer. It may be empty to suggest that the
  84. // file should not be written to disk. It may be equal to "_CONSOLE" to
  85. // suggest the data should not be written to disk.
  86. FileName string
  87. // ModTime contains the modification time of the file, or the zero time if not applicable.
  88. ModTime time.Time
  89. }
  90. // SymmetricallyEncrypt acts like gpg -c: it encrypts a file with a passphrase.
  91. // The resulting WriteCloser must be closed after the contents of the file have
  92. // been written.
  93. // If config is nil, sensible defaults will be used.
  94. func SymmetricallyEncrypt(ciphertext io.Writer, passphrase []byte, hints *FileHints, config *packet.Config) (plaintext io.WriteCloser, err error) {
  95. if hints == nil {
  96. hints = &FileHints{}
  97. }
  98. key, err := packet.SerializeSymmetricKeyEncrypted(ciphertext, passphrase, config)
  99. if err != nil {
  100. return
  101. }
  102. w, err := packet.SerializeSymmetricallyEncrypted(ciphertext, config.Cipher(), key, config)
  103. if err != nil {
  104. return
  105. }
  106. var epochSeconds uint32
  107. if !hints.ModTime.IsZero() {
  108. epochSeconds = uint32(hints.ModTime.Unix())
  109. }
  110. return packet.SerializeLiteral(w, hints.IsBinary, hints.FileName, epochSeconds)
  111. }
  112. // intersectPreferences mutates and returns a prefix of a that contains only
  113. // the values in the intersection of a and b. The order of a is preserved.
  114. func intersectPreferences(a []uint8, b []uint8) (intersection []uint8) {
  115. var j int
  116. for _, v := range a {
  117. for _, v2 := range b {
  118. if v == v2 {
  119. a[j] = v
  120. j++
  121. break
  122. }
  123. }
  124. }
  125. return a[:j]
  126. }
  127. func hashToHashId(h crypto.Hash) uint8 {
  128. v, ok := s2k.HashToHashId(h)
  129. if !ok {
  130. panic("tried to convert unknown hash")
  131. }
  132. return v
  133. }
  134. // Encrypt encrypts a message to a number of recipients and, optionally, signs
  135. // it. hints contains optional information, that is also encrypted, that aids
  136. // the recipients in processing the message. The resulting WriteCloser must
  137. // be closed after the contents of the file have been written.
  138. // If config is nil, sensible defaults will be used.
  139. func Encrypt(ciphertext io.Writer, to []*Entity, signed *Entity, hints *FileHints, config *packet.Config) (plaintext io.WriteCloser, err error) {
  140. var signer *packet.PrivateKey
  141. if signed != nil {
  142. signKey, ok := signed.signingKey(config.Now())
  143. if !ok {
  144. return nil, errors.InvalidArgumentError("no valid signing keys")
  145. }
  146. signer = signKey.PrivateKey
  147. if signer.Encrypted {
  148. return nil, errors.InvalidArgumentError("signing key must be decrypted")
  149. }
  150. }
  151. // These are the possible ciphers that we'll use for the message.
  152. candidateCiphers := []uint8{
  153. uint8(packet.CipherAES128),
  154. uint8(packet.CipherAES256),
  155. uint8(packet.CipherCAST5),
  156. }
  157. // These are the possible hash functions that we'll use for the signature.
  158. candidateHashes := []uint8{
  159. hashToHashId(crypto.SHA256),
  160. hashToHashId(crypto.SHA512),
  161. hashToHashId(crypto.SHA1),
  162. hashToHashId(crypto.RIPEMD160),
  163. }
  164. // In the event that a recipient doesn't specify any supported ciphers
  165. // or hash functions, these are the ones that we assume that every
  166. // implementation supports.
  167. defaultCiphers := candidateCiphers[len(candidateCiphers)-1:]
  168. defaultHashes := candidateHashes[len(candidateHashes)-1:]
  169. encryptKeys := make([]Key, len(to))
  170. for i := range to {
  171. var ok bool
  172. encryptKeys[i], ok = to[i].encryptionKey(config.Now())
  173. if !ok {
  174. return nil, errors.InvalidArgumentError("cannot encrypt a message to key id " + strconv.FormatUint(to[i].PrimaryKey.KeyId, 16) + " because it has no encryption keys")
  175. }
  176. sig := to[i].primaryIdentity().SelfSignature
  177. preferredSymmetric := sig.PreferredSymmetric
  178. if len(preferredSymmetric) == 0 {
  179. preferredSymmetric = defaultCiphers
  180. }
  181. preferredHashes := sig.PreferredHash
  182. if len(preferredHashes) == 0 {
  183. preferredHashes = defaultHashes
  184. }
  185. candidateCiphers = intersectPreferences(candidateCiphers, preferredSymmetric)
  186. candidateHashes = intersectPreferences(candidateHashes, preferredHashes)
  187. }
  188. if len(candidateCiphers) == 0 || len(candidateHashes) == 0 {
  189. return nil, errors.InvalidArgumentError("cannot encrypt because recipient set shares no common algorithms")
  190. }
  191. cipher := packet.CipherFunction(candidateCiphers[0])
  192. // If the cipher specifed by config is a candidate, we'll use that.
  193. configuredCipher := config.Cipher()
  194. for _, c := range candidateCiphers {
  195. cipherFunc := packet.CipherFunction(c)
  196. if cipherFunc == configuredCipher {
  197. cipher = cipherFunc
  198. break
  199. }
  200. }
  201. var hash crypto.Hash
  202. for _, hashId := range candidateHashes {
  203. if h, ok := s2k.HashIdToHash(hashId); ok && h.Available() {
  204. hash = h
  205. break
  206. }
  207. }
  208. // If the hash specified by config is a candidate, we'll use that.
  209. if configuredHash := config.Hash(); configuredHash.Available() {
  210. for _, hashId := range candidateHashes {
  211. if h, ok := s2k.HashIdToHash(hashId); ok && h == configuredHash {
  212. hash = h
  213. break
  214. }
  215. }
  216. }
  217. if hash == 0 {
  218. hashId := candidateHashes[0]
  219. name, ok := s2k.HashIdToString(hashId)
  220. if !ok {
  221. name = "#" + strconv.Itoa(int(hashId))
  222. }
  223. return nil, errors.InvalidArgumentError("cannot encrypt because no candidate hash functions are compiled in. (Wanted " + name + " in this case.)")
  224. }
  225. symKey := make([]byte, cipher.KeySize())
  226. if _, err := io.ReadFull(config.Random(), symKey); err != nil {
  227. return nil, err
  228. }
  229. for _, key := range encryptKeys {
  230. if err := packet.SerializeEncryptedKey(ciphertext, key.PublicKey, cipher, symKey, config); err != nil {
  231. return nil, err
  232. }
  233. }
  234. encryptedData, err := packet.SerializeSymmetricallyEncrypted(ciphertext, cipher, symKey, config)
  235. if err != nil {
  236. return
  237. }
  238. if signer != nil {
  239. ops := &packet.OnePassSignature{
  240. SigType: packet.SigTypeBinary,
  241. Hash: hash,
  242. PubKeyAlgo: signer.PubKeyAlgo,
  243. KeyId: signer.KeyId,
  244. IsLast: true,
  245. }
  246. if err := ops.Serialize(encryptedData); err != nil {
  247. return nil, err
  248. }
  249. }
  250. if hints == nil {
  251. hints = &FileHints{}
  252. }
  253. w := encryptedData
  254. if signer != nil {
  255. // If we need to write a signature packet after the literal
  256. // data then we need to stop literalData from closing
  257. // encryptedData.
  258. w = noOpCloser{encryptedData}
  259. }
  260. var epochSeconds uint32
  261. if !hints.ModTime.IsZero() {
  262. epochSeconds = uint32(hints.ModTime.Unix())
  263. }
  264. literalData, err := packet.SerializeLiteral(w, hints.IsBinary, hints.FileName, epochSeconds)
  265. if err != nil {
  266. return nil, err
  267. }
  268. if signer != nil {
  269. return signatureWriter{encryptedData, literalData, hash, hash.New(), signer, config}, nil
  270. }
  271. return literalData, nil
  272. }
  273. // signatureWriter hashes the contents of a message while passing it along to
  274. // literalData. When closed, it closes literalData, writes a signature packet
  275. // to encryptedData and then also closes encryptedData.
  276. type signatureWriter struct {
  277. encryptedData io.WriteCloser
  278. literalData io.WriteCloser
  279. hashType crypto.Hash
  280. h hash.Hash
  281. signer *packet.PrivateKey
  282. config *packet.Config
  283. }
  284. func (s signatureWriter) Write(data []byte) (int, error) {
  285. s.h.Write(data)
  286. return s.literalData.Write(data)
  287. }
  288. func (s signatureWriter) Close() error {
  289. sig := &packet.Signature{
  290. SigType: packet.SigTypeBinary,
  291. PubKeyAlgo: s.signer.PubKeyAlgo,
  292. Hash: s.hashType,
  293. CreationTime: s.config.Now(),
  294. IssuerKeyId: &s.signer.KeyId,
  295. }
  296. if err := sig.Sign(s.h, s.signer, s.config); err != nil {
  297. return err
  298. }
  299. if err := s.literalData.Close(); err != nil {
  300. return err
  301. }
  302. if err := sig.Serialize(s.encryptedData); err != nil {
  303. return err
  304. }
  305. return s.encryptedData.Close()
  306. }
  307. // noOpCloser is like an ioutil.NopCloser, but for an io.Writer.
  308. // TODO: we have two of these in OpenPGP packages alone. This probably needs
  309. // to be promoted somewhere more common.
  310. type noOpCloser struct {
  311. w io.Writer
  312. }
  313. func (c noOpCloser) Write(data []byte) (n int, err error) {
  314. return c.w.Write(data)
  315. }
  316. func (c noOpCloser) Close() error {
  317. return nil
  318. }