随着互联网的迅速发展,信息安全变得尤为重要。数据加密是一个必不可少的环节。有时候,我们一不留神,可能数据就被人窃听到。今天跟大家分享一个数据加密的小案例。
今天我们将会用到pycrypto
模块,该模块支持的加密方式如下:
1、对称加密方式
- AES
- DES
- ARC4
2、散列值计算:
- MD5
- SHA
- HMAC
3、公钥加密和签名:
- RSA
- DSA
使用之前先安装扩展包,执行如下命令
pip install pycrypto
下面通过过一个小案例,简单介绍pycrypto
这个库的使用。
from Crypto import Random
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5
from Crypto.PublicKey import RSA
import base64
basedir = os.path.abspath(os.path.dirname(__file__))
def create_rsa_key():
rsa = RSA.generate(1024)
#生成密钥对
private_pem = rsa.exportKey()
with open('private.pem', 'wb') as f:
f.write(private_pem)
public_pem = rsa.publickey().exportKey()
with open('public.pem', 'wb') as f:
f.write(public_pem)
#加密函数
def encrypt(message):
with open(os.path.join(basedir,'public.pem')) as f:
key = f.read()
rsakey = RSA.importKey(str(key))
cipher = Cipher_pkcs1_v1_5.new(rsakey)
cipher_text = base64.b64encode(cipher.encrypt(bytes(message.encode("utf8"))))
return cipher_text
#解密函数
def decrypt(cipher_text):
random_generator = Random.new().read
with open(os.path.join(basedir,'private.pem')) as f:
key = f.read()
rsakey = RSA.importKey(key)
cipher = Cipher_pkcs1_v1_5.new(rsakey)
text = cipher.decrypt(base64.b64decode(cipher_text), random_generator)
return str(text,"utf-8")
if __name__ == "__main__":
cipher_text= encrypt('nomore532')
print(cipher_text)
print(decrypt(cipher_text=cipher_text))