go-bycript

path: full-stack/go-chi-server/go-bycript.md

- **fileName**: go-bycript
- **Created on**: 2024-09-16 16:23:52

installation for crypto

go get require golang.org/x/crypto 

Example For Go Code For Crypto :

// main.go file
package main
import (
    "fmt"
    "log"
    "golang.org/x/crypto/bcrypt"
)
func hashingPassword(password string) (string, error) { // hash function
    // GenerateFromPassword returns a byte slice so we need to
    // and default cost is like salt in express and default = 10
    hesh, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
    if err != nil { return "", err }
    return string(hesh), nil
}
func comparePasswordHash(password, hash string) (bool,  error) { // comapre hash
    err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
    if err != nil { return false, err }
    return true, nil
}
func main() {
    passwordUser := "hg"
    hashPass, err := hashingPassword(passwordUser) // creating a hash 
    if err != nil {
        log.Fatalf("error happend hashing: %v\n", err)
    }
    fmt.Println(hashPass)
    // now compare the password
    // newPassword := "hg?"
    comparePasswordAndHash, err := comparePasswordHash(passwordUser, hashPass)
    if err != nil { log.Fatalf("error happend in compare: %v\n", err) }
    fmt.Printf("is the password correct: %v\n", comparePasswordAndHash)
    return
}

Implementation:

Hashing a Password:

Comparing Passwords:

Example Output

Key Points

continue:go-redis.md
before:go-mongodb.md