Source file src/crypto/pbkdf2/pbkdf2.go
1 // Copyright 2012 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 pbkdf2 implements the key derivation function PBKDF2 as defined in 6 // RFC 8018 (PKCS #5 v2.1). 7 // 8 // A key derivation function is useful when encrypting data based on a password 9 // or any other not-fully-random data. It uses a pseudorandom function to derive 10 // a secure encryption key based on the password. 11 package pbkdf2 12 13 import ( 14 "crypto/internal/fips140/pbkdf2" 15 "crypto/internal/fips140only" 16 "errors" 17 "hash" 18 ) 19 20 // Key derives a key from the password, salt and iteration count, returning a 21 // []byte of length keyLength that can be used as cryptographic key. The key is 22 // derived based on the method described as PBKDF2 with the HMAC variant using 23 // the supplied hash function. 24 // 25 // For example, to use a HMAC-SHA-1 based PBKDF2 key derivation function, you 26 // can get a derived key for e.g. AES-256 (which needs a 32-byte key) by 27 // doing: 28 // 29 // dk := pbkdf2.Key(sha1.New, []byte("some password"), salt, 4096, 32) 30 // 31 // Remember to get a good random salt. At least 8 bytes is recommended by the 32 // RFC. 33 // 34 // Using a higher iteration count will increase the cost of an exhaustive 35 // search but will also make derivation proportionally slower. 36 func Key[Hash hash.Hash](h func() Hash, password string, salt []byte, iter, keyLength int) ([]byte, error) { 37 if fips140only.Enabled { 38 if keyLength < 112/8 { 39 return nil, errors.New("crypto/pbkdf2: use of keys shorter than 112 bits is not allowed in FIPS 140-only mode") 40 } 41 if len(salt) < 128/8 { 42 return nil, errors.New("crypto/pbkdf2: use of salts shorter than 128 bits is not allowed in FIPS 140-only mode") 43 } 44 if !fips140only.ApprovedHash(h()) { 45 return nil, errors.New("crypto/pbkdf2: use of hash functions other than SHA-2 or SHA-3 is not allowed in FIPS 140-only mode") 46 } 47 } 48 return pbkdf2.Key(h, password, salt, iter, keyLength) 49 } 50