Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang md5 Write vs Sum - why different outputs?

Tags:

go

md5

Can anyone explain why these methods produce two different output values? It isn't clear from the md5 docs.

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

func GetMD5HashWithWrite(text string) string {
    hasher := md5.New()
    hasher.Write([]byte(text))
    return hex.EncodeToString(hasher.Sum(nil))
}

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

See example: https://play.golang.org/p/Fy7KgfCvXc

like image 343
tgreiser Avatar asked Jan 07 '23 05:01

tgreiser


1 Answers

I was mixing up hasher.Sum() with md5.Sum(). These do produce equivalent outputs.

func GetMD5HashWithWrite(text string) []byte {
    hasher := md5.New()
    hasher.Write([]byte(text))
    return hasher.Sum(nil)
}

func GetMD5HashWithSum(text string) [16]byte {
    return md5.Sum([]byte(text))
}

Playground: https://play.golang.org/p/fpE5ztnh5U

like image 65
tgreiser Avatar answered Jan 13 '23 18:01

tgreiser