buildr/internal/vault/pbkdf2.go

32 lines
698 B
Go
Raw Normal View History

2023-03-22 19:41:10 +00:00
package vault
import (
"crypto/rand"
"crypto/sha256"
"golang.org/x/crypto/pbkdf2"
)
func Pbkdf2Deriver() KeyDeriver {
2023-06-22 16:06:56 +00:00
const (
saltLength = 8
iterations = 1000
keyLength = 32
)
2023-03-22 19:41:10 +00:00
return KeyDeriverFunc(func(passphrase string, existingSalt []byte) (key []byte, salt []byte) {
2023-06-22 16:06:56 +00:00
salt = make([]byte, saltLength)
2023-03-22 19:41:10 +00:00
if existingSalt == nil {
// http://www.ietf.org/rfc/rfc2898.txt
// Salt.
_, _ = rand.Read(salt)
2023-06-22 16:06:56 +00:00
} else if len(existingSalt) >= saltLength {
copy(salt, existingSalt[:saltLength])
2023-04-25 16:14:59 +00:00
} else {
copy(salt, existingSalt)
_, _ = rand.Read(salt[len(existingSalt):])
2023-03-22 19:41:10 +00:00
}
2023-06-22 16:06:56 +00:00
return pbkdf2.Key([]byte(passphrase), salt, iterations, keyLength, sha256.New), salt
2023-03-22 19:41:10 +00:00
})
}