【亲测有效】RSA标准加密解密,高强度秘钥4096确保万无一失
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()
打印输出:
文件情况,生成私钥公钥文件:
私钥内容:
公钥内容:
代码学习,前言技术分享,深度分析编程技术,普及科普编程技术,天天都要敲代码
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)