golang

How to use md5 algorithm in GoLang


In this article, you are going to learn about how to use an md5 algorithm in the Go language.

MD5 is an algorithm that is used to compute a hash value. Though it is cryptographically broken, it is still used widely. This algorithm produces a 128-bit hash value. In the Go language, there’s a package available named crypto/md5 and with the help of this package, you may hash a string or a file input. Let’s see the below code example of how you can use this to compute a hash string value.

package main

import (
        "crypto/md5"
        "fmt"
)

func main() {
        
        hashString:= []byte("Hello World!")
        fmt.Printf("%x", md5.Sum(hashString))
}

//Output: ed076287532e86365e841e92bfc50d8c

Here, we define our main package and then import the crypto/md5 package and fmt package, and finally, in the main function, we hashed the string Hello World! with the help of md5.sum() and you can see the output where the string is converted into hash.

You can also use sha1.sum() function that comes with the crypto/md5 package. Let’s see an example of hashing Hello World! string using sha1 in the below:

package main

import (
        "crypto/sha1"
        "fmt"
)

func main() {

        sha1 := sha1.Sum([]byte("Hello World!"))
        fmt.Printf("%x\\n", sha1)
}

// Output: 2ef7bde608ce5404e97d5f042f95f89f1c232871

You can see the process is the same but the output is different while using sha1(). Similarly, you can use the sha256() that also comes with the crypto/md5 package. Let’s see the below code example:

package main

import (
        "crypto/sha256"
        "fmt"
)

func main() {

        sha256 := sha256.Sum256([]byte("Hello World!"))
        fmt.Printf("%x\\n", sha256)
}

//Output: 7f83b1657ff1fc53b92dc18148a1d65dfc2d4b1fa3d677284addd200126d9069

You can see that we have used the same string Hello World! but for three different sum functions while hashing but get the three different output.This is how you can use the package crypto/md5 for hashing a string in the Go language.


Share on social media

//