python rsa模块_Python密码模块将RSA密钥保存/加载到/从fi

我想将生成的私钥保存在一个文件中,以便以后使用。

但从文件中我找不到这需要的方法。from cryptography.hazmat.backends import default_backend

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

# Working RSA encryption you can run for yourself

MESSAGE = 'I am a very secret message'

# Create private key

private_key = rsa.generate_private_key(

public_exponent=65537,

key_size=2048,

backend=default_backend()

)

# Create public key

public_key = private_key.public_key()

# Encrypt

ciphertext = public_key.encrypt(

MESSAGE,

padding.OAEP(

mgf=padding.MGF1(algorithm=hashes.SHA1()),

algorithm=hashes.SHA1(),

label=None

)

)

# Encrypted text

print ciphertext

# Decrypt

plaintext = private_key.decrypt(

ciphertext,

padding.OAEP(

mgf=padding.MGF1(algorithm=hashes.SHA1()),

algorithm=hashes.SHA1(),

label=None

)

)

# Decrypted text

print plaintext

# Print human readable key

pem = private_key.private_bytes(

encoding=serialization.Encoding.PEM,

format=serialization.PrivateFormat.TraditionalOpenSSL,

encryption_algorithm=serialization.NoEncryption()

)

pem_data = pem.splitlines()

print pem_data

# How to Save//Load

我知道如何生成密钥,但如何将其正确保存到文件中。只需将pem_data存储在一个文件中,然后使用

load_pem_public_key?

由于加密对我来说还是新的,所以我想知道如何在文件中存储RSA密钥。

这是我当前的尝试,但出现错误。

ValueError: Could not deserialize key data.if os.path.exists('key.pem'):

print 'file exist'

else:

f = open(os.path.join(__location__, 'key.pem'), 'w')

for i in pem_data:

f.write(i)

f.close()

with open(os.path.join(__location__, 'key.pem'), "rb") as key_file:

private_key = serialization.load_pem_private_key(

key_file.read(),

password=None,

backend=default_backend()

)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值