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:
- The variable passwordUser holds the plain text password "hg".
- The function hashingPassword is called with passwordUser to generate
- its hash. If successful, it prints the hashed password. If there is an error,
it logs a fatal error and exits the program.
Comparing Passwords:
- The function comparePasswordHash is called with the original password
(passwordUser) and the hashed password (hashPass). It checks if the
password matches the hash. The result (true or false) is printed.
If there's an error during comparison, it logs a fatal error and exits the program.
Example Output
- When the code is executed, it first prints the hashed password.
- Then, it checks if the original password matches the hashed password and prints true if they match.
Key Points
- bcrypt: A widely used hashing function for passwords that includes a
salt and is computationally expensive to mitigate brute-force attacks.- Error Handling: The code logs fatal errors if anything goes wrong with
hashing or comparison, causing the program to terminate.
continue:go-redis.md
before:go-mongodb.md