GolangStudy/src/study/day6/practice4.2.go

43 lines
973 B
Go
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package main
import (
"crypto/sha256"
"crypto/sha512"
"flag"
"fmt"
"os"
)
// 练习 4.2 编写一个程序默认情况下打印标准输入的SHA256编码
// 并支持通过命令行flag定制输出SHA384或SHA512哈希算法。
func main() {
var shaflag = flag.Int("sha", 256, "sha选择")
var str = flag.String("s", "default", "需要被加密的字符串")
flag.Parse()
fmt.Println(*shaflag, *str)
sha := func() []byte {
if *shaflag == 256 {
s := sha256.Sum256([]byte(*str))
res := make([]byte, len(s))
copy(res, s[:])
return res
} else if *shaflag == 384 {
s := sha512.Sum384([]byte(*str))
res := make([]byte, len(s))
copy(res, s[:])
return res
} else if *shaflag == 512 {
s := sha512.Sum512([]byte(*str))
res := make([]byte, len(s))
copy(res, s[:])
return res
} else {
fmt.Println("参数错误请输入256384512")
os.Exit(0)
}
return nil
}
fmt.Printf("%T \n%[1]x \n", sha())
}