To hash a string using SHA-1 in Go, you can use the crypto/sha1
package. Here's an example code that demonstrates how to hash a string using SHA-1:
package main
import (
"crypto/sha1"
"fmt"
)
func main() {
str := "Hello, World!"
// Create a new SHA-1 hasher
hasher := sha1.New()
// Write the string to the hasher
hasher.Write([]byte(str))
// Get the hashed result as a byte slice
hashedBytes := hasher.Sum(nil)
// Convert the hashed bytes to a hexadecimal string
hashedStr := fmt.Sprintf("%x", hashedBytes)
fmt.Println("Hashed String:", hashedStr)
}
This code example will output:
Hashed String: 0a4d55a8d778e5022fab701977c5d840bbc486d0
In this code, we first import the crypto/sha1
package. We then create a new SHA-1 hasher using sha1.New()
. The Write()
method is used to write the string to the hasher. After writing the string, we get the hashed result as a byte slice using Sum(nil)
. Finally, we convert the byte slice to a hexadecimal string using fmt.Sprintf("%x", hashedBytes)
.