Skip to content

Instantly share code, notes, and snippets.

@mxwell
Last active August 29, 2015 13:57
Show Gist options
  • Save mxwell/9596148 to your computer and use it in GitHub Desktop.
Save mxwell/9596148 to your computer and use it in GitHub Desktop.
Byte-wise deciphering on base of known alphabet.
ab_name = "ab.txt"
cipher_name = "cipher.txt"
output_name = "output.txt"
import sys
if (len(sys.argv) < 2):
print("Error: too few arguments")
exit(0)
input_name = ""
inverse = False
if (len(sys.argv) == 3):
if (sys.argv[1] == "--encode"):
inverse = True
input_name = sys.argv[2]
elif (sys.argv[2] == "--encode"):
inverse = True
input_name = sys.argv[1]
else:
print("Error: unknown arguments")
exit(0)
elif (len(sys.argv) == 2):
input_name = sys.argv[1]
def try_conv(alphabet, code):
if (alphabet[code] == -1):
print("Warning: not found decoding for code %d (0x%02X)" % (code, code))
return code
return alphabet[code]
ab = open(ab_name, "rb")
src = [x for x in ab.read()]
ab.close()
cipher = open(cipher_name, "rb")
dst = [x for x in cipher.read()]
cipher.close()
if (inverse):
src, dst = dst, src
if (len(src) != len(dst)):
print("sizes of src and dst are different")
exit(0)
alphabet = [-1] * 256
for i in range(0, len(src)):
alphabet[dst[i]] = src[i]
# for i in range(0, len(alphabet)):
# val = alphabet[i]
# if (val != -1):
# print("%02X \t=>\t %02X" % (i, val))
BSIZE = 1024
input = open(input_name, "rb")
output = open(output_name, "wb")
while True:
data = input.read(BSIZE)
if not data:
break
output.write(bytes([try_conv(alphabet, x) for x in data]))
input.close()
output.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment