Files
ag_tools/cmd/sha1.go
T

55 lines
1.4 KiB
Go

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