1. 安装cryptography
python -m pip install cryptography
使用时import该库,或该库中的一个模块
import cryptography
from cryptography.hazmat.primitives import serialization
2.生成一个秘钥,并保存
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
# call rsa.generate_private_key
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
backend=default_backend()
)
public_key = private_key.public_key()
# store private key
pem = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption()
)
with open('private_key.pem', 'wb') as f:
f.write(pem)
# stroe public key
pem = public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
with open('public_key.pem', 'wb') as f:
f.write(pem)
非对称加密,一般公钥发布出去,私钥自己保管,防止私钥泄露。
3. 从文件读取秘钥
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
with open("private_key.pem", "rb") as key_file:
private_key = serialization.load_pem_private_key(
key_file.read(),
password=None,
backend=default_backend()
)
如果保存密钥时设置了密码,这里读取时,password要设置
公钥读取类似
4. 加密
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
message = b'encrypt me!'
public_key = ... # Use one of the methods above to get your public key
encrypted = public_key.encrypt(
message,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
RSA是一种非对称加密算法, 同一个明文, 相同公钥,两次加密得到的结果可能不一样。
5. 解密
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
encrypted = ... # From before (could have been stored then read back here)
private_key = ... # Use one of the methods above to get your public key (matches the public_key)
original_message = private_key.decrypt(
encrypted,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
Ref:
https://blog.csdn.net/wjiabin/article/details/85228078
https://nitratine.net/blog/post/asymmetric-encryption-and-decryption-in-python/#encrypting