Home  >  Article  >  Backend Development  >  How to Generate a SHA Hash of a String in Go?

How to Generate a SHA Hash of a String in Go?

Barbara Streisand
Barbara StreisandOriginal
2024-11-23 08:29:15136browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn