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