github.com/maenmax/kairep@v0.0.0-20210218001208-55bf3df36788/src/golang.org/x/crypto/openpgp/s2k/s2k.go (about) 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 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" 8 9 import ( 10 "crypto" 11 "hash" 12 "io" 13 "strconv" 14 15 "golang.org/x/crypto/openpgp/errors" 16 ) 17 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 21 // this package. 22 type Config struct { 23 // Hash is the default hash function to be used. If 24 // nil, SHA1 is used. 25 Hash crypto.Hash 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 35 // 3.7.1.3. 36 S2KCount int 37 } 38 39 func (c *Config) hash() crypto.Hash { 40 if c == nil || uint(c.Hash) == 0 { 41 // SHA1 is the historical default in this package. 42 return crypto.SHA1 43 } 44 45 return c.Hash 46 } 47 48 func (c *Config) encodedCount() uint8 { 49 if c == nil || c.S2KCount == 0 { 50 return 96 // The common case. Correspoding to 65536 51 } 52 53 i := c.S2KCount 54 switch { 55 // Behave like GPG. Should we make 65536 the lowest value used? 56 case i < 1024: 57 i = 1024 58 case i > 65011712: 59 i = 65011712 60 } 61 62 return encodeCount(i) 63 } 64 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") 73 } 74 75 for encoded := 0; encoded < 256; encoded++ { 76 count := decodeCount(uint8(encoded)) 77 if count >= i { 78 return uint8(encoded) 79 } 80 } 81 82 return 255 83 } 84 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) 89 } 90 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) 95 } 96 97 var zero [1]byte 98 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) { 102 done := 0 103 var digest []byte 104 105 for i := 0; done < len(out); i++ { 106 h.Reset() 107 for j := 0; j < i; j++ { 108 h.Write(zero[:]) 109 } 110 h.Write(salt) 111 h.Write(in) 112 digest = h.Sum(digest[:0]) 113 n := copy(out[done:], digest) 114 done += n 115 } 116 } 117 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)) 123 copy(combined, salt) 124 copy(combined[len(salt):], in) 125 126 if count < len(combined) { 127 count = len(combined) 128 } 129 130 done := 0 131 var digest []byte 132 for i := 0; done < len(out); i++ { 133 h.Reset() 134 for j := 0; j < i; j++ { 135 h.Write(zero[:]) 136 } 137 written := 0 138 for written < count { 139 if written+len(combined) > count { 140 todo := count - written 141 h.Write(combined[:todo]) 142 written = count 143 } else { 144 h.Write(combined) 145 written += len(combined) 146 } 147 } 148 digest = h.Sum(digest[:0]) 149 n := copy(out[done:], digest) 150 done += n 151 } 152 } 153 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) { 157 var buf [9]byte 158 159 _, err = io.ReadFull(r, buf[:2]) 160 if err != nil { 161 return 162 } 163 164 hash, ok := HashIdToHash(buf[1]) 165 if !ok { 166 return nil, errors.UnsupportedError("hash for S2K function: " + strconv.Itoa(int(buf[1]))) 167 } 168 if !hash.Available() { 169 return nil, errors.UnsupportedError("hash not available: " + strconv.Itoa(int(hash))) 170 } 171 h := hash.New() 172 173 switch buf[0] { 174 case 0: 175 f := func(out, in []byte) { 176 Simple(out, h, in) 177 } 178 return f, nil 179 case 1: 180 _, err = io.ReadFull(r, buf[:8]) 181 if err != nil { 182 return 183 } 184 f := func(out, in []byte) { 185 Salted(out, h, in, buf[:8]) 186 } 187 return f, nil 188 case 3: 189 _, err = io.ReadFull(r, buf[:9]) 190 if err != nil { 191 return 192 } 193 count := decodeCount(buf[8]) 194 f := func(out, in []byte) { 195 Iterated(out, h, in, buf[:8], count) 196 } 197 return f, nil 198 } 199 200 return nil, errors.UnsupportedError("S2K function") 201 } 202 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 { 208 var buf [11]byte 209 buf[0] = 3 /* iterated and salted */ 210 buf[1], _ = HashToHashId(c.hash()) 211 salt := buf[2:10] 212 if _, err := io.ReadFull(rand, salt); err != nil { 213 return err 214 } 215 encodedCount := c.encodedCount() 216 count := decodeCount(encodedCount) 217 buf[10] = encodedCount 218 if _, err := w.Write(buf[:]); err != nil { 219 return err 220 } 221 222 Iterated(key, c.hash().New(), passphrase, salt, count) 223 return nil 224 } 225 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 { 229 id byte 230 hash crypto.Hash 231 name string 232 }{ 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"}, 240 } 241 242 // HashIdToHash returns a crypto.Hash which corresponds to the given OpenPGP 243 // hash id. 244 func HashIdToHash(id byte) (h crypto.Hash, ok bool) { 245 for _, m := range hashToHashIdMapping { 246 if m.id == id { 247 return m.hash, true 248 } 249 } 250 return 0, false 251 } 252 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 { 257 if m.id == id { 258 return m.name, true 259 } 260 } 261 262 return "", false 263 } 264 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 { 268 if m.hash == h { 269 return m.id, true 270 } 271 } 272 return 0, false 273 }