ag_tools/cmd/md5.go

55 lines
1.4 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package cmd
import (
"fmt"
"archgrid.xyz/ag/tools/types"
"archgrid.xyz/ag/toolsbox/hash/md5"
"archgrid.xyz/ag/toolsbox/serialize/base64"
"archgrid.xyz/ag/toolsbox/serialize/hex"
"github.com/spf13/cobra"
)
var (
md5File bool
md5Result types.ResultEncoding = types.ResultInHex
)
var md5Cmd = &cobra.Command{
Use: "md5",
Short: "使用md5算法计算文件或者字符串的哈希值。",
Long: `使用md5算法计算文件或者字符串的哈希值支持文件和字符串两种模式。文件模式使用 -f 参数,不使用 -f 参数时将使用字符串模式。`,
Args: cobra.MinimumNArgs(1),
Run: md5HashExecute,
}
func md5HashExecute(cmd *cobra.Command, args []string) {
var (
hashResult []byte
err error
)
if md5File {
hashResult, err = md5.SumFile(args[0])
} else {
hashResult = md5.MD5([]byte(args[0]))
}
if err != nil {
fmt.Printf("散列计算失败:%s\n", err)
return
}
switch md5Result {
case types.ResultInBase64:
fmt.Printf("散列结果:%s\n", base64.ToBase64(hashResult))
case types.ResultInHex:
fallthrough
default:
fmt.Printf("散列结果:%s\n", hex.ToHex(hashResult))
}
}
func init() {
md5Cmd.PersistentFlags().BoolVarP(&md5File, "file", "f", false, "使用文件模式。")
md5Cmd.PersistentFlags().VarP(&md5Result, "output", "o", "计算结果编码输出的格式可选Base64或者Hex编码默认使用Hex编码。")
rootCmd.AddCommand(md5Cmd)
}