write.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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. hashFunc := candidateHashes[0]
  202. // If the hash specified by config is a candidate, we'll use that.
  203. configuredHash := config.Hash()
  204. for _, h := range candidateHashes {
  205. if h == uint8(configuredHash) {
  206. hashFunc = h
  207. break
  208. }
  209. }
  210. hash, _ := s2k.HashIdToHash(hashFunc)
  211. symKey := make([]byte, cipher.KeySize())
  212. if _, err := io.ReadFull(config.Random(), symKey); err != nil {
  213. return nil, err
  214. }
  215. for _, key := range encryptKeys {
  216. if err := packet.SerializeEncryptedKey(ciphertext, key.PublicKey, cipher, symKey, config); err != nil {
  217. return nil, err
  218. }
  219. }
  220. encryptedData, err := packet.SerializeSymmetricallyEncrypted(ciphertext, cipher, symKey, config)
  221. if err != nil {
  222. return
  223. }
  224. if signer != nil {
  225. ops := &packet.OnePassSignature{
  226. SigType: packet.SigTypeBinary,
  227. Hash: hash,
  228. PubKeyAlgo: signer.PubKeyAlgo,
  229. KeyId: signer.KeyId,
  230. IsLast: true,
  231. }
  232. if err := ops.Serialize(encryptedData); err != nil {
  233. return nil, err
  234. }
  235. }
  236. if hints == nil {
  237. hints = &FileHints{}
  238. }
  239. w := encryptedData
  240. if signer != nil {
  241. // If we need to write a signature packet after the literal
  242. // data then we need to stop literalData from closing
  243. // encryptedData.
  244. w = noOpCloser{encryptedData}
  245. }
  246. var epochSeconds uint32
  247. if !hints.ModTime.IsZero() {
  248. epochSeconds = uint32(hints.ModTime.Unix())
  249. }
  250. literalData, err := packet.SerializeLiteral(w, hints.IsBinary, hints.FileName, epochSeconds)
  251. if err != nil {
  252. return nil, err
  253. }
  254. if signer != nil {
  255. return signatureWriter{encryptedData, literalData, hash, hash.New(), signer, config}, nil
  256. }
  257. return literalData, nil
  258. }
  259. // signatureWriter hashes the contents of a message while passing it along to
  260. // literalData. When closed, it closes literalData, writes a signature packet
  261. // to encryptedData and then also closes encryptedData.
  262. type signatureWriter struct {
  263. encryptedData io.WriteCloser
  264. literalData io.WriteCloser
  265. hashType crypto.Hash
  266. h hash.Hash
  267. signer *packet.PrivateKey
  268. config *packet.Config
  269. }
  270. func (s signatureWriter) Write(data []byte) (int, error) {
  271. s.h.Write(data)
  272. return s.literalData.Write(data)
  273. }
  274. func (s signatureWriter) Close() error {
  275. sig := &packet.Signature{
  276. SigType: packet.SigTypeBinary,
  277. PubKeyAlgo: s.signer.PubKeyAlgo,
  278. Hash: s.hashType,
  279. CreationTime: s.config.Now(),
  280. IssuerKeyId: &s.signer.KeyId,
  281. }
  282. if err := sig.Sign(s.h, s.signer, s.config); err != nil {
  283. return err
  284. }
  285. if err := s.literalData.Close(); err != nil {
  286. return err
  287. }
  288. if err := sig.Serialize(s.encryptedData); err != nil {
  289. return err
  290. }
  291. return s.encryptedData.Close()
  292. }
  293. // noOpCloser is like an ioutil.NopCloser, but for an io.Writer.
  294. // TODO: we have two of these in OpenPGP packages alone. This probably needs
  295. // to be promoted somewhere more common.
  296. type noOpCloser struct {
  297. w io.Writer
  298. }
  299. func (c noOpCloser) Write(data []byte) (n int, err error) {
  300. return c.w.Write(data)
  301. }
  302. func (c noOpCloser) Close() error {
  303. return nil
  304. }