Exemplo n.º 1
0
def file_decrypt(encrypted_filepath, key_encrypted, iv_encrypted):
    """
    对文件进行解密
    :param encrypted_file_path: 加密文件的路径
    :param key_encrypted: 加密的密钥
    :param iv_encrypted: 加密的iv
    :return: 解密后文件路径, 解密后文件的md5
    """
    # 先用server的私钥对key和iv进行解密
    key = RSA.Decrypto(key_encrypted, client_d, client_n)
    iv = RSA.Decrypto(iv_encrypted, client_d, client_n)
    # 打开并读取加密文件
    encrypted_file = open(encrypted_filepath, 'rb')
    encrypted_filedata = encrypted_file.read().decode('latin')
    # 去掉.crypted后缀
    origin_filepath = ".".join(encrypted_filepath.split('.')[:-1])
    # 将解密后的内容写入新文件
    origin_file = open(origin_filepath, 'wb')
    origin_file.write(
        DES.des_cbc_decrypt(encrypted_filedata, libnum.n2s(key),
                            libnum.n2s(iv)).encode('latin'))
    # 关闭文件指针
    encrypted_file.close()
    origin_file.close()
    # 计算解密后文件的md5消息摘要
    origin_file_digest = get_file_md5(origin_filepath)
    return origin_filepath, origin_file_digest
Exemplo n.º 2
0
def file_encrypt(filepath):
    """
    对文件进行DES-CBC加密,并用RSA加密key和iv
    :param filepath: 原文件路径
    :return: 加密文件路径, 原文件md5值, 加密后的key, 加密后的iv
    """
    # 随机生成key和iv
    key, iv = get_des_param()
    # 打开原文件
    origin_file = open(filepath, 'rb')
    origin_filedata = origin_file.read().decode('latin')
    # 计算原文件的消息摘要
    origin_digest = md5(origin_filedata)
    # 加密后文件的地址(统一加上.encrypted后缀)
    encrypted_filepath = filepath + ".encrypted"
    # 写入加密文件
    encrypted_file = open(encrypted_filepath, 'wb')
    encrypted_file.write(
        DES.des_cbc_encrypt(origin_filedata, key, iv).encode('latin'))
    # 关闭文件
    origin_file.close()
    encrypted_file.close()
    # 用client的公钥对key和iv进行加密
    key_encrypted = RSA.Encrypt(libnum.s2n(key), server_e, server_n)
    iv_encrypted = RSA.Encrypt(libnum.s2n(iv), server_e, server_n)
    return encrypted_filepath, origin_digest, key_encrypted, iv_encrypted
Exemplo n.º 3
0
def transfer_encrypt(message):
    """
    对分组传输的每一个分组进行des_cbc加密,且每次使用不同的key和iv
    :param message: 被加密的分组
    :return: key,iv,cipher
    """
    key, iv = get_des_param()
    cipher = DES.des_cbc_encrypt(message, key, iv, 'b')
    # 用server的公钥对key和iv进行加密
    key_encrypted = RSA.Encrypt(libnum.s2n(key), server_e, server_n)
    iv_encrypted = RSA.Encrypt(libnum.s2n(iv), server_e, server_n)
    return key_encrypted, iv_encrypted, cipher
Exemplo n.º 4
0
def transfer_decrypt(cipehr, key_encrypted, iv_encrypted):
    """
    对接收到的每一个分组进行解密
    :param cipehr: 收到的加密分组
    :param key_encrypted: 收到的加密过的key
    :param iv_encrypted: 收到的加密过的iv
    :return: 明文
    """
    # 先用client的私钥对key和iv进行解密
    key = RSA.Decrypto(key_encrypted, client_d, client_n)
    iv = RSA.Decrypto(iv_encrypted, client_d, client_n)
    # 用key和iv对收到的密文分组解密
    message = DES.des_cbc_decrypt(cipehr, libnum.n2s(key), libnum.n2s(iv), 'b')
    return message