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.
5 // Package s2k implements the various OpenPGP string-to-key transforms as
6 // specified in RFC 4800 section 3.7.1.
7 package s2k // import "golang.org/x/crypto/openpgp/s2k"
15 "golang.org/x/crypto/openpgp/errors"
18 // Config collects configuration parameters for s2k key-stretching
19 // transformatioms. A nil *Config is valid and results in all default
20 // values. Currently, Config is used only by the Serialize function in
23 // Hash is the default hash function to be used. If
26 // S2KCount is only used for symmetric encryption. It
27 // determines the strength of the passphrase stretching when
28 // the said passphrase is hashed to produce a key. S2KCount
29 // should be between 1024 and 65011712, inclusive. If Config
30 // is nil or S2KCount is 0, the value 65536 used. Not all
31 // values in the above range can be represented. S2KCount will
32 // be rounded up to the next representable value if it cannot
33 // be encoded exactly. When set, it is strongly encrouraged to
34 // use a value that is at least 65536. See RFC 4880 Section
39 func (c *Config) hash() crypto.Hash {
40 if c == nil || uint(c.Hash) == 0 {
41 // SHA1 is the historical default in this package.
48 func (c *Config) encodedCount() uint8 {
49 if c == nil || c.S2KCount == 0 {
50 return 96 // The common case. Correspoding to 65536
55 // Behave like GPG. Should we make 65536 the lowest value used?
65 // encodeCount converts an iterative "count" in the range 1024 to
66 // 65011712, inclusive, to an encoded count. The return value is the
67 // octet that is actually stored in the GPG file. encodeCount panics
68 // if i is not in the above range (encodedCount above takes care to
69 // pass i in the correct range). See RFC 4880 Section 3.7.7.1.
70 func encodeCount(i int) uint8 {
71 if i < 1024 || i > 65011712 {
72 panic("count arg i outside the required range")
75 for encoded := 0; encoded < 256; encoded++ {
76 count := decodeCount(uint8(encoded))
85 // decodeCount returns the s2k mode 3 iterative "count" corresponding to
86 // the encoded octet c.
87 func decodeCount(c uint8) int {
88 return (16 + int(c&15)) << (uint32(c>>4) + 6)
91 // Simple writes to out the result of computing the Simple S2K function (RFC
92 // 4880, section 3.7.1.1) using the given hash and input passphrase.
93 func Simple(out []byte, h hash.Hash, in []byte) {
94 Salted(out, h, in, nil)
99 // Salted writes to out the result of computing the Salted S2K function (RFC
100 // 4880, section 3.7.1.2) using the given hash, input passphrase and salt.
101 func Salted(out []byte, h hash.Hash, in []byte, salt []byte) {
105 for i := 0; done < len(out); i++ {
107 for j := 0; j < i; j++ {
112 digest = h.Sum(digest[:0])
113 n := copy(out[done:], digest)
118 // Iterated writes to out the result of computing the Iterated and Salted S2K
119 // function (RFC 4880, section 3.7.1.3) using the given hash, input passphrase,
120 // salt and iteration count.
121 func Iterated(out []byte, h hash.Hash, in []byte, salt []byte, count int) {
122 combined := make([]byte, len(in)+len(salt))
124 copy(combined[len(salt):], in)
126 if count < len(combined) {
127 count = len(combined)
132 for i := 0; done < len(out); i++ {
134 for j := 0; j < i; j++ {
138 for written < count {
139 if written+len(combined) > count {
140 todo := count - written
141 h.Write(combined[:todo])
145 written += len(combined)
148 digest = h.Sum(digest[:0])
149 n := copy(out[done:], digest)
154 // Parse reads a binary specification for a string-to-key transformation from r
155 // and returns a function which performs that transform.
156 func Parse(r io.Reader) (f func(out, in []byte), err error) {
159 _, err = io.ReadFull(r, buf[:2])
164 hash, ok := HashIdToHash(buf[1])
166 return nil, errors.UnsupportedError("hash for S2K function: " + strconv.Itoa(int(buf[1])))
168 if !hash.Available() {
169 return nil, errors.UnsupportedError("hash not available: " + strconv.Itoa(int(hash)))
175 f := func(out, in []byte) {
180 _, err = io.ReadFull(r, buf[:8])
184 f := func(out, in []byte) {
185 Salted(out, h, in, buf[:8])
189 _, err = io.ReadFull(r, buf[:9])
193 count := decodeCount(buf[8])
194 f := func(out, in []byte) {
195 Iterated(out, h, in, buf[:8], count)
200 return nil, errors.UnsupportedError("S2K function")
203 // Serialize salts and stretches the given passphrase and writes the
204 // resulting key into key. It also serializes an S2K descriptor to
205 // w. The key stretching can be configured with c, which may be
206 // nil. In that case, sensible defaults will be used.
207 func Serialize(w io.Writer, key []byte, rand io.Reader, passphrase []byte, c *Config) error {
209 buf[0] = 3 /* iterated and salted */
210 buf[1], _ = HashToHashId(c.hash())
212 if _, err := io.ReadFull(rand, salt); err != nil {
215 encodedCount := c.encodedCount()
216 count := decodeCount(encodedCount)
217 buf[10] = encodedCount
218 if _, err := w.Write(buf[:]); err != nil {
222 Iterated(key, c.hash().New(), passphrase, salt, count)
226 // hashToHashIdMapping contains pairs relating OpenPGP's hash identifier with
227 // Go's crypto.Hash type. See RFC 4880, section 9.4.
228 var hashToHashIdMapping = []struct {
233 {1, crypto.MD5, "MD5"},
234 {2, crypto.SHA1, "SHA1"},
235 {3, crypto.RIPEMD160, "RIPEMD160"},
236 {8, crypto.SHA256, "SHA256"},
237 {9, crypto.SHA384, "SHA384"},
238 {10, crypto.SHA512, "SHA512"},
239 {11, crypto.SHA224, "SHA224"},
242 // HashIdToHash returns a crypto.Hash which corresponds to the given OpenPGP
244 func HashIdToHash(id byte) (h crypto.Hash, ok bool) {
245 for _, m := range hashToHashIdMapping {
253 // HashIdToString returns the name of the hash function corresponding to the
254 // given OpenPGP hash id.
255 func HashIdToString(id byte) (name string, ok bool) {
256 for _, m := range hashToHashIdMapping {
265 // HashIdToHash returns an OpenPGP hash id which corresponds the given Hash.
266 func HashToHashId(h crypto.Hash) (id byte, ok bool) {
267 for _, m := range hashToHashIdMapping {