How to translate this python method encrypt password to golang

Viewed 44

i have old code that encrypt user password written in pyton

def encrypt_password(plain_password: str, salt: str) -> str:
    password = plain_password.encode("utf-8")
    kdf = PBKDF2HMAC(
        algorithm=hashes.SHA256(),
        length=32,
        salt=salt.encode("utf-8"),
        iterations=100000,
        backend=default_backend()
    )
    result = base64.urlsafe_b64encode(kdf.derive(password))
    return result.decode("utf-8")

how i can translate to golang code ?

i search for the library that familiar like PBKDF2HMAC but in golang i didnt get it thank you

1 Answers

Try this:

package main

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

func EncryptPassword(password, salt string) string {
    key := pbkdf2.Key(
        []byte(password),
        []byte(salt),
        4096,
        32,
        sha256.New,
    )
    return fmt.Sprintf("%x", key)
}

func main() {
    encryptPassword := EncryptPassword("your_scary_password", "stackoverflow")
    fmt.Println(encryptPassword)
}

Output:

b8765db9531b72c3a5273b6ca3e0dcbaf70c4bdb080cfe9f34c60b50fb8315a7

Related