要从PEM文件加载RSA密钥并在Python中使用它,您需要使用cryptography
库。首先,确保您已经安装了cryptography
库。如果没有,请使用以下命令安装:
pip install cryptography
接下来,您可以使用以下代码从PEM文件加载RSA密钥:
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.backends import default_backend
# 将此路径替换为您的PEM文件的路径
pem_file_path = "path/to/your/pem/file.pem"
# 加载私钥
with open(pem_file_path, "rb") as key_file:
private_key = serialization.load_pem_private_key(
key_file.read(),
password=None,
backend=default_backend()
)
# 加载公钥
with open(pem_file_path, "rb") as key_file:
public_key = serialization.load_pem_public_key(
key_file.read(),
backend=default_backend()
)
现在,您可以使用private_key
和public_key
对象执行加密和解密操作。例如,使用私钥加密,公钥解密:
# 使用私钥加密
plaintext = b"Hello, world!"
ciphertext = private_key.encrypt(
plaintext,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
# 使用公钥解密
plaintext = public_key.decrypt(
ciphertext,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
print(plaintext)
这个例子使用了OAEP
填充模式,它是一种常用的加密填充模式。您可以根据需要选择其他填充模式。
领取专属 10元无门槛券
手把手带您无忧上云