コード例 #1
0
ファイル: ftpclient.py プロジェクト: jy-cw/ftp
    def _put(self, *args, **kwargs):
        cmd_list = args[0]
        print("上传命令列表--", cmd_list)
        if len(cmd_list) == 1:
            print('没带文件参数')
            return

        filename = cmd_list[1]

        if os.path.isfile(filename):
            size = os.path.getsize(filename)
            if self.__md5_required(cmd_list):
                local_md5 = md5.md5sum(filename)
                data_header = {
                    'action': 'put',
                    'filename': filename,
                    'size': size,
                    'md5': local_md5
                }
            else:
                data_header = {
                    'action': 'put',
                    'filename': filename,
                    'size': size,
                    'md5': None
                }
            self.client.send(json.dumps(data_header).encode())
            response = self.get_response()
            if response['code'] == 200:
                process = self.show_progress(size)
                process.__next__()
                f = open(filename, 'rb')
                for line in f:
                    self.client.send(line)
                    try:
                        process.send(len(line))
                    except StopIteration as e:
                        print("100%")
                print('文件上传完毕')
                f.close()
            else:
                print('错误: ', response['msg'])
            if self.__md5_required(cmd_list):
                md5_recv = self.get_response()
                server_md5 = md5_recv['data']['md5']
                if server_md5 == local_md5:
                    print('服务器上的文件和本地文件md5校验一致,都是: ', local_md5)
                else:
                    print('文件MD5校验不一致,服务器MD5: %s,本地MD5: %s' %
                          (server_md5, local_md5))
        else:
            print(os.getcwd())
            print(filename, '本地文件不存在')
コード例 #2
0
ファイル: PGP.py プロジェクト: universuen/Cryptography
    def decrypt(self, en_msg):
        print('Started decryption')
        # <IDEA(ZIP(M, S)), RSA(k)> -> IDEA(ZIP(M, S)), RSA(k)
        print('\tExtracting key')
        bin_en_msg = base_64.decode(en_msg)
        idea_en_msg = bin_en_msg[:-128]
        en_key = bin_en_msg[-128:]

        # RSA(k) -> k
        print('\tDecrypting key')
        temp_key = "".encode('utf-8')
        for i in range(int(len(en_key))):
            tmp = en_key[i]
            tmp = int(tmp)  # bytes->int
            tmp = '{:08b}'.format(tmp).encode('utf-8')  # int->str->bytes
            temp_key = temp_key + tmp
        en_key = int(str(temp_key.decode('utf-8')), 2)
        idea_key = rsa.decrypt(en_key, self.receiver.pri_key)

        # IDEA(ZIP(M, S)) -> ZIP(M, S)
        print('\tDecrypting data')
        msg = IDEA.IDEA_de(idea_en_msg, idea_key)

        # ZIP(M, S) -> M, S
        print('\tDecompressing data')
        msg = zipstream.bytes2bitarray(msg)
        msg = self.compressor.decompress(msg)
        message = msg[:-128]
        sign = msg[-128:]
        temp_sign = "".encode('utf-8')
        for i in range(int(len(sign))):
            tmp = sign[i]
            tmp = int(tmp)  # bytes->int
            tmp = '{:08b}'.format(tmp).encode('utf-8')  # int->str->bytes
            temp_sign = temp_sign + tmp
        sign = int(str(temp_sign.decode('utf-8')), 2)

        # Verification
        print('\tVerifying')
        original_md5 = rsa.encrypt(sign, self.sender.pub_key)
        original_md5 = hex(original_md5)[2:]
        print(f'Original md5: \t{original_md5}')
        current_md5 = md5.md5sum(message)
        print(f'Current md5: \t{current_md5}')
        if current_md5 == original_md5:
            print('Verified!')
            return message
        else:
            print("Verification failed!")
            return None
コード例 #3
0
ファイル: ftpclient.py プロジェクト: jy-cw/ftp
    def _get(self, *args, **kwargs):
        cmd_list = args[0]
        print("下载命令列表--", cmd_list)
        if len(cmd_list) == 1:
            print('没带文件参数')
            return
        filename = cmd_list[1]

        if self.__md5_required(cmd_list):
            data_header = {'action': 'get', 'filename': filename, 'md5': True}
        else:
            data_header = {'action': 'get', 'filename': filename, 'md5': False}

        self.client.send(json.dumps(data_header).encode())
        response = self.get_response()
        if response['code'] == 257:
            #告诉服务器端可以发送了
            self.client.send(b'1')
            size = response['data']['size']
            recv_size = 0
            m = hashlib.md5()
            f = open(filename, 'wb')
            process = self.show_progress(size)
            process.__next__()
            while recv_size < size:
                recv_data = self.client.recv(1024)
                f.write(recv_data)
                recv_size += len(recv_data)
                try:
                    process.send(len(recv_data))
                except StopIteration as e:
                    print("100%")
            else:
                print('%s 文件下载完成' % filename)
                f.close()
        else:
            print('错误: ', response['msg'])

        if data_header['md5']:
            server_md5 = response['data']['md5']
            local_md5 = md5.md5sum(filename)
            if server_md5 == local_md5:
                print('服务器文件和本地文件md5校验一致,都是: ', local_md5)
            else:
                print('错误:文件md5校验不一致,服务器MD5: %s,本地MD5: %s' %
                      (server_md5, local_md5))
コード例 #4
0
ファイル: PGP.py プロジェクト: universuen/Cryptography
    def encrypt(self, msg):
        print('Started encryption')
        # MD5(M)
        print('\tCalculating md5')
        md5_hash = md5.md5sum(msg)
        m = int(md5_hash, 16)

        # MD5(M) -> S
        print('\tGenerating signature')
        sign = rsa.decrypt(m, self.sender.pri_key)
        sign = '{:01024b}'.format(sign)
        sign = sign.encode('utf-8')

        # <M, S> -> ZIP(M, S)
        print('\tCompressing')
        new_msg = msg
        for i in range(int(len(sign) / 8)):
            tmp = sign[i * 8:i * 8 + 8]
            data = int(tmp, 2)
            data = bytes([data])
            new_msg = new_msg + data
        new_msg = self.compressor.compress(new_msg).tobytes()

        # IDEA(ZIP(M, S))
        print('\tEncrypting compressed data')
        idea_key = 0x4AD6459F82C5B300952C49104881EF51
        idea_msg = IDEA.IDEA_en(new_msg, idea_key)

        # RSA(k)
        print('\tEncrypting key')
        rsa_key = rsa.encrypt(idea_key, self.receiver.pub_key)
        rsa_key = '{:01024b}'.format(rsa_key)
        rsa_key = rsa_key.encode('utf-8')

        # <IDEA(ZIP(M, S)), RSA(k)>
        print('\tConcatenating')
        data_part = idea_msg
        for i in range(int(len(rsa_key) / 8)):
            tmp = rsa_key[i * 8:i * 8 + 8]
            data = int(str(tmp, encoding='utf8'), 2)  # bytes->str->int
            data = bytes([data])  # int->bytes
            data_part = data_part + data
        result = base_64.encode(data_part)
        print('Done!')
        return result
コード例 #5
0
def key_hash(password):
    key = md5sum(password)
    key += md5sum(key)
    return bytes.fromhex(key)
コード例 #6
0
ファイル: PGP_main.py プロジェクト: universuen/Cryptography
import md5
import rsa
import IDEA
import base_64
import zipstream

if __name__ == '__main__':
    # 读取文件
    fp = open(
        "../../../Documents/Tencent Files/2498537532/FileRecv/ys168.com.txt",
        "rb")
    msg = fp.read()
    fp.close()
    '''****************加密过程*******************'''
    '''1. 对M进行MD5散列计算,得到MD5(M)'''
    md5_hash = md5.md5sum(msg)
    '''2.利用RSA加密MD5(M),得到S'''
    # 公钥私钥中用到的两个大质数p,q,都是512位;e是和(q-1)*(p-1)互质的另一个正整数
    p1 = 11892845164754857302192817993787160730215019683720078508868206227442930130722825064091815998764273410046313495341034135557819502333338074415976198866323473
    q1 = 11367670600867484708699649015361923450974263455941875059545547729179804359361891954089186046814453092650085798107044468298400840193141395710340815439355097
    e1 = 611

    # 1是发送者,2是接收者
    # 生成发送者公钥私钥
    pubkey_1, selfkey_1 = rsa.gen_key(p1, q1, e1)

    # 把hash值:十六进制->十进制
    m = int(md5_hash, 16)
    # 用发送者的私钥对hash进行加密得到签名S
    S = rsa.decrypt(m, selfkey_1)
    # 签名S共1024位,不足的高位补0
コード例 #7
0
    # 一维转二维
    @classmethod
    def one_dimensional_to_two_dimensional(cls, vector, row, col):
        matrix = vector.reshape(row, col)
        for i in range(row):
            if i % 2 == 1:
                matrix[i] = matrix[i][::-1]
        return matrix


if __name__ == '__main__':
    path = file_name = "D:\\Documents\\codeFiles\\Python3\GraphCompress\\4.jpg"

    app = wx.App()
    frame = GuageFrame(file_name + '.jpg')
    # frame.Show()
    # 创建线程,设定延迟加载时间及间隔执行时间
    _thread.start_new_thread(frame.timer, (0.5, ))
    app.MainLoop()

    UnCompress.uncompress(file_name + ".compress")
    print(
        md5.md5sum(file_name + '.bmp') == md5.md5sum(file_name +
                                                     '_UnCompress.bmp'))
    img1 = cv2.imread(file_name + '.bmp')
    img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
    img2 = cv2.imread(file_name + '_UnCompress.bmp')
    img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
    print(img1 == img2)