Files
ag_tools/cmd/sha256.go
T

55 lines
1.5 KiB
Go

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