Skip to content

Instantly share code, notes, and snippets.

@hasherezade
Created July 12, 2017 21:01
Show Gist options
  • Select an option

  • Save hasherezade/35d6b355fbcb81f0f35fd1c47bf6ce93 to your computer and use it in GitHub Desktop.

Select an option

Save hasherezade/35d6b355fbcb81f0f35fd1c47bf6ce93 to your computer and use it in GitHub Desktop.
Base58 decoder
#!/usr/bin/env python2.7
import sys
import os
import argparse
# Base58 charset
alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
if bytes == str: # python2
iseq = lambda s: map(ord, s)
bseq = lambda s: ''.join(map(chr, s))
buffer = lambda s: s
def b58encode(v):
origlen = len(v)
v = v.lstrip(b'\0')
newlen = len(v)
p, acc = 1, 0
for c in iseq(v[::-1]):
acc += p * c
p = p << 8
result = ''
while acc > 0:
acc, mod = divmod(acc, 58)
result += alphabet[mod]
return (result + alphabet[0] * (origlen - newlen))[::-1]
def b58decode(v):
if not isinstance(v, str):
v = v.decode('ascii')
origlen = len(v)
v = v.lstrip(alphabet[0])
newlen = len(v)
p, acc = 1, 0
for c in v[::-1]:
try:
acc += p * alphabet.index(c)
p *= 58
except:
continue
result = []
while acc > 0:
acc, mod = divmod(acc, 256)
result.append(mod)
return (bseq(result) + b'\0' * (origlen - newlen))[::-1]
def main():
parser = argparse.ArgumentParser(description="Byte converter")
parser.add_argument('--decode', dest="decode", default=False, help="Decode?", action='store_true')
parser.add_argument('--infile', dest="infile", default=None, help="Input file", required=True)
parser.add_argument('--outfile', dest="outfile", default="out.tmp", help="Output file")
args = parser.parse_args()
outbuf = None
with open(args.infile, "r") as fileIn:
buf = fileIn.read()
if args.decode:
outbuf = b58decode(buf)
else:
outbuf = b58encode(buf)
if outbuf == None:
print "Failed"
return
with open(args.outfile, "wb") as fileOut:
fileOut.write(outbuf)
print "Saved to a file: " + args.outfile
if __name__ == "__main__":
sys.exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment