g g
g g

Reputation: 33

checksum of a byte array

I have a []byte, made from a string:

    array := []byte("some string")

It looks like expected:

    [115 111 109 101 32 115 116 114 105 110 103]

Is there a way to simply get the checksum of []byte? Like:

    sum(array)

Upvotes: 1

Views: 2922

Answers (3)

Zombo
Zombo

Reputation: 1

I think it's good to avoid using fmt for conversion when possible:

package main

import (
   "crypto/md5"
   "encoding/hex"
)

func checksum(s string) string {
   b := md5.Sum([]byte(s))
   return hex.EncodeToString(b[:])
}

func main() {
   s := checksum("some string")
   println(s == "5ac749fbeec93607fc28d666be85e73a")
}

https://godocs.io/crypto/md5#Sum

Upvotes: 1

Bilal Khan
Bilal Khan

Reputation: 129

package main

import (
    "crypto/md5"
    "encoding/hex"
    "fmt"
)

func GetMD5HashWithSum(text string) string {
    hash := md5.Sum([]byte(text))
    return hex.EncodeToString(hash[:])
}

func main() {
    hello := GetMD5HashWithSum("some string")
    fmt.Println(hello)
}

You can it on Golang Playground

Upvotes: 0

Antonio Thomacelli
Antonio Thomacelli

Reputation: 108

Maybe you need md5.sum to check reliability.

https://pkg.go.dev/crypto/md5#Sum

package main

import (
    "crypto/md5"
    "fmt"
)

func main() {
    data := []byte("some string")
    fmt.Printf("%x", md5.Sum(data))
}

Another example.

https://play.golang.org/p/7_ctunsqHS3

Upvotes: 1

Related Questions