Skip to content

Instantly share code, notes, and snippets.

@kwilczynski
Created December 5, 2022 08:48
Show Gist options
  • Save kwilczynski/44c980053e9eb5d669de065b2e0e8894 to your computer and use it in GitHub Desktop.
Save kwilczynski/44c980053e9eb5d669de065b2e0e8894 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"net/url"
"strings"
"unicode/utf8"
)
func normalizePassword(input string, escape bool) (output string) {
s := input
// Assume that password is already escaped.
if strings.Contains(s, "%") {
// Prevent errant white spaces.
s = strings.Replace(s, "+", "%2B", -1)
// Verify if the password is already escaped; otherwise, only reserved
// characters are included that should be left intact.
if ss, _ := url.QueryUnescape(s); url.QueryEscape(ss) == s {
var err error
s, err = url.QueryUnescape(s)
if err != nil || !utf8.ValidString(s) {
// Unable to unescape password; not URL escaped or malformed encoding?
s = input
}
}
}
if escape {
s = url.QueryEscape(s)
}
output = s
return
}
func main() {
s1 := `test%123#`
s2 := `test%25123%23`
s3 := `test%123%A`
fmt.Println(s1, normalizePassword(s1, false))
fmt.Println(s2, normalizePassword(s2, false))
fmt.Println(s3, normalizePassword(s3, false))
fmt.Println(s1, normalizePassword(s1, true))
fmt.Println(s2, normalizePassword(s2, true))
fmt.Println(s3, normalizePassword(s3, true))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment