├── README.md ├── aes_cbc.py ├── aes_ecb.py ├── convert.py ├── decompress.py ├── dexor.py ├── file2png.py ├── morse ├── main.py └── morse.py ├── quick_aes ├── README.md └── quick_aes.py └── rc4.py /README.md: -------------------------------------------------------------------------------- 1 | # crypto_utils 2 | Set of my small utils related to cryptography, encoding, decoding etc
3 | + morse : decoder/encoder for morse code with option of custom character set
4 | + file2png.py: Visualise raw bytes of any given file and saves as a PNG
5 | + convert.py: Fetches bytes represented as ASCII strings (hexadecimal, decimal, binary) and converts them into raw binary
6 | + dexor.py: XOR file content (starting from a given offset) with a given key
7 | + quick_aes: A tiny tool to provide fast AES encryption of strings and files (dedicated for encrypting messages - provides random IV and Base64 encoding of output)
8 | + aes_ecb: AES ECB mode - simple encryptor/decryptor
9 | + aes_cbc: AES CBC mode - simple encryptor/decryptor
10 | + rc4: RC4 encryptor/decryptor
11 | -------------------------------------------------------------------------------- /aes_cbc.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python2.7 2 | 3 | import sys 4 | import os 5 | import argparse 6 | import base64 7 | import hashlib 8 | import getpass 9 | from Crypto.Cipher import AES 10 | from Crypto import Random 11 | 12 | BS = 16 13 | pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS) 14 | unpad = lambda s : s[:-ord(s[len(s)-1:])] 15 | 16 | class AESCipher: 17 | def __init__( self, key, iv): 18 | self.key = key 19 | self.iv = iv 20 | 21 | def encrypt( self, raw ): 22 | raw = pad(raw) 23 | cipher = AES.new( self.key, AES.MODE_CBC, self.iv ) 24 | return cipher.encrypt(raw) 25 | 26 | def decrypt( self, enc ): 27 | cipher = AES.new(self.key, AES.MODE_CBC, self.iv ) 28 | return unpad(cipher.decrypt(enc)) 29 | ### 30 | def expand_key(key): 31 | while len(key) < BS: 32 | key = key + key 33 | return key[:BS] 34 | 35 | def get_raw_bytes(filename, offset=0): 36 | fo = open(filename,"rb") 37 | fo.seek(offset, 0) 38 | data = fo.read() 39 | fo.close() 40 | return data 41 | 42 | def save_raw_bytes(filename, data): 43 | fo = open(filename,"wb") 44 | fo.write(data) 45 | fo.close() 46 | 47 | def main(): 48 | parser = argparse.ArgumentParser(description="AES ECB Encoder/Decoder") 49 | parser.add_argument('--infile', dest="infile", default=None, help="Input file") 50 | parser.add_argument('--outfile', dest="outfile", default="out.tmp", help="Output file") 51 | parser.add_argument('--key', dest="key", default="test", help="Key") 52 | parser.add_argument('--iv', dest="iv", default="test", help="Initialization vector") 53 | parser.add_argument('--decode', dest="decode", default=False, action='store_true', help="Decode or encode the given input?") 54 | args = parser.parse_args() 55 | 56 | key = expand_key(args.key) 57 | iv = expand_key(args.iv) 58 | print key 59 | 60 | if args.infile is None: 61 | #read message from stdin: 62 | outfile = None 63 | print "Enter a message:" 64 | raw = raw_input() 65 | else: 66 | filename = args.infile 67 | raw = get_raw_bytes(filename) 68 | print len(raw) 69 | 70 | aes = AESCipher(key, iv) 71 | if args.decode: 72 | output = aes.decrypt(raw) 73 | else: 74 | output = aes.encrypt(raw) 75 | 76 | outfile = args.outfile 77 | if outfile: 78 | save_raw_bytes(outfile, output) 79 | print "[OK] Output: " + outfile 80 | else: 81 | print "---" 82 | print output 83 | print "---" 84 | 85 | if __name__ == "__main__": 86 | main() 87 | 88 | -------------------------------------------------------------------------------- /aes_ecb.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python2.7 2 | 3 | import sys 4 | import os 5 | import argparse 6 | import base64 7 | import hashlib 8 | import getpass 9 | from Crypto.Cipher import AES 10 | from Crypto import Random 11 | 12 | BS = 32 13 | pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS) 14 | unpad = lambda s : s[:-ord(s[len(s)-1:])] 15 | 16 | class AESCipher: 17 | def __init__( self, key ): 18 | self.key = "".join(map(chr, key)) 19 | 20 | def encrypt( self, raw ): 21 | raw = pad(raw) 22 | cipher = AES.new( self.key, AES.MODE_ECB ) 23 | return cipher.encrypt(raw) 24 | 25 | def decrypt( self, enc ): 26 | cipher = AES.new(self.key, AES.MODE_ECB ) 27 | return unpad(cipher.decrypt(enc)) 28 | ### 29 | def expand_key(key): 30 | while len(key) < BS: 31 | key = key + key 32 | return key[:BS] 33 | 34 | def get_raw_bytes(filename, offset=0): 35 | fo = open(filename,"rb") 36 | fo.seek(offset, 0) 37 | data = fo.read() 38 | fo.close() 39 | return data 40 | 41 | def save_raw_bytes(filename, data): 42 | fo = open(filename,"wb") 43 | fo.write(data) 44 | fo.close() 45 | 46 | def main(): 47 | parser = argparse.ArgumentParser(description="AES ECB Encoder/Decoder") 48 | parser.add_argument('--infile', dest="infile", default=None, help="Input file") 49 | parser.add_argument('--outfile', dest="outfile", default="out.tmp", help="Output file") 50 | parser.add_argument('--key', dest="key", default="test", help="Key") 51 | parser.add_argument('--keyfile', dest="keyfile", default=None, help="File with the key") 52 | parser.add_argument('--decode', dest="decode", default=False, action='store_true', help="Decode or encode the given input?") 53 | args = parser.parse_args() 54 | 55 | 56 | if (args.key == None and args.keyfile == None): 57 | print "Supply key or keyfile" 58 | exit (-1) 59 | 60 | if args.keyfile: 61 | key = bytearray(open(args.keyfile, 'rb').read()) 62 | else: 63 | key = bytearray(args.key) 64 | 65 | key = expand_key(key) 66 | print key 67 | print len(key) 68 | 69 | if args.infile is None: 70 | #read message from stdin: 71 | outfile = None 72 | print "Enter a message:" 73 | raw = raw_input() 74 | else: 75 | filename = args.infile 76 | raw = get_raw_bytes(filename) 77 | print len(raw) 78 | 79 | aes = AESCipher(key) 80 | if args.decode: 81 | output = aes.decrypt(raw) 82 | else: 83 | output = aes.encrypt(raw) 84 | 85 | outfile = args.outfile 86 | if outfile: 87 | save_raw_bytes(outfile, output) 88 | print "[OK] Output: " + outfile 89 | else: 90 | print "---" 91 | print output 92 | print "---" 93 | 94 | if __name__ == "__main__": 95 | main() 96 | 97 | -------------------------------------------------------------------------------- /convert.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python2.7 2 | """convert.py: Fetches bytes represented as ASCII strings (hexadecimal, decimal, binary) and converts them into raw binary""" 3 | 4 | __author__ = 'hasherezade' 5 | __license__ = "GPL" 6 | 7 | import os 8 | import sys 9 | import re 10 | import argparse 11 | 12 | HEX_BYTE = r'[0-9a-fA-F]{2}\s' 13 | DEC_BYTE = r'[0-9]{1,3}\s' 14 | BIN_BYTE = r'[0-1]{8}\s' 15 | 16 | def chunks(s, n): 17 | for start in range(0, len(s), n): 18 | yield s[start:start+n] 19 | 20 | def fetch_chunks(buf, base, is_cont): 21 | pattern = HEX_BYTE 22 | chunk_len = 2 23 | if base == 10: 24 | pattern = DEC_BYTE 25 | chunk_len = 3 26 | elif base == 2: 27 | pattern = BIN_BYTE 28 | chunk_len = 8 29 | 30 | if is_cont == False: 31 | return re.findall (pattern, buf) 32 | t = [] 33 | for chunk in chunks(buf, chunk_len): 34 | t.append(chunk) 35 | return t 36 | 37 | 38 | def convert_chunks(buf, base_id, is_cont): 39 | base = 16 40 | if base_id == 'd': 41 | base = 10 42 | elif base_id == 'b': 43 | base = 2 44 | buf = buf.strip() 45 | t = fetch_chunks(buf, base, is_cont) 46 | byte_buf = [] 47 | for chunk in t: 48 | num = int (chunk, base) 49 | byte_buf.append(num) 50 | return byte_buf 51 | 52 | def main(): 53 | parser = argparse.ArgumentParser(description="Byte converter") 54 | parser.add_argument('--infile', dest="infile", default=None, help="Input file", required=True) 55 | parser.add_argument('--outfile', dest="outfile", default="out.tmp", help="Output file") 56 | parser.add_argument('--is_cont', dest="is_cont", default=False, help="Is it a continuous string? (if False: delimiter separated)", action='store_true') 57 | parser.add_argument('--base', dest="base_id", default='h', help="Number base. Supported: b - binary, d - decimal, h -hexadecimal.", required=True) 58 | args = parser.parse_args() 59 | 60 | in_fileName = args.infile 61 | out_fileName = args.outfile 62 | byte_buf = None 63 | with open(in_fileName, "r") as fileIn: 64 | buf = fileIn.read() 65 | byte_buf = convert_chunks(buf, args.base_id, args.is_cont) 66 | 67 | if len(byte_buf) == 0: 68 | print "Parsing error" 69 | exit (-1) 70 | 71 | byte_arr = bytearray(byte_buf) 72 | with open(out_fileName, "wb") as fileOut: 73 | fileOut.write(byte_arr) 74 | print "Saved to a file: " + out_fileName 75 | 76 | if __name__ == "__main__": 77 | sys.exit(main()) 78 | 79 | -------------------------------------------------------------------------------- /decompress.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python2.7 2 | """decompress.py: Zlib compressor/decompresso""" 3 | 4 | __author__ = 'hasherezade' 5 | __license__ = "GPL" 6 | 7 | import sys 8 | import os, argparse 9 | import zlib 10 | 11 | def getfilebytes(filename,offset=0): 12 | """ 13 | Get bytes from source file 14 | """ 15 | fo = open(filename,"rb") 16 | fo.seek(offset,0) #seek from current file position 17 | data = fo.read() 18 | fo.close() 19 | return (len(data),data) 20 | 21 | def get_raw_bytes(filename): 22 | filesize = os.path.getsize(filename) 23 | (bytesread,rawbytes) = getfilebytes(filename) 24 | return rawbytes 25 | 26 | ### 27 | 28 | def save_decoded(decdata, outfile): 29 | fr = open(outfile, "wb") 30 | if fr is None: 31 | return False 32 | for a in decdata: 33 | fr.write('%c' % a) 34 | fr.close() 35 | return True 36 | 37 | def main(): 38 | parser = argparse.ArgumentParser(description="Zlib compressor/decompressor") 39 | parser.add_argument('--infile', dest="infile", default=None, help="Input file", required=True) 40 | parser.add_argument('--outfile', dest="outfile", default=None, help="Output file") 41 | parser.add_argument('--decode', dest="decode", default=False, help="Decode the given file?", action='store_true') 42 | args = parser.parse_args() 43 | 44 | filename = args.infile 45 | outfile = args.outfile 46 | 47 | if outfile is None: 48 | outfile = "out.bin" 49 | 50 | print "Input: " + filename 51 | print "Output: " + outfile 52 | rawbytes = get_raw_bytes(filename) 53 | 54 | if args.decode: 55 | print "[+] Decompressing..." 56 | outdata = zlib.decompress(rawbytes) 57 | else: 58 | print "[+] Compressing..." 59 | outdata = zlib.compress(rawbytes) 60 | 61 | if save_decoded(outdata, outfile): 62 | print "[+] Saved to: " + outfile 63 | else: 64 | print "[-] Error: cannot write to file: " + outfile 65 | 66 | if __name__ == "__main__": 67 | main() 68 | -------------------------------------------------------------------------------- /dexor.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import argparse 4 | 5 | def decode(data, key, offset): 6 | maxlen = len(data) 7 | keylen = len(key) 8 | j = 0 #key index 9 | decoded = bytearray() 10 | for i in range(offset, maxlen): 11 | dec = data[i] ^ key[j % keylen] 12 | j += 1 13 | decoded.append(dec) 14 | return decoded 15 | 16 | def save_decoded(decdata, outfile): 17 | fr = open(outfile, "wb") 18 | if fr is None: 19 | return False 20 | fr.write(bytes(decdata)) 21 | 22 | fr.close() 23 | return True 24 | 25 | def main(): 26 | parser = argparse.ArgumentParser(description="Data XOR") 27 | parser.add_argument('--file', dest="file", default=None, help="Input file", required=True) 28 | parser.add_argument('--outfile', dest="outfile", default="out.bin", help="Output file") 29 | parser.add_argument('--key', dest="key", default=None, help="Value with which to XOR") 30 | parser.add_argument('--keyfile', dest="keyfile", default=None, help="File with which to XOR") 31 | parser.add_argument('--offset',dest="offset", default=0,type=int, help="Offset in file from which XOR should start") 32 | args = parser.parse_args() 33 | 34 | 35 | data = bytearray(open(args.file, 'rb').read()) 36 | if (args.key == None and args.keyfile == None): 37 | print("Supply key or keyfile") 38 | exit (-1) 39 | if args.keyfile: 40 | key = bytearray(open(args.keyfile, 'rb').read()) 41 | else: 42 | key = bytearray(args.key, 'utf-8') 43 | offset = args.offset 44 | 45 | decdata = decode(data, key, offset) 46 | save_decoded(decdata, args.outfile) 47 | 48 | print("Saved to: "+ args.outfile) 49 | 50 | 51 | if __name__ == "__main__": 52 | main() 53 | 54 | -------------------------------------------------------------------------------- /file2png.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """file2png.py: Visualise raw bytes of any given file and saves as a PNG""" 3 | 4 | __author__ = 'hasherezade' 5 | __license__ = "GPL" 6 | 7 | import sys 8 | import os 9 | import math 10 | import argparse 11 | from PIL import Image 12 | 13 | def getfilebytes(filename,offset=0): 14 | """ 15 | Get bytes from source file 16 | """ 17 | fo = open(filename,"rb") 18 | fo.seek(offset,0) #seek from current file position 19 | data = fo.read() 20 | fo.close() 21 | return (len(data),data) 22 | 23 | def get_raw_bytes(filename): 24 | filesize = os.path.getsize(filename) 25 | (bytesread,rawbytes) = getfilebytes(filename) 26 | return rawbytes 27 | 28 | ### 29 | 30 | class ImageBuffer: 31 | #private 32 | def _calcDimensions(self, size): 33 | #calculate pixel dimensiong for a square image 34 | unit = 3 #RGB 35 | pixelsCount = len(self.encbytes)/unit 36 | if self.w is None: 37 | self.w = int(math.ceil(math.sqrt(pixelsCount))) 38 | self.h = self.w #sqare 39 | else: 40 | self.h = pixelsCount / self.w 41 | self.padding = int(((self.w * self.h) * unit) - size) 42 | 43 | def _appendPadding(self, stuffing): 44 | stuffingSize = len(stuffing) 45 | stuffingUnits = self.padding / stuffingSize 46 | stuffingRem = self.padding % stuffingSize 47 | print("Dif = %d, stuffing size = %d * %d + %d" % (self.padding, stuffingSize, stuffingUnits, stuffingRem)) 48 | if self.padding == 0: 49 | return 50 | i = 0 51 | totalStuffingSize = stuffingUnits * stuffingSize 52 | while totalStuffingSize: 53 | self.encbytes += stuffing.encode('utf-8') 54 | totalStuffingSize = totalStuffingSize - 1 55 | if stuffingRem == 0: 56 | return 57 | stuffing = stuffing[:stuffingRem] 58 | self.encbytes += stuffing 59 | 60 | #public 61 | 62 | def __init__(self, rawbytes, width=None): 63 | self.encbytes = rawbytes 64 | self.w = width 65 | self._calcDimensions(len(rawbytes)) 66 | self.printInfo() 67 | self._appendPadding('\0') 68 | 69 | def printInfo(self): 70 | print("width: " + str(self.w)) 71 | print("height: " + str(self.h)) 72 | print("Padding: " + str(self.padding)) 73 | print("Finalsize: " + str(len(self.encbytes))) 74 | 75 | ### 76 | 77 | def encode(rawbytes): 78 | return rawbytes 79 | 80 | def decode(encbytes): 81 | return encbytes 82 | 83 | ### 84 | 85 | def save_image(imgBuffer, filename): 86 | imc = Image.frombuffer("RGB", (imgBuffer.w, imgBuffer.h), imgBuffer.encbytes,"raw","RGB",0,1) 87 | imc.save(filename) 88 | 89 | def get_encoded_data(imgname): 90 | imo = Image.open(imgname) 91 | rawdata = list(imo.getdata()) 92 | print("Len = %d\n" % len(rawdata)) 93 | tsdata = "" 94 | for x in rawdata: 95 | for z in x: 96 | tsdata += chr(z) 97 | del rawdata 98 | return tsdata 99 | 100 | def save_decoded(decdata, outfile): 101 | fr = open(outfile, "wb") 102 | if fr is None: 103 | return False 104 | fr.write(decdata.encode()) 105 | fr.close() 106 | return True 107 | 108 | def make_prefixed_name(filename, prefix): 109 | basename = os.path.basename(filename) 110 | dirname = os.path.dirname(filename) 111 | 112 | basename = prefix + basename 113 | out_name = os.path.join(dirname, basename) 114 | print(out_name) 115 | return out_name 116 | 117 | def make_outfile_name(filename, suffix, prefix): 118 | filename = make_prefixed_name(filename, prefix) + "."+ suffix 119 | print("out_name: " + filename) 120 | return filename 121 | 122 | def main(): 123 | parser = argparse.ArgumentParser(description="Bytes visualiser") 124 | parser.add_argument('--infile', dest="infile", default=None, help="Input file", required=True) 125 | parser.add_argument('--outfile', dest="outfile", default=None, help="Output file") 126 | parser.add_argument('--decode', dest="decode", default=False, help="Decode the given file?", action='store_true') 127 | parser.add_argument('--width', dest="width", default=None, help="Preffered width of the output image", type=int) 128 | args = parser.parse_args() 129 | 130 | filename = args.infile 131 | outfile = args.outfile 132 | prefix = "enc_" 133 | sufix = "png" 134 | if args.decode: 135 | prefix = "dec_" 136 | sufix = "out" 137 | 138 | if outfile is None: 139 | outfile = make_outfile_name(filename, sufix, prefix) 140 | 141 | print("Input: " + filename) 142 | print("Output: " + outfile) 143 | 144 | if args.decode == False: 145 | rawbytes = get_raw_bytes(filename) 146 | encodedbytes = encode(rawbytes) 147 | del rawbytes 148 | imagebuffer = ImageBuffer(encodedbytes, args.width) 149 | save_image(imagebuffer, outfile) 150 | else: 151 | tsdata = get_encoded_data(filename) 152 | decdata = decode(tsdata) 153 | print("[+] Decoded: %d bytes" % len(decdata)) 154 | if save_decoded(decdata, outfile): 155 | print("[+] Saved to: " + outfile) 156 | else: 157 | print("[-] Error: cannot write to file: " + outfile) 158 | 159 | if __name__ == "__main__": 160 | main() 161 | 162 | -------------------------------------------------------------------------------- /morse/main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | "Morse encoder/decoder with option of custom charset, CC-BY: hasherezade" 3 | 4 | import argparse 5 | from morse import * 6 | 7 | def main(): 8 | parser = argparse.ArgumentParser(description="Morse Encoder/Decoder") 9 | parser.add_argument('--charset', dest="charset", default='.- ', help="Charset in format: 'DitDashBreak', i.e '.- '") 10 | parser.add_argument('--decode', dest="decode", default=False, action='store_true', help="Decode or encode the given input?") 11 | args = parser.parse_args() 12 | 13 | m = Morse(args.charset) 14 | 15 | print "Enter a message:" 16 | raw = raw_input() 17 | 18 | if args.decode: 19 | print m.morse_dec(raw) 20 | else: 21 | print m.morse_enc(raw) 22 | 23 | if __name__ == "__main__": 24 | main() 25 | -------------------------------------------------------------------------------- /morse/morse.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | "Morse encoder/decoder with option of custom charset, CC-BY: hasherezade" 3 | 4 | class Morse: 5 | #private: 6 | morse_map = { '01':'a', '1000':'b', '1010':'c', '100':'d', '0':'e', '0010':'f', '110':'g', '0000':'h', 7 | '00':'i','0111':'j','101':'k','0100':'l','11':'m','10':'n', '111':'o', '0110':'p', 8 | '1101':'q', '010':'r', '000':'s', '1':'t', '001':'u', '0001':'v', '011':'w','1001':'x', 9 | '1011':'y','1100':'z', 10 | '01111':'1', '00111':'2', '00011':'3', '00001':'4', '00000':'5', '10000':'6', '11000':'7', '11100':'8', '11110':'9', '11111':'0', } 11 | 12 | BREAK_INDEX = 2 13 | 14 | def _makeReverseMap(self, inmap): 15 | outmap = {} 16 | for key in inmap.keys(): 17 | val = inmap[key] 18 | outmap[val] = key 19 | return outmap 20 | 21 | def _mapInput(self, chunks, inmap): 22 | output = list() 23 | for chunk in chunks: 24 | if chunk in inmap.keys(): 25 | output.append(inmap[chunk]) 26 | return output 27 | 28 | def _splitchunk(self, string): 29 | splited = string.split(self.breakchar) 30 | return splited 31 | 32 | def _rawToCharset(self, chunk): 33 | if self.charset == None: 34 | return chunk 35 | outchunk = "" 36 | for c in chunk: 37 | num = ord(c) - ord('0') 38 | outchunk += self.charset[num] 39 | return outchunk 40 | 41 | def _charsetToRaw(self, chunk): 42 | if self.charset == None: 43 | return chunk 44 | outchunk = "" 45 | for c in chunk: 46 | index = self.charset.index(c) 47 | val = chr(index + ord('0')) 48 | outchunk += val 49 | return outchunk 50 | 51 | def _setCharset(self, chunks): 52 | out2 = list() 53 | for chunk in chunks: 54 | out2.append(self._rawToCharset(chunk)) 55 | return out2 56 | 57 | def _unsetCharset(self, chunks): 58 | out2 = list() 59 | for chunk in chunks: 60 | out2.append(self._charsetToRaw(chunk)) 61 | return out2 62 | 63 | #public: 64 | def __init__( self, charset): 65 | self.rev_map = self._makeReverseMap(self.morse_map) 66 | self.charset = '.- ' 67 | if charset: 68 | self.charset = charset 69 | self.breakchar = self.charset[self.BREAK_INDEX] 70 | 71 | def morse_dec(self, string): 72 | chunks = self._splitchunk(string) 73 | chunks = self._unsetCharset(chunks) 74 | output = self._mapInput(chunks, self.morse_map) 75 | return "".join(output) 76 | 77 | def morse_enc(self, string): 78 | string = string.lower() 79 | output = self._mapInput(string, self.rev_map) 80 | out2 = self._setCharset(output) 81 | return self.breakchar.join(out2) 82 | 83 | 84 | -------------------------------------------------------------------------------- /quick_aes/README.md: -------------------------------------------------------------------------------- 1 | quick_aes 2 | --- 3 | 4 | This tiny utility is meant to provide fast AES encryption of strings and files. 5 | It can be used in cases when you don't want to send message via open text but you have no time to prepare more sophiasticated encryption methods (GPG etc). 6 | 7 | How to use: 8 | - 9 | 1) To encrypt a message: 10 | 11 |
12 | ./quick_aes.py 
13 | Password: 
14 | Enter a message:
15 | This is my test message that is going to be encrypted and saved in Base64!
16 | ---
17 | CivtrN5BtxgHcFzDHx2Eqn/W48Wp4dobb75dXt9nC+2zfqIKdyzYG6uSCXyxOeV2rAoy2kjhkKCjFgBKAkI6yXgAb6VCWOY+4pgHt/+7ucH9EWY2hY7YeHNdUKvSplQn
18 | ---
19 | 
20 | Now you can copy the Base64 text, paste it and send wherever you like. 21 | 22 | 2) To decrypt a message:
23 | use a parameter --decode and paste the encrypted text in Base64 24 |
25 | ./quick_aes.py --decode
26 | Password: 
27 | Enter a message:
28 | CivtrN5BtxgHcFzDHx2Eqn/W48Wp4dobb75dXt9nC+2zfqIKdyzYG6uSCXyxOeV2rAoy2kjhkKCjFgBKAkI6yXgAb6VCWOY+4pgHt/+7ucH9EWY2hY7YeHNdUKvSplQn
29 | ---
30 | This is my test message that is going to be encrypted and saved in Base64!
31 | ---
32 | 
33 | 3) To encrypt a file
34 | Use a parameter --infile [filename] 35 |
36 | ./quick_aes.py --infile file2png.py 
37 | Password: 
38 | [OK] Output: enc_file2png.txt
39 | 
40 | 4) To decrypt a file:
41 | Use a parameters --infile [filename] --decode --oext [output_extension] 42 |
43 | ./quick_aes.py --infile enc_file2png.txt --decode --oext py
44 | Password: 
45 | [OK] Output: dec_enc_file2png.py
46 | 
47 | 48 | -------------------------------------------------------------------------------- /quick_aes/quick_aes.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python2.7 2 | 3 | import sys 4 | import os 5 | import argparse 6 | import base64 7 | import hashlib 8 | import getpass 9 | from Crypto.Cipher import AES 10 | from Crypto import Random 11 | 12 | BS = 16 13 | pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS) 14 | unpad = lambda s : s[:-ord(s[len(s)-1:])] 15 | 16 | class AESCipher: 17 | def __init__( self, key ): 18 | self.key = key 19 | 20 | def encrypt( self, raw ): 21 | raw = pad(raw) 22 | iv = Random.new().read( AES.block_size ) 23 | cipher = AES.new( self.key, AES.MODE_CBC, iv ) 24 | return base64.b64encode( iv + cipher.encrypt( raw ) ) 25 | 26 | def decrypt( self, enc ): 27 | enc = base64.b64decode(enc) 28 | iv = enc[:BS] 29 | cipher = AES.new(self.key, AES.MODE_CBC, iv ) 30 | return unpad(cipher.decrypt( enc[BS:] )) 31 | ### 32 | 33 | def scramble(key): 34 | md_str = hashlib.sha512(key).hexdigest() 35 | salt = hashlib.sha512(key[::-1]).hexdigest() 36 | 37 | key2 = str_to_bytesstr(md_str) 38 | key3 = str_to_bytesstr(key) 39 | extended_key = key2 + key3 40 | 41 | m = hashlib.pbkdf2_hmac('sha512', bytearray(extended_key), salt, 100000) 42 | start = 2 43 | key_len = 32 44 | result = m[start : (start + key_len)] 45 | return result 46 | 47 | def str_to_bytesstr(string): 48 | bytes = list() 49 | for c in string: 50 | bytes.append(ord(c)) 51 | return "".join("%02x" % b for b in bytes) 52 | 53 | ### 54 | 55 | def get_raw_bytes(filename, offset=0): 56 | fo = open(filename,"rb") 57 | fo.seek(offset, 0) 58 | data = fo.read() 59 | fo.close() 60 | return data 61 | 62 | def save_raw_bytes(filename, data): 63 | fo = open(filename,"wb") 64 | fo.write(data) 65 | fo.close() 66 | 67 | def make_outfile_name(filename, isDecode, suffix): 68 | basename = os.path.basename(filename) 69 | dirname = os.path.dirname(filename) 70 | prefix = "enc_" 71 | if isDecode: 72 | prefix = "dec_" 73 | basename = prefix + basename 74 | if suffix : 75 | if not suffix.startswith('.'): 76 | suffix = "." + suffix 77 | basename = basename + suffix 78 | out_name = os.path.join(dirname, basename) 79 | return out_name 80 | 81 | def main(): 82 | parser = argparse.ArgumentParser(description="AES Encoder/Decoder") 83 | parser.add_argument('--infile', dest="infile", default=None, help="Input file") 84 | parser.add_argument('--oext', dest="out_ext", default=None, help="Output extension") 85 | parser.add_argument('--decode', dest="decode", default=False, action='store_true', help="Decode or encode the given input?") 86 | args = parser.parse_args() 87 | 88 | key = getpass.getpass() 89 | key = scramble(key) 90 | 91 | if args.infile is None: 92 | #read message from stdin: 93 | outfile = None 94 | print "Enter a message:" 95 | raw = raw_input() 96 | else: 97 | filename = args.infile 98 | #prepare output name: 99 | if args.decode: 100 | if args.out_ext is None: 101 | print "Output extension is required!" 102 | return 103 | outfile = make_outfile_name(filename, args.decode, args.out_ext) 104 | else: 105 | outfile = make_outfile_name(filename, args.decode, "txt") 106 | raw = get_raw_bytes(filename) 107 | 108 | aes = AESCipher(key) 109 | if args.decode: 110 | output = aes.decrypt(raw) 111 | else: 112 | output = aes.encrypt(raw) 113 | if outfile: 114 | save_raw_bytes(outfile, output) 115 | print "[OK] Output: " + outfile 116 | else: 117 | print "---" 118 | print output 119 | print "---" 120 | 121 | if __name__ == "__main__": 122 | main() 123 | 124 | -------------------------------------------------------------------------------- /rc4.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python2.7 2 | import sys 3 | import os 4 | import argparse 5 | 6 | def RC4(key, data): 7 | S = range(256) 8 | j = 0 9 | out = bytearray() 10 | 11 | #KSA Phase 12 | for i in range(256): 13 | j = (j + S[i] + ord( key[i % len(key)] )) % 256 14 | S[i] , S[j] = S[j] , S[i] 15 | 16 | #PRGA Phase 17 | i = j = 0 18 | for char in data: 19 | i = ( i + 1 ) % 256 20 | j = ( j + S[i] ) % 256 21 | S[i] , S[j] = S[j] , S[i] 22 | out.append(chr(ord(char) ^ S[(S[i] + S[j]) % 256])) 23 | return out 24 | 25 | def get_raw_bytes(filename, offset=0): 26 | fo = open(filename,"rb") 27 | fo.seek(offset, 0) 28 | data = fo.read() 29 | fo.close() 30 | return data 31 | 32 | def save_raw_bytes(filename, data): 33 | fo = open(filename,"wb") 34 | fo.write(data) 35 | fo.close() 36 | 37 | def main(): 38 | parser = argparse.ArgumentParser(description="RC4 Encoder/Decoder") 39 | parser.add_argument('--infile', dest="infile", default=None, help="Input file") 40 | parser.add_argument('--outfile', dest="outfile", default="out.tmp", help="Output file") 41 | parser.add_argument('--key', dest="key", default="test", help="Key") 42 | args = parser.parse_args() 43 | 44 | key = args.key 45 | raw = None 46 | 47 | if args.infile is None: 48 | #read message from stdin: 49 | print "Enter a message:" 50 | raw = raw_input() 51 | else: 52 | filename = args.infile 53 | raw = get_raw_bytes(filename) 54 | print "Data length: ", len(raw) 55 | 56 | output = RC4(key, raw) 57 | 58 | save_raw_bytes(args.outfile, output) 59 | print "Output saved to: " + args.outfile 60 | 61 | if __name__ == "__main__": 62 | main() 63 | 64 | --------------------------------------------------------------------------------