Home > Article > Backend Development > How to Generate a SHA Hash of a String in Go?
How to Easily Generate SHA Hash of a String in Go
Generating a SHA hash of a string is a common task in programming, and Golang provides a straightforward way to do this using the crypto/sha package. Here's a practical example to help you understand the process:
Consider the scenario where you need to generate a SHA hash for the password string myPassword := "beautiful". To achieve this in Go, follow the given code snippet:
import ( "crypto/sha1" "encoding/base64" ) func generateSHA(password string) string { hasher := sha1.New() hasher.Write([]byte(password)) sha := base64.URLEncoding.EncodeToString(hasher.Sum(nil)) return sha } func main() { myPassword := "beautiful" result := generateSHA(myPassword) fmt.Println("SHA hash:", result) }
The process involves using sha1.New() to create a new SHA-1 hashing algorithm instance. Then, hasher.Write() is employed to pass the password bytes into the algorithm. Finally, hasher.Sum(nil) computes the message hash and converts it to base64 using base64.URLEncoding.EncodeToString().
Remember that SHA hashes should be stored as raw bytes in databases for security reasons. For user display or URL compatibility, Hexadecimal or Base64 encoding is commonly used.
The above is the detailed content of How to Generate a SHA Hash of a String in Go?. For more information, please follow other related articles on the PHP Chinese website!