Home > Backend Development > Golang > How do you generate a SHA hash for a given string in Golang?

How do you generate a SHA hash for a given string in Golang?

DDD
Release: 2024-11-19 21:07:02
Original
932 people have browsed it

How do you generate a SHA hash for a given string in Golang?

Generating a SHA Hash for a Given String in Golang

One of the most typical cryptographic operations performed with strings is computing their SHA hash. The SHA (Secure Hash Algorithm) algorithm generates a unique fingerprint by taking a string as input. In Golang, creating a SHA hash is a straightforward process.

Example Usage

For instance, let's compute the SHA hash of the string "beautiful." The following code snippet provides a practical example:

import (
    "crypto/sha1"
    "encoding/base64"
)

func main() {
    myPassword := "beautiful"

    hasher := sha1.New()
    hasher.Write([]byte(myPassword))
    sha := base64.URLEncoding.EncodeToString(hasher.Sum(nil))

    println(sha)
}
Copy after login

This code demonstrates:

  • Encoding the string "beautiful" into a byte array using []byte(myPassword)
  • Creating a new SHA1 hasher using sha1.New()
  • Using hasher.Write() to feed the string to the hasher
  • Obtaining the raw bytes of the hash using hasher.Sum(nil)
  • Optionally, encoding the hash bytes in base64 for human readability using base64.URLEncoding.EncodeToString()

The resulting sha variable contains the base64-encoded SHA hash of the original string, which can be conveniently displayed or compared.

The above is the detailed content of How do you generate a SHA hash for a given string in Golang?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template