Home > Back-end >  How should I generate password with the format of $pbkdf2-sha512$25000... in golang pbkdf2 library?
How should I generate password with the format of $pbkdf2-sha512$25000... in golang pbkdf2 library?

Time:01-28

In Scala we have passwords like the below format:

$pbkdf2-sha512$25000$yCyQMMMBt1TuPa1F9FeKfT0yrNIF8tLB$TtQt5BZLs4qlA0YAkcGukZwu7pkxOLcxwuoQB3qNtxM

The above is "123" password I know it has sha512 algorithm with 25000 iteration via pbkdf2. But how should I generate like this in Go?

package main

import (
    "crypto/rand"
    "crypto/sha512"
    "fmt"
    "golang.org/x/crypto/pbkdf2"
    "log"
    "math/big"
)

func main() {
    password := []byte("123")
    salt, _ := generateRandomSalt(24)
    password = pbkdf2.Key(password, salt, 25000, len("123"), sha512.New)

    result := ""
    for _, k := range password {
        result  = fmt.Sprintf("X", k)
    }
    log.Println(result)

}

// Generate a salt value
func generateRandomSalt(length int) ([]byte, error) {
    results := make([]byte, length)
    for i := 0; i < length; i   {
        salt, err := rand.Int(rand.Reader, big.NewInt(255))
        if err != nil {
            return nil, err
        }
        results[i] = byte(salt.Int64())
    }
    return results, nil
}

CodePudding user response:

To generate a password in the format of $pbkdf2-sha512$25000... using the Golang crypto/pbkdf2 library, you can use the Key function to derive a key from a password and salt using PBKDF2 with the SHA512 hash function. Here's an example:

package main

import (
    "crypto/rand"
    "crypto/sha512"
    "fmt"
    "golang.org/x/crypto/pbkdf2"
)

func main() {
    password := []byte("mypassword")
    salt := make([]byte, 8)
    _, err := rand.Read(salt)
    if err != nil {
        fmt.Println(err)
        return
    }
    iterations := 25000
    key := pbkdf2.Key(password, salt, iterations, sha512.Size, sha512.New)
    fmt.Printf("$pbkdf2-sha512$%d$%x$%x\n", iterations, salt, key)
}

In this example, we first create a byte slice of the password using []byte("mypassword"). Then we create a byte slice of 8 bytes to use as the salt and fill it with random bytes using crypto/rand.Read(). The iterations variable is set to 25000 to match the format you mentioned. The pbkdf2.Key() function is used to derive the key using the password, salt, and iterations as inputs, with sha512.Size as the key length and sha512.New() as the hash function. Finally, we use fmt.Printf() to print the key in the desired format with the iterations, salt and key.

Keep in mind that this is just an example and you should use a secure random number generator to generate the salt and use a unique salt for each user in production.

  • Related