RSA标准加密解密,高强度秘钥4096确保万无一失
上代码:
#pip install cryptography
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
# 生成RSA密钥对
def generate_rsa_keypair():
# 生成私钥
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=4096,
)
# 生成公钥
public_key = private_key.public_key()
return private_key, public_key
# 将密钥保存到文件
def save_key_to_file(key, filename, is_private=True):
pem = key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption()
) if is_private else key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
with open(filename, 'wb') as f:
f.write(pem)
# 从文件加载密钥
def load_key_from_file(filename, is_private=True):
with open(filename, 'rb') as f:
key_data = f.read()
if is_private:
return serialization.load_pem_private_key(
key_data,
password=None
)
else:
return serialization.load_pem_public_key(
key_data
)
# 加密
def encrypt_message(public_key, message):
ciphertext = public_key.encrypt(
message,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
return ciphertext
# 解密
def decrypt_message(private_key, ciphertext):
plaintext = private_key.decrypt(
ciphertext,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
return plaintext
# 示例使用
def main():
# 生成密钥对
private_key, public_key = generate_rsa_keypair()
# 保存密钥到文件
save_key_to_file(private_key, 'private_key.pem', is_private=True)
save_key_to_file(public_key, 'public_key.pem', is_private=False)
print(f"private_key: {private_key}")
print(f"private_key: {private_key.key_size}")
pem = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption()
)
print(f"private_key pem: {pem}")
print(f"public_key: {public_key}")
# 加载密钥
private_key = load_key_from_file('private_key.pem', is_private=True)
public_key = load_key_from_file('public_key.pem', is_private=False)
# 示例消息
message = b"HelloWorld, RSA Encryption!"
print(f"Original message: {message}")
# 加密消息
ciphertext = encrypt_message(public_key, message)
print(f"Ciphertext: {ciphertext}")
# 解密消息
decrypted_message = decrypt_message(private_key, ciphertext)
print(f"Decrypted message: {decrypted_message}")
if __name__ == "__main__":
main()
打印输出:
文件情况,生成私钥公钥文件:
私钥内容:
公钥内容: