-
Notifications
You must be signed in to change notification settings - Fork 0
/
base64enc
executable file
·123 lines (115 loc) · 4.94 KB
/
base64enc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys, os, base64, binascii, itertools, logging
from extras import colorize
from extras import ColoredArgParser
from extras import ColoredLogger
from extras import ColoredSetting
from extras import init_colored_logger
from extras import FileRead
from extras import trydecodingbytes
from extras import RingLooper
output_palette = ( { 'fgcolor' : 'green', 'set' : ( 'bold', ) },
{ 'fgcolor' : 'yellow', 'set' : ( 'bold', ) },
{ 'fgcolor' : 'blue', 'set' : ( 'bold', ) },
{ 'fgcolor' : 'magenta', 'set' : ( 'bold', ) },
{ 'fgcolor' : 'cyan', 'set' : ( 'bold', ) },
{ 'fgcolor' : 'light green', 'set' : ( 'bold', ) },
{ 'fgcolor' : 'light yellow', 'set' : ( 'bold', ) },
{ 'fgcolor' : 'light blue', 'set' : ( 'bold', ) },
{ 'fgcolor' : 'light magenta', 'set' : ( 'bold', ) },
{ 'fgcolor' : 'light cyan', 'set' : ( 'bold', ) }, )
LINE_WIDTH = 76
def is_valid_file(parser, f):
if f != '-' and not os.path.isfile(f):
parser.error("%s: No such file" % f)
else:
return f
def parse_args():
parser = ColoredArgParser(description = 'Support encode/decode of base 16 32 64 85.')
parser.add_argument('-c', '--characters',
choices = ('16', '32', '64', '85'),
default = '64',
help = 'The number of characters, the default is 64.')
parser.add_argument('-d', '--decode',
action = 'store_true',
default = False,
dest = 'is_decode',
help = 'Decode the data.')
parser.add_argument('-u', '--urlsafe',
action = 'store_true',
default = False,
dest = 'is_urlsafe',
help = 'Using the URL safe alphabet for Base64 only.')
parser.add_argument('-i', '--infile',
action = 'append',
type = lambda f: is_valid_file(parser, f),
help = 'File path.')
parser.add_argument('-e', '--encoding',
default = None,
help = 'Character encoding for decode only.')
parser.add_argument('-w', '--nowrap',
action = 'store_true',
default = False,
dest = 'is_nowrap',
help = 'Does not wrap when output after encode.')
parser.add_argument('--color',
choices = ['auto', 'always', 'never'],
default = 'auto',
dest = 'colored',
help = 'When to colored, the default is auto.')
parser.add_argument('strings',
nargs = '*',
help = 'Strings for encoding or decoding.')
return parser.parse_args()
def convert(func, bs, is_decode, encoding, is_nowrap, paint):
try:
converted_bs = func(bs)
except binascii.Error as e:
logging.getLogger(__name__).error(str(e))
return
else:
if is_decode:
if not encoding:
s, _ = trydecodingbytes(converted_bs)
else:
try:
s = converted_bs.decode(encoding = encoding)
except UnicodeDecodeError:
s = str(converted_bs)
print(colorize(s, enabling = ColoredSetting().is_colorize(sys.stdout), **paint))
else:
s = converted_bs.decode(errors = 'ignore')
if not is_nowrap:
start = 0
while(s[start:]):
lw = min(LINE_WIDTH, len(s[start:]))
print(colorize('%*.*s' % (-lw, lw, s[start:]), enabling = ColoredSetting().is_colorize(sys.stdout), **paint))
start += LINE_WIDTH
else:
print(colorize(s, enabling = ColoredSetting().is_colorize(sys.stdout), **paint))
def main(args = None):
if args is None:
return 0
ColoredSetting(args.colored)
init_colored_logger()
func = eval('base64.%sb%s%s' %
('urlsafe_' if args.characters == '64' and args.is_urlsafe else '',
args.characters,
'decode' if args.is_decode else 'encode'))
paletteiter = iter(RingLooper(*output_palette))
for i in args.strings:
paint = next(paletteiter)
print(colorize(repr(i), enabling = ColoredSetting().is_colorize(sys.stdout), **paint))
convert(func, i.encode(), args.is_decode, args.encoding, args.is_nowrap, paint)
if not args.strings and not args.infile:
args.infile = ( '-', )
if args.infile:
readhook = (lambda f: b''.join(f.read().splitlines())) if args.is_decode else None
freader = FileRead(args.infile, mode = 'rb', prompt_when_stdin = 'Press Ctrl-D when finished.', readhook = readhook)
for content in freader:
paint = next(paletteiter)
print(colorize(repr(freader.filename()), enabling = ColoredSetting().is_colorize(sys.stdout), **paint))
convert(func, content, args.is_decode, args.encoding, args.is_nowrap, paint)
if __name__ == '__main__':
sys.exit(main(parse_args()))