Menu

Crypto

October 11, 2016 - Crypto, python
from Crypto.Cipher import AES
from Crypto.Cipher import XOR
from Crypto.Hash import SHA256
from Crypto.Hash import MD5

import base64
import os

# SHA - returns a string 64 chars
print "SHA: " + SHA256.new('mep').hexdigest()
# ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad

# FILE MD5
def get_file_checksum(filename):
    h = MD5.new()
    chunk_size = 8192
    with open(filename, 'rb') as f:
        while True:
            chunk = f.read(chunk_size)
            if len(chunk) == 0:
                break
            h.update(chunk)
    return h.hexdigest()

print 'MD5: ' + get_file_checksum("char1.txt")

## AES
msg_text = '26cb20dfb5cb1c68413389bbbe7fead5'.rjust(32)
secret_key = '6d616a610c0c0c0c0c0c0c0c0c0c0c0c' 

cipher = AES.new(secret_key,AES.MODE_ECB)
encoded = base64.b64encode(cipher.encrypt(msg_text))
decoded = cipher.decrypt(base64.b64decode(encoded))

print "AES - decoded: " + decoded.strip()
print "AES - ENCRYPT: " +cipher.encrypt(msg_text)


## XOR of ciphers

c1 = '6f7bcef0dd3299ce4d26de3333e389e4'
c2 = '10800d42f36793d76dbc9541ce5b75f6'
cX = '7ffbc3b22e550a19209a4b72fdb8fc12'

def xor_strings(xs, ys):
    xs = xs.decode("hex")   # Decode both strings to hex
    ys = ys.decode("hex")
    return "".join(chr(ord(x) ^ ord(y)) for x, y in zip(xs, ys))

xored = xor_strings(c1, c2).encode("hex")
print "XOR: " + xored  # 7ffbc3b22e550a19209a4b72fdb8fc12

p1 = '6e616d650c0c0c0c0c0c0c0c0c0c0c0c'
p2 = '6a6f6b650c0c0c0c0c0c0c0c0c0c0c0c'
pX = '40e0600000000000000000000000000'

# XORs two string
def strxor(a, b):     # xor two strings (trims the longer input)
    return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a, b)])

'''
XOR EXPLANATION
=================================================================
Plain Text1: 0001011    Plain Text2: 0110011
Key        : 1010110    Key        : 1010110
Ciphertext : 1011101    Ciphertext : 1100101

XOR of ciphertexts  XOR of plaintexts (which of course match)
1011101         0001011
1100101         0110011
0111000         0111000
'''