Table of Contents
Introduction to Golang sha512
In previous chapter, we discuss about how to encrypt and decrypt data in Golang. With today's article, we will examine some example of using SHA-512 to hash data:
SHA-512 is a function of cryptographic algorithm SHA-2, which is an evolution of famous SHA-1. SHA-512 is very close to Sha-256 except that it used 1024 bits "blocks", and accept as input a 2^128 bits maximum length string. SHA-512 also has others algorithmic modifications in comparison with Sha-256.
In Go, we can use crypto/sha512Â to hash data:
crypto/sha512
: Package sha512 implements the SHA-384, SHA-512, SHA-512/224, and SHA-512/256 hash algorithms as defined in FIPS 180-4. All the hash.Hash implementations returned by this package also implement encoding.BinaryMarshaler and encoding.BinaryUnmarshaler to marshal and unmarshal the internal state of the hash.
Example 1: Using sha512.Sum() to hash data
Here is an example of create a new sha515
hash and Sum()
function to return the checksum of data:
package main
import (
"crypto/sha512"
"fmt"
)
func main() {
input := "Hello GoLinuxCloud!"
sha_512 := sha512.New()
// sha from a byte array
sha_512.Write([]byte(input))
fmt.Printf("sha512: %x\n", sha_512.Sum(nil))
}
Output:
sha512: 84ad5dfdd5265d37a3732986ffdee98fc0e635dbffa16f8771f5421cfb9c13dee61183d2ab8c90e647cf00daaa4e6141d2c2e40c4c39cbd42e3629c9076bff42
Example 2: Using sha512.Sum512() to hash data
sha512.Sum512()
: Sum512 returns the SHA512 checksum of the data.
Here is an example of using Sum512()
to hash a byte array:
package main
import (
"crypto/sha512"
"fmt"
)
func main() {
input := "Hello GoLinuxCloud!"
sha := sha512.Sum512([]byte(input))
fmt.Printf("sha512: %x\n", sha3)
}
Output:
sha512: 84ad5dfdd5265d37a3732986ffdee98fc0e635dbffa16f8771f5421cfb9c13dee61183d2ab8c90e647cf00daaa4e6141d2c2e40c4c39cbd42e3629c9076bff42
Example 3: Hash and Salt Passwords in Golang Using SHA-512
The industry standard for safeguarding passwords for any reputable service is hashing and salting. Using the quick-calculating SHA-512 algorithm is one choice. We will follow 4 steps to hash and salt a password:
- Convert the password to a byte slice
- Generate random salt of 16 bytes
- Append salt to password slice
- Hash the result
Let's take a look at the detail code:
package main
import (
"crypto/rand"
"crypto/sha512"
"encoding/hex"
"fmt"
)
// Define salt size
const saltSize = 16
// Generate 16 bytes randomly
func generateSalt(saltSize int) []byte {
var salt = make([]byte, saltSize)
_, err := rand.Read(salt[:])
if err != nil {
panic(err)
}
return salt
}
// Combine password and salt then hash them using the SHA-512
func hashFunc(password string, salt []byte) string {
// Convert password string to byte slice
var pwdByte = []byte(password)
// Create sha-512 hasher
var sha512 = sha512.New()
pwdByte = append(pwdByte, salt...)
sha512.Write(pwdByte)
// Get the SHA-512 hashed password
var hashedPassword = sha512.Sum(nil)
// Convert the hashed to hex string
var hashedPasswordHex = hex.EncodeToString(hashedPassword)
return hashedPasswordHex
}
// Check if two passwords match
func doPasswordsMatch(hashedPassword, currPassword string,
salt []byte) bool {
var currPasswordHash = hashFunc(currPassword, salt)
return hashedPassword == currPasswordHash
}
func main() {
var salt = generateSalt(saltSize)
// Hash password
var hashedPassword = hashFunc("Hello GoLinuxcloud", salt)
fmt.Println("Salt:", salt)
fmt.Println("Hased Password:", hashedPassword)
// Check if hashed password match original string
fmt.Println("check hashed passwor with ", "hello", ":",
doPasswordsMatch(hashedPassword, "hello", salt))
fmt.Println("check hashed passwor with ", "Hello GoLinuxcloud", ":",
doPasswordsMatch(hashedPassword, "Hello GoLinuxcloud", salt))
}
Output:
Salt: [37 134 147 225 191 181 103 195 185 185 142 69 247 240 106 188]
Hased Password: 80f770d6991883e26ca4286dbc3fd9cad83ef3eea933d70ef15e42335d6a7a97e67d18b1a753e0f397179bcf5ca025575d123c24aecfeee22eae938050b4324d
check hashed passwor with hello : false
check hashed passwor with Hello GoLinuxcloud : true
Summary
Here are some examples of using sha512 in Golang. Noted that SHA512 is a hash algorithm based on non-linear functions, so it is impossible to decryption method and so is made to be uncrackable.
References
https://en.bitcoinwiki.org/wiki/SHA-512
https://en.wikipedia.org/wiki/SHA-2
https://pkg.go.dev/crypto/sha512
https://en.wikipedia.org/wiki/Checksum
https://en.wikipedia.org/wiki/Salt_(cryptography)