Home > OS >  Golang byte array - getting the checksum
Golang byte array - getting the checksum

Time:10-11

I have a byte array, made from a string:

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

it looks like expected:

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

Coming to go from python I assume there is a better way, than something like:

    func sum(array []int) int {  
      result := 0  
      for _, v := range array {  
        result  = v  
        }  
      return result  
    }

(the above fails as the numbers are not integers, so this would need another data conversion)

Is there a way to simply get the checksum of byte array?

Like:

    sum(array)

CodePudding user response:

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

CodePudding user response:

I think its 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

CodePudding user response:

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

  • Related