launchpad.net/~rogpeppe/juju-core/500-errgo-fix@v0.0.0-20140213181702-000000002356/thirdparty/pbkdf2/pbkdf2.go (about) 1 // Original package at code.google.com/p/go.crypto/pbkdf2 2 3 // Copyright 2012 The Go Authors. All rights reserved. 4 // Use of this source code is governed by a BSD-style 5 // license that can be found in the LICENSE file. 6 7 /* 8 Package pbkdf2 implements the key derivation function PBKDF2 as defined in RFC 9 2898 / PKCS #5 v2.0. 10 11 A key derivation function is useful when encrypting data based on a password 12 or any other not-fully-random data. It uses a pseudorandom function to derive 13 a secure encryption key based on the password. 14 15 While v2.0 of the standard defines only one pseudorandom function to use, 16 HMAC-SHA1, the drafted v2.1 specification allows use of all five FIPS Approved 17 Hash Functions SHA-1, SHA-224, SHA-256, SHA-384 and SHA-512 for HMAC. To 18 choose, you can pass the `New` functions from the different SHA packages to 19 pbkdf2.Key. 20 */ 21 package pbkdf2 22 23 import ( 24 "crypto/hmac" 25 "hash" 26 ) 27 28 // Key derives a key from the password, salt and iteration count, returning a 29 // []byte of length keylen that can be used as cryptographic key. The key is 30 // derived based on the method described as PBKDF2 with the HMAC variant using 31 // the supplied hash function. 32 // 33 // For example, to use a HMAC-SHA-1 based PBKDF2 key derivation function, you 34 // can get a derived key for e.g. AES-256 (which needs a 32-byte key) by 35 // doing: 36 // 37 // dk := pbkdf2.Key([]byte("some password"), salt, 4096, 32, sha1.New) 38 // 39 // Remember to get a good random salt. At least 8 bytes is recommended by the 40 // RFC. 41 // 42 // Using a higher iteration count will increase the cost of an exhaustive 43 // search but will also make derivation proportionally slower. 44 func Key(password, salt []byte, iter, keyLen int, h func() hash.Hash) []byte { 45 prf := hmac.New(h, password) 46 hashLen := prf.Size() 47 numBlocks := (keyLen + hashLen - 1) / hashLen 48 49 var buf [4]byte 50 dk := make([]byte, 0, numBlocks*hashLen) 51 U := make([]byte, hashLen) 52 for block := 1; block <= numBlocks; block++ { 53 // N.B.: || means concatenation, ^ means XOR 54 // for each block T_i = U_1 ^ U_2 ^ ... ^ U_iter 55 // U_1 = PRF(password, salt || uint(i)) 56 prf.Reset() 57 prf.Write(salt) 58 buf[0] = byte(block >> 24) 59 buf[1] = byte(block >> 16) 60 buf[2] = byte(block >> 8) 61 buf[3] = byte(block) 62 prf.Write(buf[:4]) 63 dk = prf.Sum(dk) 64 T := dk[len(dk)-hashLen:] 65 copy(U, T) 66 67 // U_n = PRF(password, U_(n-1)) 68 for n := 2; n <= iter; n++ { 69 prf.Reset() 70 prf.Write(U) 71 U = U[:0] 72 U = prf.Sum(U) 73 for x := range U { 74 T[x] ^= U[x] 75 } 76 } 77 } 78 return dk[:keyLen] 79 }