目录
需求:
用golang计算一个字符串的md5值
我们先用shell来计算一下,再去判断golang计算的md5值是否正确
在线md5计算工具:
https://www.sojson.com/encrypt_md5.html

用shell计算字符串md5值
echo "helloworld"|md5sum

结果计算的值跟在线的不对应,这是怎么回事,是在线的计算错了,还是我shell命令计算错了
原来是echo 默认是在字符串最后加上了"\n",上图里计算的是带有"\n"的计算值
如何获取echo的帮助文档
方式一:
man echo

方式二:
我们都知道一般linux命令的帮助信息,是 command -h,command --h,command -help,command --help,可是这些对echo 命令都不好使,这个命令是回显的,echo 什么就回显什么,如图

这个命令得反过来 是help echo

通过echo 帮助文档,我们可以使用-n不追加\n,
所以最后正确的用shell命令获取字符串的方式应该是,这就跟在线的对应起来了
echo -n "helloworld"|md5sum

用golang计算字符串的md5值
package main
import (
"crypto/md5"
"encoding/hex"
"fmt"
)
func MD5(str string) string {
signByte := []byte(str)
hash := md5.New()
hash.Write(signByte)
return hex.EncodeToString(hash.Sum(nil))
}
func main() {
str := "helloworld"
stMD5 := MD5(str)
fmt.Println("str:", str, "\nstrMD5", stMD5)
}
运行结果:
验证,用shell golang和在线md5计算工具
番外:
在mac系统上计算md5的方式:
md5 -s helloworld
