package postbank import ( "encoding/base64" "fmt" "github.com/spf13/cobra" ) // go run main.go postbank decrypt --key="sm4 key" var decryptCmd = &cobra.Command{ Use: "decrypt", Short: "邮储国密解密", Args: func(cmd *cobra.Command, args []string) error { var err error if err = forceArgsToStringContext(cmd, merchantIdKey, merchantIdContextKey); err != nil { return err } if err = forceArgsToStringContext(cmd, privateKeyKey, privateKeyContextKey); err != nil { return err } if err = forceArgsToStringContext(cmd, sopPublicKeyKey, sopPublicKeyContextKey); err != nil { return err } if err = forceArgsToStringContext(cmd, inputKey, inputContextKey); err != nil { return err } if err = forceArgsToBoolContext(cmd, isRequestKey, isRequestContextKey); err != nil { return err } return nil }, Run: decryptRun, } func decryptRun(cmd *cobra.Command, args []string) { merchantId := cmd.Context().Value(merchantIdContextKey).(string) privateKey := cmd.Context().Value(privateKeyContextKey).(string) sopPublicKey := cmd.Context().Value(sopPublicKeyContextKey).(string) inputJson := cmd.Context().Value(inputContextKey).(string) isRequest := cmd.Context().Value(isRequestContextKey).(bool) res, errStr := decrypt(merchantId, privateKey, sopPublicKey, inputJson, isRequest) cmd.Println(res) cmd.Print(errStr) } func decrypt(merchantId, privateKey, sopPublicKey, inputJson string, isRequest bool) (string, string) { data, _ := base64.StdEncoding.DecodeString(inputJson) resp, err := Decrypt(merchantId, privateKey, sopPublicKey, string(data), isRequest) if err != nil { return "fail", fmt.Sprintf("解密失败: %v", err) } return resp, "success" }