在用包cryptography进行非对称加密时, 生成公钥的函数异常.
标签:str,cryptography,key,instead,geted,type,public,PublicFormat From: https://www.cnblogs.com/tslam/p/17989884
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
# 生成RSA密钥对
def generate_rsa_key_pair():
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048, # 一般是1024位,重要场合是2048位。
backend=default_backend()
)
public_key = private_key.public_key()
return private_key, public_key
private_key, public_key = generate_rsa_key_pair()
def get_public_key():
geted_public_key = public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
).decode('utf-8')
return geted_public_key
"""
上面的代码块在PyCharm中下面两行
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
异常: Expected type 'PublicFormat', got 'str' instead
原因: 当时用的cryptography==1.9, cryptography版本太低, 换了一个高版本好了
"""
geted_public_key = get_public_key()
print(f'geted_public_key:\n{geted_public_key}, type:{type(geted_public_key)}')