Crypto sha

Comment

Author: Admin | 2025-04-28

Introduction to Golang sha512In 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 dataHere is an example of create a new sha515 hash and Sum() function to return the checksum of data:package mainimport ( "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: 84ad5dfdd5265d37a3732986ffdee98fc0e635dbffa16f8771f5421cfb9c13dee61183d2ab8c90e647cf00daaa4e6141d2c2e40c4c39cbd42e3629c9076bff42Example 2: Using sha512.Sum512() to hash datasha512.Sum512(): Sum512 returns the SHA512 checksum of the data.Here is an example of using Sum512() to hash a byte array:package mainimport ( "crypto/sha512" "fmt")func main() { input := "Hello GoLinuxCloud!" sha := sha512.Sum512([]byte(input)) fmt.Printf("sha512: %x\n", sha3)}Output:sha512: 84ad5dfdd5265d37a3732986ffdee98fc0e635dbffa16f8771f5421cfb9c13dee61183d2ab8c90e647cf00daaa4e6141d2c2e40c4c39cbd42e3629c9076bff42Example 3: Hash and Salt Passwords in Golang Using SHA-512The 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 sliceGenerate random salt of 16 bytesAppend salt to password sliceHash the resultLet's take a look at the detail code:package mainimport ( "crypto/rand" "crypto/sha512" "encoding/hex" "fmt")// Define salt sizeconst saltSize = 16// Generate 16 bytes randomlyfunc 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-512func hashFunc(password string, salt []byte) string { // Convert password string to byte slice var pwdByte = []byte(password) // Create sha-512 hasher var

Add Comment