python 第三方库 crypto

crypto导入报错问题解决记录

安装没有什么问题,不管哪一个实际上都是crypto,这个库似乎有点特殊

from Crypto.PublicKey import RSA

如果显示导入报错,别急

先卸载安装过的所有的crypto模块,pip list,看一看带crypto名字的,全都pip uninstall xxx

全部卸载干净后:pip install pycryptodome

一定要全部卸载后,如果已经安装过pycryptodome,也要卸载,不然依然报错。必须卸载完所有安装的crypto模块,最后安装pycryptodome

补充

网上大部分都是重命名的方案,把crypto大小写重新改名,个人认为对于第三方库,最好不要做修改,哪怕是这种很小的改动。

如何使用 (RSA)

代码如下:

如果使用过linux操作系统的人一定对于密钥的生成不陌生,ssh-keygen,生成密钥,用于免密登录。

代码先生成一对密钥,然后使用这对密钥进行加密和解密。这里要提一下对称加密和非对称加密。

从安全性上来考虑,非对称加密>对称加密,RSA 是非对称加密,AES 是对称加密,安全性高并不意味着好,越高的安全性意味着越低的效率,不过在低数据量下,二者差别不大,所以可以按需使用。最佳的方式就是用 RSA 加密 AES 密钥,AES 加密信息,这样的话就发挥了两者的优势。

RSA,bits越高越安全,但同时也意味着低效率,这里使用2048,实际体验时候可以试试4096。

import os.path

from Crypto.Cipher import PKCS1_OAEP
from Crypto.PublicKey import RSA

def generate_key(_public_path,_private_path,bits=2048):
    if os.path.exists(_public_path) and os.path.exists(_private_path):
        return
    # if os.path.exists(_private_path):
    #     os.remove(_private_path)
    # if os.path.exists(_public_path):
    #     os.remove(_public_path)
    private_key = RSA.generate(bits=bits)
    with open(_public_path, "wb") as f:
        f.write(private_key.publickey().export_key())
    with open(_private_path, "wb") as f:
        f.write(private_key.export_key())

def encryption_decryption(_public_path, _private_path, _message = u"你好,我的全世界!"):
    bytes_message = bytes(_message, encoding ="utf-8")
    with open (_public_path,"rb") as f:
        _public_key = RSA.importKey(f.read())
    cipher = PKCS1_OAEP.new(_public_key)
    encrypted_message = cipher.encrypt(bytes_message)
    print(f"加密后的数据:{encrypted_message}")
    
    with open (_private_path,"rb") as f:
        _private_key = RSA.importKey(f.read())
    cipher = PKCS1_OAEP.new(_private_key)
    decrypted_message = cipher.decrypt(encrypted_message)
    print(f'解密后的数据:{decrypted_message.decode("utf-8")}')

if __name__ == '__main__':
    key_dir = os.path.dirname(__file__) # 当前文件的文件夹路径
    private_path = os.path.join(key_dir,"id_rsa")
    public_path = os.path.join(key_dir,"id_rsa.pub")
    generate_key(_public_path=public_path,_private_path=private_path,bits=2048)
    encryption_decryption(_public_path=public_path,_private_path=private_path)

如何使用 (AES)

一个小Demo:

import os.path
from os import urandom

from Crypto.Cipher import PKCS1_OAEP, AES
from Crypto.PublicKey import RSA

def my_aes():
    secret_key = urandom(16)
    iv = urandom(16)
    _aes = AES.new(secret_key,AES.MODE_CBC, iv)
    message = "Hello World     "
    bytes_message = bytes(message,encoding="utf-8")
    print(f"加密前:{message}")
    encrypted_text = _aes.encrypt(bytes_message)
    _aes = AES.new(secret_key, AES.MODE_CBC, iv)
    print(f"加密后:{encrypted_text}")
    decrypted_text = _aes.decrypt(encrypted_text)
    print(f"解密后:{decrypted_text.decode('utf-8')}")
    
if __name__ == '__main__':
    my_aes()

上面的例子是非常简单的,但是其实有很多问题,例如,加密消息并不是,“你好,我的全世界!”,加密消息后面有好几个空格,_aes 出现了两次。

加密文件(Demo)

import os
from hashlib import md5
from Crypto.Cipher import AES
from os import urandom

def derive_key_and_iv(password, salt, key_length, iv_length): #derive key and IV from password and salt.
    d = d_i = b''
    while len(d) < key_length + iv_length:
        d_i = md5(d_i + str.encode(password) + salt).digest() #obtain the md5 hash value
        d += d_i
    return d[:key_length], d[key_length:key_length+iv_length]

def encrypt(in_file, out_file, password, key_length=32):
    bs = AES.block_size #16 bytes
    salt = urandom(bs) #return a string of random bytes
    key, iv = derive_key_and_iv(password, salt, key_length, bs)
    cipher = AES.new(key, AES.MODE_CBC, iv)
    out_file.write(salt)
    finished = False

    while not finished:
        chunk = in_file.read(1024 * bs)
        if len(chunk) == 0 or len(chunk) % bs != 0:#final block/chunk is padded before encryption
            padding_length = (bs - len(chunk) % bs) or bs
            chunk += str.encode(padding_length * chr(padding_length))
            finished = True
        out_file.write(cipher.encrypt(chunk))

def decrypt(in_file, out_file, password, key_length=32):
    bs = AES.block_size
    salt = in_file.read(bs)
    key, iv = derive_key_and_iv(password, salt, key_length, bs)
    cipher = AES.new(key, AES.MODE_CBC, iv)
    next_chunk = ''
    finished = False
    while not finished:
        chunk, next_chunk = next_chunk, cipher.decrypt(in_file.read(1024 * bs))
        if len(next_chunk) == 0:
            padding_length = chunk[-1]
            chunk = chunk[:-padding_length]
            finished = True
        out_file.write(bytes(x for x in chunk))


password = '123456789' # 你应该使用强度高的密码

with open("origin.txt","w+",encoding="utf-8") as f:
    f.write("你好,我的全世界!")

with open('origin.txt', 'rb') as in_file, open('encrypt_origin.txt', 'wb') as out_file:
    encrypt(in_file, out_file, password)

with open('encrypt_origin.txt', 'rb') as in_file, open('decrypt_origin.txt', 'wb') as out_file:
    decrypt(in_file, out_file, password)
    
is_delete = False
if is_delete:
    files = ['origin.txt','encrypt_origin.txt','decrypt_origin.txt']
    for file in files:
        os.remove(file)

AES 参考

如果需要详细了解,请参考:https://www.cnblogs.com/Hellowshuo/p/15706590.html

该博主写的非常详细,可以帮助答疑解惑

  • 6
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值