Skip to content

Commit ade1a45

Browse files
committed
Adds b64d
1 parent 780633b commit ade1a45

File tree

3 files changed

+100
-0
lines changed

3 files changed

+100
-0
lines changed

b64d/.gitignore

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
testfile
2+
b64d
3+
*.sw*

b64d/README.md

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# b64d
2+
3+
Find and decode base64-encoded strings in a file.
4+
5+
## Usage
6+
7+
```
8+
▶ b64d <filename>
9+
```
10+
11+
## Install
12+
13+
```
14+
▶ go get -u github.com/tomnomnom/hacks/b64d
15+
```

b64d/main.go

+82
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
package main
2+
3+
import (
4+
"encoding/base64"
5+
"flag"
6+
"fmt"
7+
"io/ioutil"
8+
"os"
9+
"regexp"
10+
"strings"
11+
"unicode"
12+
)
13+
14+
var ASCIIChar = &unicode.RangeTable{
15+
R16: []unicode.Range16{
16+
{0x0020, 0x007F, 1},
17+
},
18+
}
19+
20+
func main() {
21+
flag.Parse()
22+
23+
filename := flag.Arg(0)
24+
if filename == "" {
25+
fmt.Fprintln(os.Stderr, "usage: b64d <filename>")
26+
return
27+
}
28+
29+
f, err := os.Open(filename)
30+
if err != nil {
31+
fmt.Fprintf(os.Stderr, "%s\n", err)
32+
return
33+
}
34+
35+
b, err := ioutil.ReadAll(f)
36+
if err != nil {
37+
fmt.Fprintf(os.Stderr, "%s\n", err)
38+
return
39+
}
40+
41+
content := string(b)
42+
43+
// TODO: deal with urlencoded bits
44+
re := regexp.MustCompile("[^A-Za-z0-9+/][a-zA-Z0-9+/]+={0,2}")
45+
matches := re.FindAllString(content, -1)
46+
47+
if matches == nil {
48+
return
49+
}
50+
51+
for _, m := range matches {
52+
53+
if len(m) < 7 {
54+
continue
55+
}
56+
57+
// match has one extra char at the beginning
58+
if (len(m)-1)%4 != 0 {
59+
continue
60+
}
61+
decb, _ := base64.StdEncoding.DecodeString(m[1:])
62+
decoded := string(decb)
63+
if decoded == "" {
64+
continue
65+
}
66+
67+
decoded = strings.Replace(decoded, "\n", " ", -1)
68+
69+
containsNonASCII := false
70+
for _, r := range decoded {
71+
if !unicode.Is(ASCIIChar, r) {
72+
containsNonASCII = true
73+
break
74+
}
75+
}
76+
if containsNonASCII {
77+
continue
78+
}
79+
80+
fmt.Println(decoded)
81+
}
82+
}

0 commit comments

Comments
 (0)