github.com/cozy/cozy-stack@v0.0.0-20240603063001-31110fa4cae1/pkg/crypto/pbkdf2.go (about)

     1  package crypto
     2  
     3  import (
     4  	"crypto/sha256"
     5  	"encoding/base64"
     6  
     7  	"golang.org/x/crypto/pbkdf2"
     8  )
     9  
    10  // DefaultPBKDF2Iterations is the number of iterations used to hash the
    11  // passphrase on the client-side with the PBKDF2 algorithm.
    12  const DefaultPBKDF2Iterations = 650000
    13  
    14  // MinPBKDF2Iterations is the recommended minimum number of iterations for
    15  // hashing with PBKDF2.
    16  const MinPBKDF2Iterations = 50000
    17  
    18  // MaxPBKDF2Iterations is the recommended maximal number of iterations for
    19  // hashing with PBKDF2.
    20  const MaxPBKDF2Iterations = 5000000
    21  
    22  // hashedPassLen is the length of the hashed password (in bytes).
    23  const hashedPassLen = 32
    24  
    25  // HashPassWithPBKDF2 will hash a password with the PBKDF2 algorithm and same
    26  // parameters as it's done in client side. It returns the hashed password
    27  // encoded in base64, but also the master key.
    28  func HashPassWithPBKDF2(password, salt []byte, iterations int) ([]byte, []byte) {
    29  	key := pbkdf2.Key(password, salt, iterations, hashedPassLen, sha256.New)
    30  	hashed := pbkdf2.Key(key, password, 1, hashedPassLen, sha256.New)
    31  	encoded := make([]byte, base64.StdEncoding.EncodedLen(len(hashed)))
    32  	base64.StdEncoding.Encode(encoded, hashed)
    33  	return encoded, key
    34  }