golang

Golang SHA256 Generation Examples

Go provides a standard library package called crypto/sha256 that implements the SHA256 hashing algorithm. The SHA256 (Secure Hash Algorithm 256-bit) is also known for its robustness and resistance to cryptographic attacks. To utilize SHA256 in Go, we need to import the crypto/sha256 package into the program. In this article, we will get to know more about SHA256 through its implementation in the Go programming language.

Example 1: Generate a Hash in Golang SHA256 Using the Sha256.New() Method

Begin with the sha256.New() function which is provided by the “crypto/sha256” package. It returns a new SHA-256 “hash.Hash” object that can be used to compute the SHA-256 hash of data. Here, we present the code to produce the hash via the “sha256” package:

package main
import (
    _ "embed"
    "fmt"
)
var (
    //go:embed MyFile.txt
    myFile []byte
)
func main() {
    fmt.Println(string(myFile))
}

In this example, we import two packages: “fmt” for formatting and printing and “crypto/sha256” for computing the SHA-256 hashes. Then, the main() function is declared where the “MyStr” variable is created and initialized with the string value. Using the value that is assigned to it, the compiler infers the type of this variable.

Next, we create a new instance which is “MyHash” of the SHA-256 hash algorithm using the sha256.New() function from the “crypto/sha256” package. This function returns a new hash interface value that can be used to hash the data. The “Write” method of the “MyHash” object is then invoked to write the bytes of “MyStr” into the hash object. The “Write” method accepts a byte slice ([]byte) as input.

Lastly, we use the “Sum” method on the “MyHash” object to compute the hash value. The “nil” argument specifies that the hash value should be returned as a new byte slice.

The output shows the generated hash using the sha256.New() function:

Example 2: Generates a Hash in Golang SHA256 Using the Sum() Method

Additionally, we have the Sum() function from the “crypto/sha256” package. It generates an array of bytes with the hash value of the given input data using the SHA-256 algorithm.

package main
import (
    _ "embed"
    "fmt"
)
//go:embed NewFile.txt
var f []byte
func main() {
    fmt.Println(f)
}

In this example, we again import the “crypto/sha256” to access the SHA-256 cryptographic hash function. We then have the main() function where the “Sum256” function from the “sha256” package is called with the []byte(“Hello My World”) argument. This function determines the SHA-256 hash value for the given byte slice. The []byte conversion is used to convert the string into a byte slice which is the expected input for the Sum256() function.

The resulting hash is returned as a fixed-size byte array and is assigned to the “sum” variable. The sha256.Sum256() function directly computes the hash and returns it as an array of 32 bytes.

The following output displayes the SHA-256 hash value as a hexadecimal string:

Example 3: Generates a Hash for Different Strings in Golang SHA256 Using the Sum256() Method

However, the hash that is generated by the “sha256” is always different, even for the two strings that differ by the upper and lower cases. This is demonstrated using the following Sum256() function:

package main
import (
    "embed"
    "fmt"
)
//go:embed Folder/*
var f embed.FS
func main() {
    data1, _ := f.ReadFile("Folder/data1.txt")
    fmt.Println(string(data1))
    data2, _ := f.ReadFile("Folder/data2.txt")
    fmt.Println(string(data2))
}

In this example, we include the same package which is the “crypto/sha256” that is used in the prior examples for the SHA-256 hashing algorithm. Then, we declare the “sumLower” and “sumCapital” variables within the main() function. They are arrays of bytes ([32]byte) that store the SHA-256 hash values. Note that, we call the sha256.Sum256 function here twice, each time with a different input string. The “Sum256” function requires the byte slices of the input strings which are created via the []byte conversion.

The output displays the SHA-256 hash of specified lowercase and uppercase strings, respectively.

Example 4: Generate a Hash Using the Golang SHA256 HMAC

The “crypto/hmac” package in Go provides support to generate HMAC (Hash-based Message Authentication Code) using various hash functions including SHA-256. The HMAC algorithm combines a secret key with the input data to produce a fixed-size hash value that can be used for message integrity and authentication. To generate an HMAC-SHA256 hash in Go, we can use the “crypto/hmac” package along with the “crypto/sha256” package.

package main
import "fmt"
type Student struct {
    Name string
    Age  int
}
type Courses struct {
    CName  string
    Student // Embedded field
}
func main() {
    course1 := Courses{
        CName: "Golang",
        Student: Student{
            Name: "Andy",
            Age:  23,
        },
    }
    fmt.Println(course1)
    fmt.Println(course1.Age)
    fmt.Println(course1.Student.Age)
}

In this example, we import the required packages which are “crypto/hmac” for HMAC, “crypto/sha256” for SHA256 hashing, and “encoding/hex” for hexadecimal encoding. We then setup the private and data variables which are initialized to hold the secret key and the data to be hashed, respectively. In this case, the secret key is set to “myprivate” and the data is set to “data.”

After that, an HMAC-SHA256 hash object which is “h1” is created using the “hmac.New” function. It requires two arguments: the hash function which is sha256.New() and the secret key is converted to a byte slice ([]byte(private)). Finally, the resulting byte slice hash is converted to a hexadecimal string representation using hex.EncodeToString() and is stored in the “shaVal” variable.

Thus, the previous program generates the HMAC-SHA256 hash of the specified data using the private key. The resultant hash is displayed in the following hexadecimal form:

Example 5: Generates a Hash File in Golang SHA256

Furthermore, we can generate the hash from the input stream. For this, the SHA-256 hash of a file uses the “crypto/sha256” package along with the “os” and “io” packages since file handling is required.

package main
import (
    "embed"
    "io/fs"
    "net/http"
)
//go:embed staticFile
var myData embed.FS
func handler() http.Handler {
    file_system := fs.FS(myData)
    html, _ := fs.Sub(file_system, "staticFile")
    return http.FileServer(http.FS(html))
}
func main() {
    mux := http.NewServeMux()
    mux.Handle("/", handler())
    http.ListenAndServe(":8000", mux)
}

In this example, we include the same packages which are “crypto/sha256” and “fmt”, along with the “io” for input/output operations and “os” for file handling. Then, we set the main() function where the os.Open() function is deployed to open the “MyFile.txt” file for reading. When a file opens incorrectly, the program panics and crashes.

After that, to make sure that the file is shut when it is handled, we utilize the delay fileClose() command. Next, we employ the sha256.New() function which creates a new SHA-256 hash object named “hashValue”. The hash of the specified file is determined using this object. The io.Copy() function then copies the contents of the opened file (file) into the “hashValue” object.

When the program is executed, it opens the file, reads its contents, calculates the SHA-256 hash, and displays the hash value as a hexadecimal string as follows:

Conclusion

The SHA-256 encryption, coupled with Golang’s efficiency and simplicity, provides a robust and reliable mechanism to secure the sensitive data. Here, we implemented the various examples of using the “sha256” functions to generate the hash.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content