s2k.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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 s2k implements the various OpenPGP string-to-key transforms as
  5. // specified in RFC 4800 section 3.7.1.
  6. package s2k // import "golang.org/x/crypto/openpgp/s2k"
  7. import (
  8. "crypto"
  9. "hash"
  10. "io"
  11. "strconv"
  12. "golang.org/x/crypto/openpgp/errors"
  13. )
  14. // Config collects configuration parameters for s2k key-stretching
  15. // transformatioms. A nil *Config is valid and results in all default
  16. // values. Currently, Config is used only by the Serialize function in
  17. // this package.
  18. type Config struct {
  19. // Hash is the default hash function to be used. If
  20. // nil, SHA1 is used.
  21. Hash crypto.Hash
  22. // S2KCount is only used for symmetric encryption. It
  23. // determines the strength of the passphrase stretching when
  24. // the said passphrase is hashed to produce a key. S2KCount
  25. // should be between 1024 and 65011712, inclusive. If Config
  26. // is nil or S2KCount is 0, the value 65536 used. Not all
  27. // values in the above range can be represented. S2KCount will
  28. // be rounded up to the next representable value if it cannot
  29. // be encoded exactly. When set, it is strongly encrouraged to
  30. // use a value that is at least 65536. See RFC 4880 Section
  31. // 3.7.1.3.
  32. S2KCount int
  33. }
  34. func (c *Config) hash() crypto.Hash {
  35. if c == nil || uint(c.Hash) == 0 {
  36. // SHA1 is the historical default in this package.
  37. return crypto.SHA1
  38. }
  39. return c.Hash
  40. }
  41. func (c *Config) encodedCount() uint8 {
  42. if c == nil || c.S2KCount == 0 {
  43. return 96 // The common case. Correspoding to 65536
  44. }
  45. i := c.S2KCount
  46. switch {
  47. // Behave like GPG. Should we make 65536 the lowest value used?
  48. case i < 1024:
  49. i = 1024
  50. case i > 65011712:
  51. i = 65011712
  52. }
  53. return encodeCount(i)
  54. }
  55. // encodeCount converts an iterative "count" in the range 1024 to
  56. // 65011712, inclusive, to an encoded count. The return value is the
  57. // octet that is actually stored in the GPG file. encodeCount panics
  58. // if i is not in the above range (encodedCount above takes care to
  59. // pass i in the correct range). See RFC 4880 Section 3.7.7.1.
  60. func encodeCount(i int) uint8 {
  61. if i < 1024 || i > 65011712 {
  62. panic("count arg i outside the required range")
  63. }
  64. for encoded := 0; encoded < 256; encoded++ {
  65. count := decodeCount(uint8(encoded))
  66. if count >= i {
  67. return uint8(encoded)
  68. }
  69. }
  70. return 255
  71. }
  72. // decodeCount returns the s2k mode 3 iterative "count" corresponding to
  73. // the encoded octet c.
  74. func decodeCount(c uint8) int {
  75. return (16 + int(c&15)) << (uint32(c>>4) + 6)
  76. }
  77. // Simple writes to out the result of computing the Simple S2K function (RFC
  78. // 4880, section 3.7.1.1) using the given hash and input passphrase.
  79. func Simple(out []byte, h hash.Hash, in []byte) {
  80. Salted(out, h, in, nil)
  81. }
  82. var zero [1]byte
  83. // Salted writes to out the result of computing the Salted S2K function (RFC
  84. // 4880, section 3.7.1.2) using the given hash, input passphrase and salt.
  85. func Salted(out []byte, h hash.Hash, in []byte, salt []byte) {
  86. done := 0
  87. var digest []byte
  88. for i := 0; done < len(out); i++ {
  89. h.Reset()
  90. for j := 0; j < i; j++ {
  91. h.Write(zero[:])
  92. }
  93. h.Write(salt)
  94. h.Write(in)
  95. digest = h.Sum(digest[:0])
  96. n := copy(out[done:], digest)
  97. done += n
  98. }
  99. }
  100. // Iterated writes to out the result of computing the Iterated and Salted S2K
  101. // function (RFC 4880, section 3.7.1.3) using the given hash, input passphrase,
  102. // salt and iteration count.
  103. func Iterated(out []byte, h hash.Hash, in []byte, salt []byte, count int) {
  104. combined := make([]byte, len(in)+len(salt))
  105. copy(combined, salt)
  106. copy(combined[len(salt):], in)
  107. if count < len(combined) {
  108. count = len(combined)
  109. }
  110. done := 0
  111. var digest []byte
  112. for i := 0; done < len(out); i++ {
  113. h.Reset()
  114. for j := 0; j < i; j++ {
  115. h.Write(zero[:])
  116. }
  117. written := 0
  118. for written < count {
  119. if written+len(combined) > count {
  120. todo := count - written
  121. h.Write(combined[:todo])
  122. written = count
  123. } else {
  124. h.Write(combined)
  125. written += len(combined)
  126. }
  127. }
  128. digest = h.Sum(digest[:0])
  129. n := copy(out[done:], digest)
  130. done += n
  131. }
  132. }
  133. // Parse reads a binary specification for a string-to-key transformation from r
  134. // and returns a function which performs that transform.
  135. func Parse(r io.Reader) (f func(out, in []byte), err error) {
  136. var buf [9]byte
  137. _, err = io.ReadFull(r, buf[:2])
  138. if err != nil {
  139. return
  140. }
  141. hash, ok := HashIdToHash(buf[1])
  142. if !ok {
  143. return nil, errors.UnsupportedError("hash for S2K function: " + strconv.Itoa(int(buf[1])))
  144. }
  145. if !hash.Available() {
  146. return nil, errors.UnsupportedError("hash not available: " + strconv.Itoa(int(hash)))
  147. }
  148. h := hash.New()
  149. switch buf[0] {
  150. case 0:
  151. f := func(out, in []byte) {
  152. Simple(out, h, in)
  153. }
  154. return f, nil
  155. case 1:
  156. _, err = io.ReadFull(r, buf[:8])
  157. if err != nil {
  158. return
  159. }
  160. f := func(out, in []byte) {
  161. Salted(out, h, in, buf[:8])
  162. }
  163. return f, nil
  164. case 3:
  165. _, err = io.ReadFull(r, buf[:9])
  166. if err != nil {
  167. return
  168. }
  169. count := decodeCount(buf[8])
  170. f := func(out, in []byte) {
  171. Iterated(out, h, in, buf[:8], count)
  172. }
  173. return f, nil
  174. }
  175. return nil, errors.UnsupportedError("S2K function")
  176. }
  177. // Serialize salts and stretches the given passphrase and writes the
  178. // resulting key into key. It also serializes an S2K descriptor to
  179. // w. The key stretching can be configured with c, which may be
  180. // nil. In that case, sensible defaults will be used.
  181. func Serialize(w io.Writer, key []byte, rand io.Reader, passphrase []byte, c *Config) error {
  182. var buf [11]byte
  183. buf[0] = 3 /* iterated and salted */
  184. buf[1], _ = HashToHashId(c.hash())
  185. salt := buf[2:10]
  186. if _, err := io.ReadFull(rand, salt); err != nil {
  187. return err
  188. }
  189. encodedCount := c.encodedCount()
  190. count := decodeCount(encodedCount)
  191. buf[10] = encodedCount
  192. if _, err := w.Write(buf[:]); err != nil {
  193. return err
  194. }
  195. Iterated(key, c.hash().New(), passphrase, salt, count)
  196. return nil
  197. }
  198. // hashToHashIdMapping contains pairs relating OpenPGP's hash identifier with
  199. // Go's crypto.Hash type. See RFC 4880, section 9.4.
  200. var hashToHashIdMapping = []struct {
  201. id byte
  202. hash crypto.Hash
  203. name string
  204. }{
  205. {1, crypto.MD5, "MD5"},
  206. {2, crypto.SHA1, "SHA1"},
  207. {3, crypto.RIPEMD160, "RIPEMD160"},
  208. {8, crypto.SHA256, "SHA256"},
  209. {9, crypto.SHA384, "SHA384"},
  210. {10, crypto.SHA512, "SHA512"},
  211. {11, crypto.SHA224, "SHA224"},
  212. }
  213. // HashIdToHash returns a crypto.Hash which corresponds to the given OpenPGP
  214. // hash id.
  215. func HashIdToHash(id byte) (h crypto.Hash, ok bool) {
  216. for _, m := range hashToHashIdMapping {
  217. if m.id == id {
  218. return m.hash, true
  219. }
  220. }
  221. return 0, false
  222. }
  223. // HashIdToString returns the name of the hash function corresponding to the
  224. // given OpenPGP hash id.
  225. func HashIdToString(id byte) (name string, ok bool) {
  226. for _, m := range hashToHashIdMapping {
  227. if m.id == id {
  228. return m.name, true
  229. }
  230. }
  231. return "", false
  232. }
  233. // HashIdToHash returns an OpenPGP hash id which corresponds the given Hash.
  234. func HashToHashId(h crypto.Hash) (id byte, ok bool) {
  235. for _, m := range hashToHashIdMapping {
  236. if m.hash == h {
  237. return m.id, true
  238. }
  239. }
  240. return 0, false
  241. }