Esempio n. 1
0
 def encrypt(self, raw):
     iv = bytearray(os.urandom(16))
     cipher = aes.AES(mode='cbc', key=self.key, iv=iv)
     # for when raw is an bytes object and not an str object.
     if isinstance(raw, str):
         data = bytearray(raw.encode('ascii'))
     else:
         data = bytearray(raw)
     while (len(data) / 16) % 1 != 0:
         data.append(0x00)
     cipher.encrypt(data)
     return bytes(iv + data)
Esempio n. 2
0
def main(encrypt, input_file, output_file, block_cipher_mode, key_length):

    if encrypt:

        key = aes.random_key_generator(int(key_length))

        if key_length == "128":
            AES = aes.AES(key, 128)

        elif key_length == "192":
            AES = aes.AES(key, 192)

        elif key_length == "256":
            AES = aes.AES(key, 256)

        if block_cipher_mode == "ECB":
            bcm = aes.ECB(AES)

        elif block_cipher_mode == "CBC":
            bcm = aes.CBC(AES, 16)

        elif block_cipher_mode == "CTR":
            bcm = aes.CTR(AES)

        bcm.cipher(input_file, output_file)
        print("Cipher Key:", key)
        write_key(key)

    else:
        key = read_key()
        if key == 1:
            print("File key.txt doesn't exists! Can't decrypt without key")
            exit(1)

        key_length = len(key) * 4

        if key_length == 128:
            AES = aes.AES(key, 128)

        elif key_length == 192:
            AES = aes.AES(key, 192)

        elif key_length == 256:
            AES = aes.AES(key, 256)

        else:
            print("Key length not valid!")
            exit(1)

        if block_cipher_mode == "ECB":
            bcm = aes.ECB(AES)

        elif block_cipher_mode == "CBC":
            bcm = aes.CBC(AES, 16)

        elif block_cipher_mode == "CTR":
            bcm = aes.CTR(AES)

        bcm.decipher(input_file, output_file)
Esempio n. 3
0
def test_AES():
    # INIT KEYS AND PLAINTEXT

    key1 = np.array([[GF2int(randint(0, 255)) for i in range(4)]
                     for j in range(4)],
                    dtype=GF2int)
    key2 = np.array([[GF2int(randint(0, 255)) for i in range(4)]
                     for j in range(4)],
                    dtype=GF2int)
    key3 = np.array([[GF2int(randint(0, 255)) for i in range(4)]
                     for j in range(4)],
                    dtype=GF2int)

    key1 = "".join(format(y, '02x') for x in key1 for y in x)
    key2 = "".join(format(y, '02x') for x in key2 for y in x)
    key3 = "".join(format(y, '02x') for x in key3 for y in x)

    key_cipher = np.array([[GF2int(0) for i in range(4)] for j in range(4)],
                          dtype=GF2int)
    plain_text = np.array([[GF2int(0) for i in range(4)] for j in range(4)],
                          dtype=GF2int)

    plain_text_str = "".join(format(y, '02x') for x in plain_text for y in x)
    key_cipher_str = "".join(format(y, '02x') for x in key_cipher for y in x)

    aes_ref = AES.new(key_cipher_str)
    cipher_ref_str = aes_ref.encrypt(plain_text_str).encode("hex")
    W = aes.ExpandRoundKey(key_cipher)
    master = Master(key_cipher, 4)
    keys = [key1, key2, key3]
    sub = SubCircuit(
        np.array([
            MiniCircuit(keys[s % 3], keys[(s + 1) % 3], W) for s in range(3)
        ]))

    randomness = sub.getCorrRandom()
    shares = [Secret(), Secret(), Secret()]
    for s in range(0, 3):
        shares[s].alpha = randomness[s]
        shares[s].x = plain_text + randomness[(s - 1) % 3]
    W = aes.ExpandRoundKey(key_cipher)
    sub.initShares(shares)
    sub.AES()

    shared = master.reconstructShares(sub)

    state = aes.AES(key_cipher, plain_text)
    if (not np.array_equal(state, shared)):
        return 0
    else:
        return 1
Esempio n. 4
0
def check_secret_key(secret_key, triples):
    num_wrong = 0
    num_processed = 0
    aes_algo = aes.AES()
    for triple in triples:
        encrypted_form = aes_algo.encrypt(triple.plaintext, secret_key, 16)
        if encrypted_form != triple.ciphertext:
            num_wrong += 1
        num_processed += 1

        if num_processed % 10000 == 0:
            print "Processed: ", num_processed
            print "Percentage Incorrect: ", float(num_wrong) / num_processed

    print "Final Result: "
    print "Percentage Incorrect: ", float(num_wrong) / len(triples)
def test_position_of_bits_changed_M():
    aes = AES.AES(key)
    c = aes.encrypt_block(message)
    modifiedbits = [0] * 128
    sum = 0
    for i in range(128):
        modifiedMessage = int_to_bytes(bytes_to_int(message) ^ (1 << i), 16)
        ci = aes.encrypt_block(modifiedMessage)
        for j in range(128):
            bitc = (bytes_to_int(c) >> j) % 2
            bitci = (bytes_to_int(ci) >> j) % 2
            if (bitc != bitci):
                modifiedbits[j] += 1
                sum += 1
    print(modifiedbits)
    print("mean = ", sum / 128)
Esempio n. 6
0
def propagateChangesMessageNumBits():
    aesv = aes.AES(master_key)
    m = 0x1597C4EF331CC28B7E6D1B2EB3EA3B95
    c = aesv.encrypt(m)
    nchanges = []
    for i in range(128):
        mi = m ^ (1 << i)
        ci = aesv.encrypt(mi)
        nchanges.append(nDiffBits(c, ci))
    possibleNumberOfChanges = list(set(nchanges))
    fin = [possibleNumberOfChanges.index(i) for i in nchanges]
    plt.hist(fin, bins=range(len(possibleNumberOfChanges) + 1), align="left")
    plt.xticks(range(len(possibleNumberOfChanges)), possibleNumberOfChanges)
    plt.title("Number of total bits changed per modification histogram")
    plt.xlabel("Number of bits changed")
    plt.ylabel("Frecuency")
    plt.show()
Esempio n. 7
0
def propagateChangesMessagePositions():
    aesv = aes.AES(master_key)
    m = 0x1597C4EF331CC28B7E6D1B2EB3EA3B95
    c = aesv.encrypt(m)
    binc = asBinString(c)
    posChanging = {}
    for i in range(128):
        mi = m ^ (1 << i)
        ci = aesv.encrypt(mi)
        binci = asBinString(ci)
        pos = 0
        for bit in binci:
            if (bit != binc[pos]):
                if pos in posChanging:
                    posChanging[pos] += 1
                else:
                    posChanging[pos] = 1
            pos += 1
    width = 0.5
    plt.figure(figsize=(10, 12))
    plt.ylabel("Frecuency")
    plt.xlabel("Bins of positions changing")
    plt.bar(posChanging.keys(), posChanging.values(), width, color='g')
Esempio n. 8
0
def aes_ecb_decrypt(key, block):
    adjustment = aes.AES().decrypt(map(ord, block), map(ord, key), len(key))
    return ''.join(chr(x) for x in adjustment)
Esempio n. 9
0
def run_test(bit, test, order):
    directory = os.fsencode(source_dir)

    subprocess.run(['mkdir', target_1])
    subprocess.run(['mkdir', target_2])
    count = 0
    for file in os.listdir(directory):
        count += 1
        if (count % 1000 == 0):
            print("Processed", count, "files")


        filename = os.fsdecode(file)
        arr = filename.strip().split('_')
        # get the key, plaintext and ciphertext
        key = arr[5]
        pt = arr[6]
        ct = arr[7]
        key = key[2:]
        pt = pt[2:]
        ct = ct[2:34]
        #convert these to bytes objects
        key = bytes.fromhex(key)
        pt = bytes.fromhex(pt)
        ct = bytes.fromhex(ct)

        aes_obj = aes.AES(key)
        out, intermediate = aes_obj.decrypt_block(ct)
        if (out == pt):
            command = ["cp"]
            file_location = source_dir + filename
            #conditon
            v1 = intermediate[m]
            v2 = intermediate[m+1]
            v1_int = int(v1, 16)
            v2_int = int(v2, 16)
            v1 = format(v1_int, '0>128b')
            v2 = format(v2_int, '0>128b')

            # 5th round bth bit test
            if(bit < 128):
                v1_int = int(v1[bit])
                v2_int = int(v2[bit])

            if (test == 1):
                if (v1_int + v2_int == 1):
                    # XOR = 1
                    target_location = target_2
                else:
                    target_location = target_1
            elif (test == 2):
                if (v1_int == 0):
                    target_location = target_1

                else:
                    target_location = target_2

            elif (test == 3):
                b_str = v1[120:]
                b = int(b_str, 2)
                if (b == bit):
                    target_location = target_1
                else:
                    target_location = target_2

            elif (test == 4):
                b_str = v1[112:120]
                b = int(b_str, 2)
                if (b == bit):
                    target_location = target_1
                else:
                    target_location = target_2

            command.append(file_location)
            command.append(target_location)
            subprocess.run(command)
        else:
            print("Error in decryption")

    TVLA.run(target_1, target_2, str(bit)+"_"+str(test), order)

    subprocess.run(['rm', '-r', target_1])
    subprocess.run(['rm', '-r', target_2])
Esempio n. 10
0
#!/usr/bin/env python3
import aes


def conv_128to4w(text):
    w0 = text >> 96 & 0xffffffff
    w1 = text >> 64 & 0xffffffff
    w2 = text >> 32 & 0xffffffff
    w3 = text & 0xffffffff
    return (w0, w1, w2, w3)


my_aes = aes.AES()

# input the 128bit of block and key, then run the script.
# the last line will be the result
block_key1 = 0x51d0856638566c23c7c8113acc9711a9
block_text1 = 0x3c163add545c3aad3b8253efab2c9297
# ans1 : a8b06bd6b8798ae69e9c0b4a719ee7af

block_key2 = 0x239eb524e68c87be855fd15d99daea48
block_text2 = 0x0f8c0d86a5964f40f3525db4b9aa2eef
# ans2 : 37cb528d, 0x768ef263, 0xa28f9b9c, 0x1f1da371

block_key3 = 0x15094ed296002566211dbea2ea042d85
block_text3 = 0x90179c110a47eba744f9e4b0077fb5e0
# ans3 : 9e656eca, 0x9711c02b, 0x670aa95b, 0x896a3a17

block_key4 = 0x12bc7a427cf169be5bf920c475ceb9ed
block_text4 = 0xb78a114061bda1b670e985c4e4cf22c9
# ans4 : 0cd459f6, 0x7505547e, 0xbbbe8c27, 0xb1fa4a12
Esempio n. 11
0
import aes as AES
from helpers import bytes_to_int, int_to_bytes

key = b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
cipher = b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

aes = AES.AES(key)
message = aes.decrypt_block(cipher)
print(hex(bytes_to_int(message)))
Esempio n. 12
0
	Convert an array of hex, [0x6d, 0x69, 0x63] --> mic
	First it converts each element into binary of length 8 and then calling chr to convert to ascii
	Finally concats all and returns the string
	'''
	concat = map(lambda x:chr(int(bin(x)[2:].zfill(8), 2)), arr)
	return ''.join(concat)

message = "First it converts each element into binary of length 8 and then calling chr to convert to ascii"


#Turn the string length into a some multiple of 16
padding = 16-(len(message)%16)
factor16len = padding + len(message)
message = message.ljust(factor16len)

#Divide the message into blocks of 16 chars
messageblocks =  list(map(''.join, zip(*[iter(message)]*16)))
#messageblock = 'microprogramming'
for messageblock in messageblocks:
	print messageblock+"|"
	msg_hex =  map(lambda x: int(binascii.hexlify(x), 16), list(messageblock))
	cipher =  aes.AES(shared_key).encrypt(msg_hex)
	deciphered = aes.AES(shared_key).decrypt(cipher)
	print "messageblock:"+messageblock
	print "msg_hex:"+str(np.array(msg_hex))
	print "cipher:"+str(np.array(cipher)) 
	print "deciphered:"+str(np.array(deciphered))
	combined = convert2ascii(deciphered)
	print "final:"+combined

unittest.main()
Esempio n. 13
0
if __name__ == '__main__':
    test = PinServerClient()
    # Make ourselves a static key pair for this logical client
    priv_key, _, _ = test.file_static_client_keys()

    # The 'correct' client pin
    pin_secret = bytes(sha256(b'pippo'))

    # Make a new client and set the pin secret to get a new aes key
    aeskey_s = test.set_pin(priv_key, pin_secret, test.new_entropy())
    if not len(aeskey_s) == AES_KEY_LEN_256:
        print('dimension!')

    iv = priv_key[0:16]
    encrypted = aes.AES(aeskey_s).encrypt_ctr(b'Attack at dawn', iv)
    iv = priv_key[0:16]
    print(aes.AES(aeskey_s).decrypt_ctr(encrypted, iv))
    print('---')

    # Get key with a new client, with the correct pin secret (new entropy)
    for attempt in range(5):
        aeskey_g = test.get_pin(priv_key, pin_secret, test.new_entropy())
        if not compare_digest(aeskey_g, aeskey_s):
            print('compare_digest fails')
        iv = priv_key[0:16]
        print(aes.AES(aeskey_g).decrypt_ctr(encrypted, iv))

    # Get key with a new client, with the wrong pin secret (new entropy)
    pin_secret_wrong = bytes(sha256(b'pluto'))
    for attempt in range(5):
Esempio n. 14
0
 def setUp(self):
     self.aes = aes.AES()
Esempio n. 15
0
 def _blockciphers(self):
     a = aes.AES()
     a.set_keylen(32)
     return [a]
Esempio n. 16
0
# https://opensource.org/licenses/MIT.

import aes
import bachata
import hpolyc
import latindance
import adiantum
import nh
import nhpoly1305
import poly1305
import xconstruct

common_ciphers = [
    latindance.Salsa20(),
    xconstruct.XConstruct(latindance.Salsa20()),
    latindance.ChaCha(),
    latindance.ChaCha20RFC(),
    xconstruct.XConstruct(latindance.ChaCha()),
    poly1305.Poly1305(),
]

our_test_ciphers = common_ciphers + [
    hpolyc.HPolyC(),
    bachata.Bachata(),
    adiantum.Adiantum(),
    nh.NH(),
    nhpoly1305.NHPoly1305(),
]

all_ciphers = our_test_ciphers + [aes.AES()]
Esempio n. 17
0
parser.add_argument("output_file",
                    help="File to write output",
                    type=argparse.FileType('wb', 0))
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("-e",
                   "--encrypt",
                   action="store_true",
                   help="Encrypt input file")
group.add_argument("-d",
                   "--decrypt",
                   action="store_true",
                   help="Decrypt input file")
args = parser.parse_args()

key = bytes2int(args.key_file.read(16))
Aes = aes.AES(key)

if (args.encrypt):
    print "AES encrypting ..."
    action = lambda x: Aes.encrypt(x)
elif (args.decrypt):
    print "AES decrypting ..."
    action = lambda x: Aes.decrypt(x)
else:
    print "Wrong input arguments"
    sys.exit()

while (True):
    input_bytes = args.input_file.read(16)
    if (input_bytes == ''):
        break
Esempio n. 18
0
	def AES(self,plain_texts):
		self.plain_texts = plain_texts
		id = 0
		child_lst = []
		_lambda= len(self.subcircuits)

		for sub in self.subcircuits:
			newpid = os.fork()
			if newpid == 0: #child compute its shares
				random.seed(time.time())
				shares_pt = [] #Generate shares
				for plain_text in plain_texts:
					randomness = sub.getCorrRandom();
					shares = [Secret(),Secret(),Secret()]
					for s in range(0,3):
						shares[s].alpha = randomness[s]
						shares[s].x = plain_text + randomness[(s-1)%3]
					shares_pt.append(shares)

				sub.preloadShares(shares_pt)
				sub.run(self,id,id==0)
				os._exit(0)
			else:
				child_lst.append(newpid)
			id = id+1

		#parent child computes expected cipher
		expected_output = np.zeros(len(plain_texts)*16,dtype=int)
		for i,plain_text in enumerate(plain_texts):
			expected = aes.AES(self.key_cipher,plain_text)
			with open("expected.hex","a") as file:
				for j,x in enumerate(expected.reshape(16)):
					file.write("{:02X}".format(x)+"\n")
					expected_output[i*16 + j] = x

		for child in child_lst:
			pid, status = os.waitpid(child, 0)
			print("wait returned, pid = %d, status = %d" % (pid, status))

		## LOAD ALL FILES
		sub_index = np.array(range(_lambda),dtype=int)
		sub_outputs = np.zeros([_lambda,len(plain_texts)*16],dtype=int)
		stats = np.zeros([_lambda,2])

		for i in sub_index:
			with open("subcircuit%d.hex"%(i),'rb') as file:
				for j in range(len(plain_texts)*16):
					r = file.readline()
					sub_outputs[i,j] = int(r,16)

		for n_sub in range(_lambda):
			base = 0;

			while base < _lambda - (n_sub):
				sub_select = range(base,base+n_sub+1)
				if len(sub_select) != n_sub+1:
					continue

				result = 0

				rnd = randint(0,1)

				#Check the output of the master after majority vote
				for pl in range(len(plain_texts)*16):
					c = Counter(sub_outputs[sub_select,pl]).most_common()
					out_maj = c[0][0]
					unclear_maj = c[0][1] < ((n_sub+1)/2 +1)
					outputs_all = sub_outputs[sub_select,pl]

					if unclear_maj:
						arg = np.min([np.nonzero(outputs_all==c[0][0]),np.nonzero(outputs_all==c[1][0])])
						out_maj = outputs_all[arg]

					if(out_maj != expected_output[pl]):
						result = 1
						break

				for f in self.flags[sub_select]:
					if f!=0:
						result = 0

				stats[n_sub,0] = stats[n_sub,0] + 1
				stats[n_sub,1] = stats[n_sub,1] + result
				base = base + n_sub+1
		return stats