package postbank import ( "encoding/base64" "fmt" "github.com/spf13/cobra" ) // go run main.go postbank encrypt --key="sm4 key" var encryptCmd = &cobra.Command{ Use: "encrypt", 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 } // 不强制 if err = argsToStringContext(cmd, accessTokenKey, accessTokenContextKey); err != nil { return err } return nil }, Run: encryptRun, } func encryptRun(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) accessToken := cmd.Context().Value(accessTokenContextKey).(string) res, errStr := encrypt(merchantId, privateKey, sopPublicKey, inputJson, accessToken, isRequest) cmd.Println(res) cmd.Print(errStr) } func encrypt(merchantId, privateKey, sopPublicKey, inputJson, accessToken string, isRequest bool) (string, string) { data, _ := base64.StdEncoding.DecodeString(inputJson) resp, err := Encrypt(merchantId, privateKey, sopPublicKey, string(data), accessToken, isRequest) if err != nil { return "fail", fmt.Sprintf("加密失败: %v", err) } return resp, "success" }