Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "fmt"
- "io"
- "io/ioutil"
- "os"
- "regexp"
- "strings"
- )
- func main() {
- defer func() {
- if rec := recover(); rec != nil {
- fmt.Fprintf(os.Stderr, "error: %v\n", rec)
- os.Exit(1)
- }
- }()
- obfuscate()
- }
- func obfuscate() {
- re := regexp.MustCompile(`\b[_a-zA-Z][_a-zA-Z0-9]*\b`)
- data, err := ioutil.ReadAll(os.Stdin)
- chk(err)
- var (
- idxs = re.FindAllIndex(data, -1)
- subst = map[string]string{}
- w io.Writer = os.Stdout
- isStr bool
- escaped bool
- last int
- idNum int
- write = writeFunc(w, &isStr, &escaped)
- )
- addConst(subst, keywords[:])
- addConst(subst, funcs[:])
- subst["main"] = "main"
- for _, idx := range idxs {
- i, j := idx[0], idx[1]
- write(data[last:i])
- last = j
- if isStr {
- write(data[i:j])
- continue
- }
- s := string(data[i:j])
- replS := subst[s]
- if replS == "" {
- idNum++
- replS = strings.Repeat("_", idNum)
- subst[s] = replS
- }
- fmt.Fprint(w, replS)
- }
- write(data[last:len(data)])
- }
- func writeFunc(w io.Writer, isStr *bool, escaped *bool) func([]byte) error {
- return func(slice []byte) error {
- for i := range slice {
- if *escaped {
- *escaped = false
- continue
- }
- if slice[i] == '"' {
- *isStr = !*isStr
- } else if *isStr && slice[i] == '\\' {
- *escaped = true
- }
- }
- _, err := w.Write(slice)
- return err
- }
- }
- func addConst(subst map[string]string, cs []string) {
- for _, c := range cs {
- subst[c] = c
- }
- }
- var keywords = [...]string{
- "False", "class", "finally", "is", "return",
- "None", "continue", "for", "lambda", "try",
- "True", "def", "from", "nonlocal", "while",
- "and", "del", "global", "not", "with",
- "as", "elif", "if", "or", "yield",
- "assert", "else", "import", "pass",
- "break", "except", "in", "raise",
- }
- // only a minimal set for now because I couldn't find a listing that would be easy to parse into a Go array
- var funcs = [...]string{
- "print", "remove", "insert", "xrange", "range", "enumerate", "list",
- }
- func chk(err error) {
- if err != nil {
- panic(err)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement