write.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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. signer = signed.signingKey().PrivateKey
  143. if signer == nil || signer.Encrypted {
  144. return nil, errors.InvalidArgumentError("signing key must be decrypted")
  145. }
  146. }
  147. // These are the possible ciphers that we'll use for the message.
  148. candidateCiphers := []uint8{
  149. uint8(packet.CipherAES128),
  150. uint8(packet.CipherAES256),
  151. uint8(packet.CipherCAST5),
  152. }
  153. // These are the possible hash functions that we'll use for the signature.
  154. candidateHashes := []uint8{
  155. hashToHashId(crypto.SHA256),
  156. hashToHashId(crypto.SHA512),
  157. hashToHashId(crypto.SHA1),
  158. hashToHashId(crypto.RIPEMD160),
  159. }
  160. // In the event that a recipient doesn't specify any supported ciphers
  161. // or hash functions, these are the ones that we assume that every
  162. // implementation supports.
  163. defaultCiphers := candidateCiphers[len(candidateCiphers)-1:]
  164. defaultHashes := candidateHashes[len(candidateHashes)-1:]
  165. encryptKeys := make([]Key, len(to))
  166. for i := range to {
  167. encryptKeys[i] = to[i].encryptionKey()
  168. if encryptKeys[i].PublicKey == nil {
  169. return nil, errors.InvalidArgumentError("cannot encrypt a message to key id " + strconv.FormatUint(to[i].PrimaryKey.KeyId, 16) + " because it has no encryption keys")
  170. }
  171. sig := to[i].primaryIdentity().SelfSignature
  172. preferredSymmetric := sig.PreferredSymmetric
  173. if len(preferredSymmetric) == 0 {
  174. preferredSymmetric = defaultCiphers
  175. }
  176. preferredHashes := sig.PreferredHash
  177. if len(preferredHashes) == 0 {
  178. preferredHashes = defaultHashes
  179. }
  180. candidateCiphers = intersectPreferences(candidateCiphers, preferredSymmetric)
  181. candidateHashes = intersectPreferences(candidateHashes, preferredHashes)
  182. }
  183. if len(candidateCiphers) == 0 || len(candidateHashes) == 0 {
  184. return nil, errors.InvalidArgumentError("cannot encrypt because recipient set shares no common algorithms")
  185. }
  186. cipher := packet.CipherFunction(candidateCiphers[0])
  187. // If the cipher specifed by config is a candidate, we'll use that.
  188. configuredCipher := config.Cipher()
  189. for _, c := range candidateCiphers {
  190. cipherFunc := packet.CipherFunction(c)
  191. if cipherFunc == configuredCipher {
  192. cipher = cipherFunc
  193. break
  194. }
  195. }
  196. hashFunc := candidateHashes[0]
  197. // If the hash specified by config is a candidate, we'll use that.
  198. configuredHash := config.Hash()
  199. for _, h := range candidateHashes {
  200. if h == uint8(configuredHash) {
  201. hashFunc = h
  202. break
  203. }
  204. }
  205. hash, _ := s2k.HashIdToHash(hashFunc)
  206. symKey := make([]byte, cipher.KeySize())
  207. if _, err := io.ReadFull(config.Random(), symKey); err != nil {
  208. return nil, err
  209. }
  210. for _, key := range encryptKeys {
  211. if err := packet.SerializeEncryptedKey(ciphertext, key.PublicKey, cipher, symKey, config); err != nil {
  212. return nil, err
  213. }
  214. }
  215. encryptedData, err := packet.SerializeSymmetricallyEncrypted(ciphertext, cipher, symKey, config)
  216. if err != nil {
  217. return
  218. }
  219. if signer != nil {
  220. ops := &packet.OnePassSignature{
  221. SigType: packet.SigTypeBinary,
  222. Hash: hash,
  223. PubKeyAlgo: signer.PubKeyAlgo,
  224. KeyId: signer.KeyId,
  225. IsLast: true,
  226. }
  227. if err := ops.Serialize(encryptedData); err != nil {
  228. return nil, err
  229. }
  230. }
  231. if hints == nil {
  232. hints = &FileHints{}
  233. }
  234. w := encryptedData
  235. if signer != nil {
  236. // If we need to write a signature packet after the literal
  237. // data then we need to stop literalData from closing
  238. // encryptedData.
  239. w = noOpCloser{encryptedData}
  240. }
  241. var epochSeconds uint32
  242. if !hints.ModTime.IsZero() {
  243. epochSeconds = uint32(hints.ModTime.Unix())
  244. }
  245. literalData, err := packet.SerializeLiteral(w, hints.IsBinary, hints.FileName, epochSeconds)
  246. if err != nil {
  247. return nil, err
  248. }
  249. if signer != nil {
  250. return signatureWriter{encryptedData, literalData, hash, hash.New(), signer, config}, nil
  251. }
  252. return literalData, nil
  253. }
  254. // signatureWriter hashes the contents of a message while passing it along to
  255. // literalData. When closed, it closes literalData, writes a signature packet
  256. // to encryptedData and then also closes encryptedData.
  257. type signatureWriter struct {
  258. encryptedData io.WriteCloser
  259. literalData io.WriteCloser
  260. hashType crypto.Hash
  261. h hash.Hash
  262. signer *packet.PrivateKey
  263. config *packet.Config
  264. }
  265. func (s signatureWriter) Write(data []byte) (int, error) {
  266. s.h.Write(data)
  267. return s.literalData.Write(data)
  268. }
  269. func (s signatureWriter) Close() error {
  270. sig := &packet.Signature{
  271. SigType: packet.SigTypeBinary,
  272. PubKeyAlgo: s.signer.PubKeyAlgo,
  273. Hash: s.hashType,
  274. CreationTime: s.config.Now(),
  275. IssuerKeyId: &s.signer.KeyId,
  276. }
  277. if err := sig.Sign(s.h, s.signer, s.config); err != nil {
  278. return err
  279. }
  280. if err := s.literalData.Close(); err != nil {
  281. return err
  282. }
  283. if err := sig.Serialize(s.encryptedData); err != nil {
  284. return err
  285. }
  286. return s.encryptedData.Close()
  287. }
  288. // noOpCloser is like an ioutil.NopCloser, but for an io.Writer.
  289. // TODO: we have two of these in OpenPGP packages alone. This probably needs
  290. // to be promoted somewhere more common.
  291. type noOpCloser struct {
  292. w io.Writer
  293. }
  294. func (c noOpCloser) Write(data []byte) (n int, err error) {
  295. return c.w.Write(data)
  296. }
  297. func (c noOpCloser) Close() error {
  298. return nil
  299. }