예제 #1
0
파일: servidor.py 프로젝트: fealuin/sha1
def handleHashClaveSimetrica():
	hn=connection.recv(1024)
	print 'Se ha recibido el mensaje %s, el texto es %s y el hash %s'%(hn,hn[:-48],hn[-48:])
	k=getClave()
	hh=sha1.sha1(hn[:-48])
	print hh,len(hh)
	dhh=(aes.aes('d',hn[-48:],k))[:40]
	print 'Al desenciptar %s se obtiene %s'%(hn[-48:],dhh)
	print 'Al calcular el hash sha1 del texto \"%s\" se obtiene: %s que'%(hn[:-48],hh)+' ' if hh==dhh else ' no ', 'coincide'
예제 #2
0
파일: cliente.py 프로젝트: fealuin/sha1
def hashClaveSimetrica():
    sock.sendall('hcs')
    msg=getMsg()
    k=getClave()
    ha=sha1.sha1(msg)
    h=aes.aes('e',ha,k)#+aes.encriptarAes(ha[32:48],k)
    print 'largo hash Encriptado %d'%len(h)
    msg=msg+h
    sock.sendall(msg)
    return 0
예제 #3
0
def get(index):

    hashez = re.findall(r'"(\w+)"', index)

    a = toNumbers(hashez[0])
    b = toNumbers(hashez[1])
    c = toNumbers(hashez[2])

    cookie_value = toHex(aes().decrypt(c, 2, a, b))

    return cookie_value
예제 #4
0
def make_auth(pid=0, as_server=False, timestamp=0):
    """ Assemble authentication token. """
    data = ['\x00'] * 16

    if not timestamp:
        timestamp = int(time())
    data[:4] = pack('L', timestamp)

    # 'magic number' 64 00 00 00
    data[4] = 'd'

    data[8:12] = pack('L', pid)

    if as_server:
        data[12] = 1

    dc = crc(data[:14])
    try:
        data[14:16] = pack('H', dc)
    except:
        print hex(dc)

    return base64(aes(data))
예제 #5
0
import random
import aes


def gen_rand_slice():
    return [random.randint(0, 255) for j in range(0, 4)]


def print_slice(aes, slice):
    print "%s " % aes.hex_slice_to_str(slice),
    x = e.mixmul(slice)
    print "%s " % aes.hex_slice_to_str(x),
    print


e = aes.aes()

zeros = [0 for j in range(0, 4)]
print_slice(e, zeros)

ones = [0x01 for j in range(0, 4)]
print_slice(e, ones)

increasing = [0xdb, 0x13, 0x53, 0x45]
print_slice(e, increasing)

total = 1024

for i in range(0, total):
    key = gen_rand_slice()
    print_slice(e, key)
예제 #6
0
 def __init__(self, key):
     if (len(key)) != self.BYTE:
         print("Key Length Error: Must be 16 Bytes Long")
         exit(1)
     self.key = key
     self.AES = aes(key)
예제 #7
0
        else:
            break

this_child_start_time = time.time()

# Check if any other wraiths are active. If so, die. If not, bind
# to socket to tell all other wraiths we're active.
single_instance_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
    single_instance_socket.bind(("localhost", NON_DUPLICATE_CHECK_PORT))
    if DEBUG_MODE: print("Single instance check passed, starting")
except:
    if DEBUG_MODE: print("Single instance check failed, exiting")
    sys.exit(0)

aes = aes()


class Wraith():
    def __init__(self, api_url, CRYPT_KEY, crypt_obj):
        self.id = None  # Will be replaced with server-assigned UUID on login
        self.api_url = api_url  # Create a local copy of the API url
        self.CRYPT_KEY = CRYPT_KEY  # Create a local copy of the encryption key
        self.crypt = crypt_obj  # Create a local copy of the encryption object
        self.command_queue = []  # Create a queue of all the commands to run

    # Make requests to the api and return responses
    def api(self, data_dict):
        # If we are meant to log interactions, log (debug)
        if DEBUG_MODE: print(f"\n[CLIENT]:\n{json.dumps(data_dict)}\n")
        # Create the encrypted data string
예제 #8
0
파일: colors.py 프로젝트: bnmnetp/ggplot
                color = color_gen(gg.manual_color_list)
            else:
                color = color_gen()
            possible_colors = np.unique(gg.data[color_col])
            if sys.hexversion > 0x03000000:
                color_mapping = {value: color.__next__() for value in possible_colors}
            else:
                color_mapping = {value: color.next() for value in possible_colors}
            gg.data["color_mapping"] = gg.data[color_col].apply(lambda x: color_mapping[x])
            gg.legend["color"] = { v: k for k, v in color_mapping.items() }

    return gg


if __name__ == '__main__':
    import pandas as pd
    from aes import aes
    from ggplot import ggplot

    df = pd.DataFrame({
        "x": ["a", "b", "c"] + ["a", "b", "c"],
        "y": [1, 2, 3] + [1, 2, 3],
        "z": [4, 5, 6] + [4, 5, 6]
    })

    gg = ggplot(df, aes(x="x", y="y", color="y"))
    gg.manual_color_list = None
    gg = assign_colors(gg)
    print gg.data
    print gg.legend
예제 #9
0
 def __init__(self, path, key, iv):
     super(ConfAESCache, self).__init__(path)
     self._aes = aes.aes(key, iv)
     data = super(ConfAESCache, self).read()
     self.__dict__['__data__'] = {} if data is None else data
예제 #10
0
 def __init__(self, path, key, iv):
     super(AESCache, self).__init__(path)
     self._aes = aes.aes(key, iv)
예제 #11
0
def dec_aes_pcbc(crypted, salt, passphrase, keylen=32):
    key, iv = passphrase_to_salted_key_and_iv(passphrase, salt, keylen, 16)
    return pkcs7_unpad(dec_pcbc(aes(key), iv)(crypted))
예제 #12
0
def main():
    description = """
   Custom AES implementation using python. By deault it will encrypt/decrypt 
   text using 128-bit key size. 
   """
    parse = argparse.ArgumentParser(description=description)
    parse.add_argument("ifile",
                       metavar="IN_FILE",
                       type=str,
                       help="The file to encrypt/decrypt")
    parse.add_argument("ofile",
                       metavar="OUT_FILE",
                       type=str,
                       help="Output file")
    parse.add_argument("key",
                       metavar="KEY",
                       type=str,
                       help="encryption/decryption key")
    parse.add_argument("-d",
                       "--decrypt",
                       action="store_true",
                       help="Decrypts the output")
    parse.add_argument("-v",
                       "--verbose",
                       action="store_true",
                       help="Show me that verbosity")
    parse.add_argument("-k",
                       metavar="--key_size",
                       type=str,
                       help="Set the encryption key to 128, 192 or 256 bits")
    parse.add_argument("-l",
                       "--loop",
                       action="store_true",
                       help="Encryps then decrypts and the print both console")
    args = parse.parse_args()

    BLOCK_SIZE = 16
    array = [4, 6]
    NK = 4
    ENCRYPT = True
    DECRYPT = False

    fd_in, fd_out = None, None

    try:
        fd_in = open(args.ifile, "rb")
        fd_out = open(args.ofile, "wb")

    except IOError:
        print "[!] Cannot open {}".format(args.ifile)
        exit(0)

    # Gets the key ready
    round_keys = key_expansion(args.key, NK)

    # Decrypt
    if args.decrypt == True:
        plain_text = fd_in.read()
        cypher_text = aes(plain_text, round_keys)
        fd_out.write(bytearray(cypher_text))

        fd_in.close()
        fd_out.close()

    # Encrypt
    else:
        cypher_text = fd_in.read()
        plain_text = aes(cypher_text, round_keys, DECRYPT)
        fd_out.write(bytearray(plain_text))

        fd_in.close()
        fd_out.close()
예제 #13
0
파일: main.py 프로젝트: jtylers/tools
# TODO split messages larger than nb * nk into segments
message = str.encode("Hello World!")  # Turn the message into a matrix
# message = str.encode(input('Message to Encode: '))
bytes_in_word = int(32 / 8)

# if verbose:
#    print("deciphered text:")
#    print(aes.genText(undo, nb, nk))

# Message to be used for passoff
message = bytes([0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff])
state = aes.genMatrix(message, nb, bytes_in_word)

# run the tests for nk = 4
nk = 4
nk_4 = aes.aes(cipher_key, nb, nk)  # Initialise aes class
cipher_text = nk_4.cipher(state)
nk_4.invCipher(cipher_text)

# run the tests for nk = 6
nk = 6
nk_6 = aes.aes(cipher_key, nb, nk)  # Initialise aes class
cipher_text = nk_6.cipher(state)
nk_6.invCipher(cipher_text)

# run the tests for nk = 8
nk = 8
nk_8 = aes.aes(cipher_key, nb, nk)  # Initialise aes class
cipher_text = nk_8.cipher(state)
nk_8.invCipher(cipher_text)
예제 #14
0
파일: dfa1.py 프로젝트: arnaudMDM/aes
    point = sbox[point / 16][point % 16]
    return point

def unshiftRows(tab):
    for i in range(4):
        for j in range(i):
            tab[i].insert(0, tab[i].pop(3))
    return tab

byte = random.randrange(16)
text = [[0x32,0x88,0x31,0xe0],[0x43,0x5a,0x31,0x37],[0xf6,0x30,0x98,0x07],[0xa8,0x8d,0xa2,0x34]]
key = [[0x2b,0x28,0xab,0x09],[0x7e,0xae,0xf7,0xcf],[0x15,0xd2,0x15,0x4f],[0x16,0xa6,0x88,0x3c]]

d = []
for i in range(ITERATION):
    d.append(aes(copy.deepcopy(text), copy.deepcopy(key), 1, byte))
c = aes(text, key)

xor = [[[c[i][j] ^ d[l][i][j] for j in range(4)] for i in range(4)] for l in range(ITERATION)]

xor = filter(lambda x: x != 0, reduce(lambda a,b: a + b, reduce(lambda a,b: a + b, xor)))

possible = []
for k in range(ITERATION):
    possible.append([[],[]])
    for i in range(8):
        for j in range(256):
            correctM = j
            faultM = j ^ 2**i# ~(j & 2**i) & (j | 2**i)
            if (subytesPoint(correctM) ^ subytesPoint(faultM)) == xor[k]:
                possible[k][0].append(correctM)
예제 #15
0
 def __init__(self):
     self.CIPHER = aes.aes(256)
예제 #16
0
def gen_rand_block():
   return   [
               [random.randint(0, 255) for j in range(0, 4)]
               for i in range(0, 4)
            ]
               


def print_block(aes, block):
   print "%s " % aes.hex_to_str(block),
   x = e.shiftrows(block)
   print "%s " % aes.hex_to_str(x),
   print

e = aes.aes()

zeros = [[0 for j in range(0, 4)] for i in range(0, 4)]
print_block(e, zeros)

ones = [[0xFF for j in range(0, 4)] for i in range(0, 4)]
print_block(e, ones)

increasing = [[4*j+i for j in range(0, 4)] for i in range(0, 4)]
print_block(e, increasing)


total = 1024

for i in range(0, total):
   key = gen_rand_block()
예제 #17
0
def enc_aes_pcbc(text, salt, passphrase, keylen=32):
    key, iv = passphrase_to_salted_key_and_iv(passphrase, salt, keylen, 16)
    return enc_pcbc(aes(key), iv)(pkcs7_pad(text))