示例#1
0
文件: client.py 项目: Monica-y/Monica
def socket_client():
    serverName = '127.0.0.1'
    serverPort = 11000
    BUFSIZ = 1024
    ADDR = (serverName, serverPort)
    # 套接字家族可以使 AF_UNIX 或者 AF_INET。
    # 套接字类型可以根据是面向连接的还是非连接分为 SOCK_STREAM 或 SOCK_DGRAM。
    clientSocket = socket(AF_INET, SOCK_STREAM)
    # 主动初始化TCP服务器连接。
    # 一般address的格式为元组(hostname,port),如果连接出错,返回socket.error错误。
    clientSocket.connect(ADDR)
    print(clientSocket.recv(BUFSIZ))
    data = clientSocket.recv(BUFSIZ)
    str_data = bytes.decode(data)
    # p_g_public
    begin = 0
    keyword = ['', '', '']
    cnt = 0
    for index in range(len(str_data)):
        if str_data[index] == 'A' or index == len(str_data) - 1:
            if (index == len(str_data) - 1):
                index = index + 1
            for i in range(begin, index):
                keyword[cnt] = keyword[cnt] + str_data[i]
            cnt = cnt + 1
            begin = index + 1
    client = DH(int(keyword[0]), int(keyword[1]))
    client.calculateAESKey(int(keyword[2]))
    clientSocket.send(str(client.send_to_other_key).encode())
    print(clientSocket.recv(BUFSIZ))
    print('The client\'s AES key seed is ' + str(client.AES_key))
    Clientmd5 = MD5(str(client.AES_key))
    key = Clientmd5.md5Encode()
    print('The client\'s AES key is ' + key)
    while True:
        filepath = input("please input file path:")
        if os.path.isfile(filepath):
            # 定义定义文件信息。128s表示文件名为128bytes长,l表示一个int或log文件类型,在此为文件大小
            fileinfo_size = struct.calcsize('128sl')
            # 定义文件头信息,包括文件名和文件大小
            datalen = getlen(filepath, key)
            # fhead = struct.pack('128sl',os.path.basename(filepath).encode('utf-8'),
            # os.stat(filepath).st_size)
            fhead = struct.pack('128sl',
                                os.path.basename(filepath).encode('utf-8'),
                                datalen)
        if os.path.isfile(filepath):
            clientSocket.send(fhead)
            print('client filepath:{0}'.format(filepath))
            fp = open(filepath, 'rb')
            while True:
                data = fp.read(512)  # 1024的话这里可能会有问题,因为编码后大小会变大
                if not data:
                    print('{0} file send over...'.format(filepath))
                    fp.close()
                    break
                data = AES(key, bytes.decode(data), ENCRYPT)
                clientSocket.send(data.encode())
    # 因为如果传输完数据就关闭client,那么server那里会报错,因此使用死循环让client不能断开,这样server就不会报错了
    clientSocket.close()
示例#2
0
def main():
    f = open(sys.argv[3], "w")
    key = parseInput(sys.argv[2])
    aes = AES()
    if sys.argv[1] == "128":

        if len(key) != 16:
            print("Longitud de la llave invalido")
            exit(1)

        keyS = aes.KeyExpansion(key, 16, 176)  #AES 128
        hexlist = [hex(x)[2:] if x > 15 else "0" + hex(x)[2:] for x in keyS]
        matrixKey = [hexlist[i:i + 16] for i in range(0, len(hexlist), 16)]
        #f.write(str(matrixKey))
    elif sys.argv[1] == "192":
        if len(key) != 24:
            print("Longitud de la llave invalido")
            exit(1)
        keyS = aes.KeyExpansion(key, 24, 208)
        hexlist = [hex(x)[2:] if x > 15 else "0" + hex(x)[2:] for x in keyS]
        matrixKey = [hexlist[i:i + 16] for i in range(0, len(hexlist), 16)]
        #f.write(str(matrixKey))

    # Formato
    f.write("".join(matrixKey[0]) + "\n")
    matrixKey = matrixKey[1:]
    for row in matrixKey:
        f.write("".join(row) + "\n")
    f.close()
    return
示例#3
0
class TestChunkEncryption(unittest.TestCase):
    def setUp(self):
        self.aes = AES(b'z' * 16)
        self.iv = b'\x01' * 16

    def test_long_msg(self):
        message = b'M' * 228
        ciphertext = self.aes.encrypt(message, self.iv)
        self.assertEqual(self.aes.decrypt(ciphertext, self.iv), message)

    def test_diff_iv(self):
        iv2 = b'\x02' * 16
        message = b'M' * 16

        ciphertext1 = self.aes.encrypt(message, self.iv)
        ciphertext2 = self.aes.encrypt(message, iv2)
        self.assertNotEqual(ciphertext1, ciphertext2)

        plaintext1 = self.aes.decrypt(ciphertext1, self.iv)
        plaintext2 = self.aes.decrypt(ciphertext2, iv2)
        self.assertEqual(plaintext1, plaintext2)
        self.assertEqual(plaintext1, message)
        self.assertEqual(plaintext2, message)

    def test_bad_iv(self):
        message = b'M' * 16

        with self.assertRaises(AssertionError):
            self.aes.encrypt(message, b'short')

        with self.assertRaises(AssertionError):
            self.aes.encrypt(message, b'long' * 25)
示例#4
0
class ErrorHandler(QtWidgets.QFrame):
    def __init__(self):
        super(ErrorHandler, self).__init__(flags=Qt.FramelessWindowHint)
        self.ui = Ui_ErrorHandler()
        self.__press_pos = None
        self.data = None
        self.AES = AES()
        self.ui.setupUi(self)
        self.error_text = self.ui.error_text
        self.ui.close.clicked.connect(lambda: self.hide())
        self.ui.send_button.clicked.connect(self.send)

    def send(self):
        if self.ui.rgpd_accept.isChecked() and len(self.ui.discordname.text()) > 0:
            self.AES.send_issues(self.data, self.ui.discordname.text())
            self.hide()

    def set_error(self, e, data):
        self.data = data
        self.error_text.setPlainText(e)

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.__press_pos = event.pos()  # remember starting position

    def mouseReleaseEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.__press_pos = None

    def mouseMoveEvent(self, event):
        if self.__press_pos and self.ui.titlebar_widget.underMouse():
            self.move(self.pos() + (event.pos() - self.__press_pos))
示例#5
0
def test_AES(inp):
    aes = AES(4, "00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f")
    key = os.urandom(16).hex()

    ciphertext = aes.encrypt(inp, key, "bytes")

    deciphered = aes.decrypt(ciphertext, key, "bytes")
    assert deciphered == inp
示例#6
0
    def test_MixColumnsInv(self):
        instance = AES()

        # full inversion test
        for i in xrange(0, len(self.gf_full), 16):
            test_input = self.gf_full[i:i + 16]
            self.assertEquals(
                test_input,
                instance.MixColumnsInv(instance.MixColumns(test_input)))
            self.assertNotEqual(test_input, instance.MixColumnsInv(test_input))
示例#7
0
 def __init__(self):
     super(ErrorHandler, self).__init__(flags=Qt.FramelessWindowHint)
     self.ui = Ui_ErrorHandler()
     self.__press_pos = None
     self.data = None
     self.AES = AES()
     self.ui.setupUi(self)
     self.error_text = self.ui.error_text
     self.ui.close.clicked.connect(lambda: self.hide())
     self.ui.send_button.clicked.connect(self.send)
示例#8
0
def subByteTest():
    aes = AES(master_key)
    m = master_message
    c = aes.encrypt(m)
    for i in range(128):
        for j in range(i+1, 128):
            ci = aes.encrypt(m ^ (1 << i))
            cj = aes.encrypt(m ^ (1 << j))
            ij_mov = 1 << i ^ 1 << j
            cij = aes.encrypt(m ^ ij_mov)
            assert(c != ci ^ cj ^ cij)
示例#9
0
def deal_data(conn, addr):
    print('Accept new connection from{0}'.format(addr))
    conn.send('Welcome to the server!Let\'s exchange the key'.encode('utf-8'))
    p, g = find_pg()
    Server = DH(p, g)
    p_g_publicKey = str(p) + 'A' + str(g) + 'A' + str(Server.send_to_other_key)
    conn.send(p_g_publicKey.encode())
    conn.send('Server\'s public key send over'.encode())
    data = conn.recv(1024)
    public_key = int(data)
    Server.calculateAESKey(public_key)
    conn.send('key exchange completed'.encode())
    print('The server\'s AES key seed is ' + str(Server.AES_key))
    Servermd5 = MD5(str(Server.AES_key))
    key = Servermd5.md5Encode()
    print('The server\'s AES key is ' + key)
    # while True:
    fileinfo_size = struct.calcsize('128sl')
    buf = conn.recv(fileinfo_size)
    if buf:
        filename, filesize = struct.unpack('128sl', buf)
        if filesize % 16 != 0:
            filesize = filesize + 16  # 因为AES加密会填充够16个
            filesize = int(floor(filesize / 16) * 16)
        fn = filename.strip('\00'.encode('utf-8'))
        strfn = str(fn, 'utf-8')
        new_filename = os.path.join('F:\\py-test\\key_exchange\\' +
                                    'receive_' + strfn)
        print('file new name is{0},filesize is{1}'.format(
            new_filename, filesize))
        # 记录已接收文件的大小
        recvd_size = 0
        fp = open(new_filename, 'wb+')
        print('start receiving')

        while True:
            # 可能会碰到ConnectionResetError [WinError 10054] 远程主机强迫关闭了一个现有的连接。这是因为client已经发完数据并关闭了连接造成的
            data = conn.recv(1024)
            if not data:
                print('end receive...')
                break
            data = AES(key, bytes.decode(data), DECRYPT)  # 在这里加上解密
            print(data)
            recvd_size = recvd_size + len(data)
            fp.write(data.encode())
            if recvd_size >= filesize:
                break
        fp.close()
        print('end receive...')
        # conn.send('receive successfully'.encode())
    conn.close()
示例#10
0
class TestFileEncryption(unittest.TestCase):
    def setUp(self):
        self.aes = AES(b'z' * 16)
        self.iv = b'\x01' * 16

    def test_small_file_enctime(self):
        filename = "small.txt"
        start = time.time()
        self.aes.encrypt_file(filename, iv=self.iv)
        print(filename + "encrypted within %s seconds" % (time.time() - start))

    def test_small_file_dectime(self):
        filename = "small.txt.enc"
        start = time.time()
        self.aes.decrypt_file(filename)
        print(filename + "decrypted within %s seconds" % (time.time() - start))

    def test_2mbfile_enctime(self):
        filename = "lorem-ipsum.txt"
        start = time.time()
        self.aes.encrypt_file(filename, iv=self.iv)
        print(filename + " encrypted within %s seconds" %
              (time.time() - start))

    def test_2mbfile_dectime(self):
        filename = "lorem-ipsum.txt.enc"
        start = time.time()
        self.aes.decrypt_file(filename)
        print(filename + " decrypted within %s seconds" %
              (time.time() - start))
示例#11
0
文件: getlen.py 项目: Monica-y/Monica
def getlen(filepath, key):
    filelen = 0
    if os.path.isfile(filepath):
        fp = open(filepath, 'rb')
        while True:
            data = fp.read(512)  # 1024的话这里可能会有问题,因为编码后大小会变大
            if not data:
                print('{0} End of encrypted file size calculation...'.format(
                    filepath))
                fp.close()
                break
            data = AES(key, bytes.decode(data), ENCRYPT)
            filelen = filelen + len(data.encode())
    # print(filelen)
    return filelen
示例#12
0
    def test_decrypt_multiple_blocks_ECB(self):
        data = b'\xa9\x13)\xaf\x99\xa7\x8d\x02\xae\xc1|PwW\xaa\xef\xa9\x13)\xaf\x99\xa7' \
               b'\x8d\x02\xae\xc1|PwW\xaa\xef\x8ed\xce\x87?\x17M\xbb$#\xfc\xd8\x14X\x0e\x15'

        expected = b'abcdefghijklmnopabcdefghijklmnop'
        actual = AES(key, ECB).decrypt(data)
        self.assertEqual(expected, actual)
示例#13
0
文件: client.py 项目: Monica-y/Monica
def socket_client():
    serverName = '127.0.0.1'
    serverPort = 11000
    BUFSIZ = 1024
    ADDR = (serverName, serverPort)

    # 套接字家族可以使 AF_UNIX 或者 AF_INET。
    # 套接字类型可以根据是面向连接的还是非连接分为 SOCK_STREAM 或 SOCK_DGRAM。
    clientSocket = socket(AF_INET, SOCK_STREAM)
    # 主动初始化TCP服务器连接。
    # 一般address的格式为元组(hostname,port),如果连接出错,返回socket.error错误。
    clientSocket.connect(ADDR)
    print(clientSocket.recv(BUFSIZ))

    while True:
        # data = "client message"
        # data = input('>>>')
        filepath = input("please input file path:")
        if os.path.isfile(filepath):
            # 定义定义文件信息。128s表示文件名为128bytes长,l表示一个int或log文件类型,在此为文件大小
            fileinfo_size = struct.calcsize('128sl')
            # 定义文件头信息,包括文件名和文件大小
            fhead = struct.pack('128sl',
                                os.path.basename(filepath).encode('utf-8'),
                                os.stat(filepath).st_size)
            clientSocket.send(fhead)
            print('client filepath:{0}'.format(filepath))
            fp = open(filepath, 'rb')
            # fp = open(filepath,'r')
            while True:
                data = fp.read(1024)  # 1024
                # data = AES('1234567890123456',str(data,'utf-8'),ENCRYPT)
                if not data:
                    print('{0} file send over...'.format(filepath))
                    break
                data = AES('1234567890123456', bytes.decode(data), ENCRYPT)
                # clientSocket.send(data.encode('utf-8'))
                clientSocket.send(data.encode())
        # clientSocket.send(data.encode('utf-8'))
        # returnData = clientSocket.recv(BUFSIZ)
        # if not returnData:
        #     break
        # print('Return time is:%s' %returnData.decode('utf-8'))
        clientSocket.close()
示例#14
0
    def test_SubBytesInv_table(self):
        input = [gf._cache.fetch_int(i) for i in S]
        assert input[125] == gf._cache.fetch_int(255)
        result = AES().SubBytesInv(input)

        for (i, expected_gfe) in enumerate(result):
            expected_int = int(expected_gfe._int_repr())
            if expected_int is not i:
                print expected_int, i
            self.assertEquals(expected_int, i)
示例#15
0
class Cryptography:
    def __init__(self, private_key, public_key, P):
        self.private_key = private_key
        self.public_key = public_key
        self.session_key = pow(public_key, private_key, P)
        self.aes_obj = AES(self.session_key)

    def encrypt(self, message):
        blocks = convertMessage(message)
        y = []
        for block in blocks:
            y.append(str(self.aes_obj.encrypt(block)))
        return '&'.join(y)

    def decrypt(self, message):
        x = []
        message = message.split("&")
        for block in message:
            x.append(self.aes_obj.decrypt(int(block)))
        return getMessage(x)
示例#16
0
def deal_data(conn, addr):
    print('Accept new connection from{0}'.format(addr))
    conn.send('Welcome to the server!'.encode('utf-8'))
    while True:
        fileinfo_size = struct.calcsize('128sl')
        buf = conn.recv(fileinfo_size)
        if buf:
            filename, filesize = struct.unpack('128sl', buf)
            fn = filename.strip('\00'.encode('utf-8'))
            strfn = str(fn, 'utf-8')
            # new_filename = os.path.join('./','receive_'+strfn)# fn
            new_filename = os.path.join('F:\\py-test\\' + 'receive_' + strfn)
            # "C:\Users\孙玉琪\receive_info.txt"
            print('file new name is{0},filesize is{1}'.format(
                new_filename, filesize))
            # 记录已接收文件的大小
            recvd_size = 0
            # fp = open(new_filename,'wb')
            fp = open(new_filename, 'wb+')
            print('start receiving')

            while True:
                data = conn.recv(1024)
                if not data:
                    print('end receive...')
                    break
                # data = AES('1234567890123456',str(data,'utf-8'),DECRYPT)# 在这里加上解密
                data = AES('1234567890123456', bytes.decode(data),
                           DECRYPT)  # 在这里加上解密
                print(data)
                recvd_size = recvd_size + len(data)
                # fp.write(data.encode('utf-8'))
                fp.write(data.encode())
            fp.close()
            print('end receive...')
        conn.close()
        break
示例#17
0
    def test__left_shift(self):
        input = 0b01000011
        expected_result = 0b00001101
        poly = gf._cache.fetch_int(input)
        result = AES._left_shift(poly, 2)
        self.assertEquals(expected_result, int(result._int_repr()))

        input = 0b00110011
        expected_result = 0b11001100
        poly = gf._cache.fetch_int(input)
        result = AES._left_shift(poly, 2)
        self.assertEquals(expected_result, int(result._int_repr()))

        input = 0b11111111
        expected_result = 0b0
        poly = gf._cache.fetch_int(input)
        result = AES._left_shift(poly, 2)
        self.assertEquals(expected_result, int(result._int_repr()))

        input = 0b0
        expected_result = input
        poly = gf._cache.fetch_int(input)
        result = AES._left_shift(poly, 2)
        self.assertEquals(expected_result, int(result._int_repr()))
示例#18
0
def calculation(message,
                n,
                e,
                d,
                p,
                q,
                startzustand=[1, 1, 1, 1, 0, 0, 0, 0],
                verbose=False):
    ### Alice ###
    ## 1,
    a = bitarray(startzustand)
    start_lfsr_alice = LFSR.lfsr(a, [0, 1, 3, 4])
    key = [next(start_lfsr_alice) for _ in range(120)]
    key = "".join(str(x) for x in startzustand + key)
    print("--ALICE--------")
    print("LFSR-Key: {}".format(helper.get_split_string_from_list(list(key))))

    ## 2,
    rsa = RSA(p="", q="", n=n, e=e)
    if verbose:
        rsa.print_stats()
    c_1 = rsa.short_public_exponent_encrypt(int("".join(
        str(i) for i in startzustand),
                                                base=2),
                                            verbose=verbose)
    print("RSA Ciphertext: {}".format(c_1))

    ## 3,
    aes = AES(key)
    c_2 = aes.encrypt(message, verbose=verbose)
    print("AES Ciphertext: {}".format(c_2))

    ### Bob ###
    ## 1,
    rsa = RSA(p=p, q=q, e=e, private_key=d)
    print("--BOB----------")
    print("Decryption....")
    bin_str = bin(rsa.chinese_decrypt(c_1, verbose=verbose))[2:]
    print("RSA Plaintext: {}".format(
        helper.get_split_string_from_list(list(bin_str))))

    ## 2,
    a = bitarray(bin_str)
    start_lfsr_bob = LFSR.lfsr(a, [0, 1, 3, 4])
    key_bob = [next(start_lfsr_bob) for _ in range(120)]
    key_bob = "".join(str(x) for x in list(bin_str) + key_bob)
    print("LFSR-Key: {}".format(
        helper.get_split_string_from_list(list(bin_str))))

    ## 3,
    aes = AES(key_bob)
    corresponding_message = aes.decrypt(c_2, verbose=verbose)
    print("Message: {}".format(corresponding_message))
    return message
示例#19
0
 def test_expand_key(self):
     key = bytes([0x54, 0x68, 0x61, 0x74, 0x73, 0x20, 0x6D, 0x79, 0x20, 0x4B, 0x75, 0x6E, 0x67, 0x20, 0x46, 0x75])
     expected = [
         ([0x54, 0x68, 0x61, 0x74], [0x73, 0x20, 0x6D, 0x79], [0x20, 0x4B, 0x75, 0x6E], [0x67, 0x20, 0x46, 0x75]),
         ([0xE2, 0x32, 0xFC, 0xF1], [0x91, 0x12, 0x91, 0x88], [0xB1, 0x59, 0xE4, 0xE6], [0xD6, 0x79, 0xA2, 0x93]),
         ([0x56, 0x08, 0x20, 0x07], [0xC7, 0x1A, 0xB1, 0x8F], [0x76, 0x43, 0x55, 0x69], [0xA0, 0x3A, 0xF7, 0xFA]),
         ([0xD2, 0x60, 0x0D, 0xE7], [0x15, 0x7A, 0xBC, 0x68], [0x63, 0x39, 0xE9, 0x01], [0xC3, 0x03, 0x1E, 0xFB]),
         ([0xA1, 0x12, 0x02, 0xC9], [0xB4, 0x68, 0xBE, 0xA1], [0xD7, 0x51, 0x57, 0xA0], [0x14, 0x52, 0x49, 0x5B]),
         ([0xB1, 0x29, 0x3B, 0x33], [0x05, 0x41, 0x85, 0x92], [0xD2, 0x10, 0xD2, 0x32], [0xC6, 0x42, 0x9B, 0x69]),
         ([0xBD, 0x3D, 0xC2, 0x87], [0xB8, 0x7C, 0x47, 0x15], [0x6A, 0x6C, 0x95, 0x27], [0xAC, 0x2E, 0x0E, 0x4E]),
         ([0xCC, 0x96, 0xED, 0x16], [0x74, 0xEA, 0xAA, 0x03], [0x1E, 0x86, 0x3F, 0x24], [0xB2, 0xA8, 0x31, 0x6A]),
         ([0x8E, 0x51, 0xEF, 0x21], [0xFA, 0xBB, 0x45, 0x22], [0xE4, 0x3D, 0x7A, 0x06], [0x56, 0x95, 0x4B, 0x6C]),
         ([0xBF, 0xE2, 0xBF, 0x90], [0x45, 0x59, 0xFA, 0xB2], [0xA1, 0x64, 0x80, 0xB4], [0xF7, 0xF1, 0xCB, 0xD8]),
         ([0x28, 0xFD, 0xDE, 0xF8], [0x6D, 0xA4, 0x24, 0x4A], [0xCC, 0xC0, 0xA4, 0xFE], [0x3B, 0x31, 0x6F, 0x26]),
     ]
     actual = AES(key).round_keys
     self.assertEqual(expected, actual)
示例#20
0
	def rip_video(self):
		r = self.httpy.get(self.url)

		if 'video_title":"' not in r:
			raise Exception('no video_title":" found at %s' % self.url)
		title = self.httpy.between(r, 'video_title":"', '"')[0]
		title = title.replace('+', ' ')

		if '0p":"' not in r:
			raise Exception('no 0p":" found at %s' % self.url)
		quality = self.httpy.between(r, '0p":"', '"')[0]
		quality = unquote(quality)

		vid = AES.decrypt(quality, title, 256)

		result = self.get_video_info(vid)
		result['poster'] = None # Beeg doesn't provide video splash images
		return result
示例#21
0
    def rip_video(self):
        r = self.httpy.get(self.url)

        if 'video_title":"' not in r:
            raise Exception('no video_title":" found at %s' % self.url)
        title = self.httpy.between(r, 'video_title":"', '"')[0]
        title = title.replace('+', ' ')

        if '0p":"' not in r:
            raise Exception('no 0p":" found at %s' % self.url)
        quality = self.httpy.between(r, '0p":"', '"')[0]
        quality = unquote(quality)

        vid = AES.decrypt(quality, title, 256)

        result = self.get_video_info(vid)
        result['poster'] = None  # Beeg doesn't provide video splash images
        return result
示例#22
0
    def test_SubBytesInv(self):

        # test single substitution
        sbox_input = gf._cache.fetch_int(0xb8)
        expected_result = gf._cache.fetch_int(0x9a)

        instance = AES()
        result = instance.SubBytesInv([sbox_input])[0]
        self.assertEquals(expected_result, result)

        poly = gf._cache.fetch_int(0x99)
        self.assertEquals(poly,
                          instance.SubBytesInv(instance.SubBytes([poly]))[0])

        # full inversion test
        self.assertEquals(
            self.gf_full,
            instance.SubBytesInv(instance.SubBytes(self.gf_full)))
示例#23
0
    def rip_video(self):
        r = self.httpy.get(self.url)

        if 'video_title":"' not in r:
            raise Exception('no video_title":" found at %s' % self.url)
        title = self.httpy.between(r, 'video_title":"', '"')[0]
        title = title.replace('+', ' ')

        if 'video_url":"' not in r:
            raise Exception('no video_url":" found at %s' % self.url)
        quality = self.httpy.between(r, 'video_url":"', '"')[0]
        quality = unquote(quality)

        vid = AES.decrypt(quality, title, 256)

        result = self.get_video_info(vid)
        result['poster'] = None  # No Preview
        result['no_video'] = True  # Don't try to display the video
        result['title'] = title
        return result
示例#24
0
文件: VideoTube8.py 项目: 4pr0n/rip3
	def rip_video(self):
		r = self.httpy.get(self.url)

		if 'video_title":"' not in r:
			raise Exception('no video_title":" found at %s' % self.url)
		title = self.httpy.between(r, 'video_title":"', '"')[0]
		title = title.replace('+', ' ')

		if 'video_url":"' not in r:
			raise Exception('no video_url":" found at %s' % self.url)
		quality = self.httpy.between(r, 'video_url":"', '"')[0]
		quality = unquote(quality)

		vid = AES.decrypt(quality, title, 256)

		result = self.get_video_info(vid)
		result['poster'] = None # No Preview
		result['no_video'] = True # Don't try to display the video
		result['title'] = title
		return result
示例#25
0
 def test_expand_key_192_bit(self):
     key = bytes(bytearray.fromhex('000102030405060708090a0b0c0d0e0f1011121314151617'))
     expected = [
         '000102030405060708090a0b0c0d0e0f',
         '10111213141516175846f2f95c43f4fe',
         '544afef55847f0fa4856e2e95c43f4fe',
         '40f949b31cbabd4d48f043b810b7b342',
         '58e151ab04a2a5557effb5416245080c',
         '2ab54bb43a02f8f662e3a95d66410c08',
         'f501857297448d7ebdf1c6ca87f33e3c',
         'e510976183519b6934157c9ea351f1e0',
         '1ea0372a995309167c439e77ff12051e',
         'dd7e0e887e2fff68608fc842f9dcc154',
         '859f5f237a8d5a3dc0c02952beefd63a',
         'de601e7827bcdf2ca223800fd8aeda32',
         'a4970a331a78dc09c418c271e3a41d5d'
     ]
     expected = [list(map(list, _chunk(bytes(bytearray.fromhex(exp)), 4))) for exp in expected]
     actual = AES(key).round_keys
     for exp, act in zip(expected, actual):
         self.assertEqual(exp, list(act))
示例#26
0
    def test_ShiftRowsInv(self):
        instance = AES()
        test_indice_replacement = [(0, 0), (8, 8), (4, 4), (12, 12), (1, 13),
                                   (5, 1), (9, 5), (13, 9), (2, 10), (6, 14),
                                   (10, 2), (14, 6), (3, 7), (7, 11), (11, 15),
                                   (15, 3)]

        for indices in test_indice_replacement:
            self.assertEquals(test_mask(indices[1]),
                              instance.ShiftRowsInv(test_mask(indices[0])),
                              msg="indice %d is not replaced correctly" %
                              indices[0])

        # full inversion test
        for block in instance._get_blocks(self.gf_full):
            test_input = block
            self.assertEquals(
                test_input,
                instance.ShiftRowsInv(instance.ShiftRows(test_input)))
            self.assertNotEqual(test_input, instance.ShiftRowsInv(test_input))
示例#27
0
    def test_AddRoundKey(self):
        # for input = key the result should be 0
        instance = AES(key=("test" * 3))
        input = [gf._cache.fetch_int(i) for i in xrange(16)]
        key = [gf._cache.fetch_int(i) for i in xrange(16)]
        expected_result = [gf(0)] * 16
        result = instance.AddRoundKey(input, key)
        self.assertEquals(expected_result, result)

        # for each position the result should be the xor result
        input = [gf._cache.fetch_int(i) for i in xrange(16)]
        key = [gf._cache.fetch_int(i + i) for i in xrange(16)]
        result = instance.AddRoundKey(input, key)
        self.assertEquals(len(result), len(input))
        for i in xrange(len(result)):
            self.assertEquals(input[i] + key[i], result[i])

        # inversion test: applying the same key again should invert the effect
        input = [gf._cache.fetch_int(2 * i) for i in xrange(16)]
        key = [gf._cache.fetch_int(i**2) for i in xrange(16)]
        result = instance.AddRoundKey(input, key)
        self.assertEquals(input, instance.AddRoundKey(result, key))
示例#28
0
def main(*arg):
    #Ckecks that length of path meets the requirement CHECK
    if len(arg) < 6:
        print("\nError!!!\nArgument is too long/less\n")
        print(
            "\nPlease try entering the following path:\n python ./cipher <CIPHER NAME><KEY><ENC/DEC><IPUT FILE><OUTPUT FiLE>"
        )
        exit(-1)

    #declaring arguments
    cname = arg[1]
    key = arg[2]
    encdec = arg[3]
    iFile = arg[4]
    oFile = arg[5]

    cipher = None
    #opens in.txt file and reads from it to encrypt/decrypt the message provided
    with open(iFile, "r") as f:
        iString = f.read()


#================EXTRA CREDIT IMPLEMENTATION STARTS HERE===========================
#This is for DES encryption in CBC mode
    if cname == "dcbc":
        cipher = DES()
        if cipher.setKey(key):
            if encdec == "enc":
                output = cipher.encryptCBC(iString)
            elif encdec == "dec":
                output = cipher.encryptCBC(iString)
            else:
                print("\nError enc/dec not entered\n")
                exit(-1)
        else:
            print("\nError. Invalid dcbc key\n")
            exit(-1)
    #This is for DES encryption in CFB mode
    elif cname == "dcfb":
        cipher = DES()
        if cipher.setKey(key):
            if encdec == "enc":
                output = cipher.encryptCFB(iString)
            elif encdec == "dec":
                output = cipher.decryptCFB(iString)
            else:
                print("\nError enc/dec not entered\n")
                exit(-1)
        else:
            print("\nError. Invalid dcfb key\n")
            exit(-1)
    #This is for AES encryption in CBC mode
    elif cname == "acbc":
        cipher = AES()
        if cipher.setKey(key):
            if encdec == "enc":
                output = cipher.encryptCBC(iString)
            elif encdec == "dec":
                output = cipher.decryptCBC(iString)
            else:
                print("\nError enc/dec not entered\n")
                exit(-1)
        else:
            print("\nError. Invalid acbc key\n")
            exit(-1)
    elif cname == "acfb":
        cipher = AES()
        if cipher.setKey(key):
            if encdec == "enc":
                output = cipher.encryptCFB(iString)
            elif encdec == "dec":
                output = cipher.decryptCFB(iString)
            else:
                print("\nError enc/dec not entered\n")
                exit(-1)
        else:
            print("\nError. Invalid acfb key\n")
            exit(-1)

    #END, below is a selection for a cipher error selection
    else:
        print("\nError. No class has been selected.\n")
        exit(-1)

    #displays the user's input and output
    print("\nWhat goes to the in.txt file (user's input): " + iString)
    print("\nWhat goes to the out.txt file (user's output): " + output)
    print("\n\n")

    #writing to the output file
    with open(oFile, "w") as out_f:
        out_f.write(output)
        print(
            "\nEncryption was written to out.txt/Decryption was written to out2.txt"
        )
        print(
            "\NOTE: to decrypt message use out.txt first and then out2.txt.\n")

    #close all txt files
    f.close()
    out_f.close()
示例#29
0
    cer = Certificate(origen.getPrivateKey(), origen.getPublicKey())
    certificado = cer.getCertificate()
    # Se pasa la llave publica del receptor al origen
    origen.setEntityKey(receptor.getPublicKey())

    ########## Tiempo de cifrado ###############
    # Se cifra con la llave de la otra entidad
    tiempos.medir(f'cifradollave_{x}')
    cypherKey = origen.encrypt(k)
    tiempos.medir(f'cifradollave_{x}')
    ############################################

    # Se cifran los documentos
    for documento in documentos:
        # Se instancia el cifrador simetrico
        aeso = AES(k, iv)

        # Se lee el archivo
        f = open(f'documentos/{documento}', 'rb')
        contenido = f.read()
        f.close()

        ########## Tiempo de cifrado ###############
        # Se cifra el contenido de cada archivo
        tiempos.medir(f'cifrado_{documento}_llave_{x}')
        cyphertext = aeso.encrypt(contenido)
        tiempos.medir(f'cifrado_{documento}_llave_{x}')
        ############################################

        # Se retira la extension [opcional]
        nombre = documento.split('.')
示例#30
0
def main(*arguments):
    #Display instructions if improper argument length is given
    if len(arguments) != 6 and len(arguments) != 7:
        print("\nINVALID ARGUMENTS:")
        print(
            "./cipher <CIPHER NAME> <KEY> <ENC/DEC> <INPUTFILE> <OUTPUT FILE> <--OPTIONS/-O>"
        )
        print("\n\tSupported Ciphers:")
        print("\t- DES: Indicates the 64bit DES cipher")
        print(
            "\t- DES-CBC: DES Cipher in CBC Mode\n\t- DES-CFB: DES Cipher in CFB Mode\n"
        )
        print("\t- AES: Indicates 128bit AES cipher")
        print(
            "\t- AES-CBC: AES Cipher in CBC Mode\n\t- AES-CFB: AES Cipher in CFB Mode"
        )
        print(
            "\n\t--OPTIONS - Optional setting: If enabled will ask for converting\n\t\tto lowercase and removing non-alpha characters\n"
        )
        quit()

    cipherName = arguments[1].upper()
    key = arguments[2].replace(" ", "")
    encOrDec = arguments[3].upper()
    inFile = arguments[4]
    outFile = arguments[5]

    try:
        #Check if option is specified
        opt = arguments[6].upper()
    except:
        opt = None

    if opt == "--OPTIONS" or opt == "-O":
        #ask for options
        options = [None] * 2
        while options[0] != 'y' and options[0] != 'n':
            if sys.version[0] == '3':
                options[0] = input(
                    "Strip input file of non alphabetical characters? (Y/N): "
                ).lower()
            elif sys.version[0] == '2':
                options[0] = raw_input(
                    "Strip input file of non alphabetical characters? (Y/N): "
                ).lower()
        while options[1] != 'y' and options[1] != 'n':
            if sys.version[0] == '3':
                options[1] = input("Convert to lower case? (Y/N): ").lower()
            elif sys.version[0] == '2':
                options[1] = raw_input(
                    "Convert to lower case? (Y/N): ").lower()
    else:
        options = ['n', 'n']  #set options to no

    try:
        #Open data from inputString file
        with open(inFile, "r") as f:
            if options[0] == options[1] == 'n':
                #Both no
                inputString = f.read()
            elif options[0] == 'n':
                #lower case
                inputString = f.read().lower()
            elif options[1] == 'n':
                #strip non-alpha
                inputString = ''.join([c for c in f.read() if c.isalpha()])
            else:
                #strip non-alpha characters and lower case
                inputString = ''.join(
                    [c.lower() for c in f.read() if c.isalpha()])
    except:
        print("\nError: Input file \"" + inFile + "\" doesn't exist")
        quit()

    if cipherName == "DES":
        cipher = DES()
        if cipher.setKey(key):
            if encOrDec == "ENC":
                output = cipher.encrypt(inputString)
            elif encOrDec == "DEC":
                output = cipher.decrypt(inputString)
            else:
                print("Invalid Encryption/Decryption Option")
                quit()
        else:
            print("Failure: Invalid Key")
            quit()

    elif cipherName == "DES-CBC":
        cipher = DES()
        if cipher.setKey(key):
            if encOrDec == "ENC":
                output = cipher.encryptCBC(inputString)
            elif encOrDec == "DEC":
                output = cipher.decryptCBC(inputString)
            else:
                print("Invalid Encryption/Decryption Option")
                quit()
        else:
            print("Failure: Invalid Key")
            quit()

    elif cipherName == "DES-CFB":
        cipher = DES()
        if cipher.setKey(key):
            if encOrDec == "ENC":
                output = cipher.encryptCFB(inputString)
            elif encOrDec == "DEC":
                output = cipher.decryptCFB(inputString)
            else:
                print("Invalid Encryption/Decryption Option")
                quit()
        else:
            print("Failure: Invalid Key")
            quit()

    elif cipherName == "AES":
        cipher = AES()
        if cipher.setKey(key):
            if encOrDec == "ENC":
                output = cipher.encrypt(inputString)
            elif encOrDec == "DEC":
                output = cipher.decrypt(inputString)
            else:
                print("Invalid Encryption/Decryption Option")
                quit()
        else:
            print("Failure: Invalid Key")
            quit()

    elif cipherName == "AES-CBC":
        cipher = AES()
        if cipher.setKey(key):
            if encOrDec == "ENC":
                output = cipher.encryptCBC(inputString)
            elif encOrDec == "DEC":
                output = cipher.decryptCBC(inputString)
            else:
                print("Invalid Encryption/Decryption Option")
                quit()
        else:
            print("Failure: Invalid Key")
            quit()

    elif cipherName == "AES-CFB":
        cipher = AES()
        if cipher.setKey(key):
            if encOrDec == "ENC":
                output = cipher.encryptCFB(inputString)
            elif encOrDec == "DEC":
                output = cipher.decryptCFB(inputString)
            else:
                print("Invalid Encryption/Decryption Option")
                quit()
        else:
            print("Failure: Invalid Key")
            quit()

    else:
        print("\nError: Cipher not supported. Please check the name again.")
        quit()

    print("\nINPUT: ")
    print(inputString)

    print("\nOUTPUT: ")
    print(output)
    with open(outFile, "w+") as f:
        f.write(output)
        print("\nSuccess!")
示例#31
0
#!/usr/bin/env sage
from sage.all import *
from AES import AES

instance = AES(key="sometestkey", rounds=2)

plaintext = "some message to encrypt"
print "plaintext:", plaintext
print "plaintext length:", len(plaintext)
ciphertext = instance.encrypt(plaintext)

print "ENCRYPTION RESULT"
print plaintext, "->", AES.state_int(ciphertext)
print
print "DECRYPTION RESULT"
decrypted_plaintext = instance.decrypt(ciphertext)
print AES.state_int(ciphertext), "->", AES.state_str(decrypted_plaintext)

示例#32
0
# coding=UTF-8

from AES import AES
import numpy as np

key = 0x3220db6534d687f844c41b6de5a4c737
aes = AES(key, 1, 0)
inp_row = np.array([172,47,117,192,67,251,195,103,9,211,21,242,36,87,70,216])
cipher_text, trace = aes.encrypt(inp_row)
assert ([173,205,44,52,32,86,75,184,193,231,36,82,28,6,44,234] == cipher_text).all()
print("AES Test PASS")