700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > Python:cryptography私钥公钥生成 序列化 加密解密 签名验签

Python:cryptography私钥公钥生成 序列化 加密解密 签名验签

时间:2020-01-09 00:26:07

相关推荐

Python:cryptography私钥公钥生成 序列化 加密解密 签名验签

cryptography is a package designed to expose cryptographic primitives and recipes to Python developers.

译文:cryptography是一个旨在向Python开发人员公开加密原语和配方的包。

目录

文档安装示例1、生成私钥和获取公钥2、私钥和公钥序列化3、私钥和公钥的反序列化4、公钥加密私钥解密5、私钥签名公钥验签 源码RSAPrivateKey源码 RSAPublicKey源码

文档

/pyca/cryptography/project/cryptography/https://cryptography.io/en/latest/https://cryptography.io/en/latest/hazmat/primitives/asymmetric/rsa/

安装

pip install cryptography

示例

1、生成私钥和获取公钥

# -*- coding: utf-8 -*-from cryptography.hazmat.backends import default_backendfrom cryptography.hazmat.primitives import serializationfrom cryptography.hazmat.primitives.asymmetric import rsa# 生成私钥private_key = rsa.generate_private_key(public_exponent=65537,key_size=2048,backend=default_backend())# 获取公钥public_key = private_key.public_key()

2、私钥和公钥序列化

# 私钥序列化private_key_pem = private_key.private_bytes(encoding=serialization.Encoding.PEM,format=serialization.PrivateFormat.PKCS8,encryption_algorithm=serialization.NoEncryption())# 保存私钥到文件with open('private.key', 'wb') as f:f.write(private_key_pem)# 公钥序列化public_key_pem = public_key.public_bytes(encoding=serialization.Encoding.PEM,format=serialization.PublicFormat.SubjectPublicKeyInfo)# 保存公钥到文件with open('public.pem', 'wb') as f:f.write(public_key_pem)

3、私钥和公钥的反序列化

from cryptography.hazmat.backends import default_backendfrom cryptography.hazmat.primitives import serialization# 从文件加载私钥with open("private.key", "rb") as private_key_file:private_key = serialization.load_pem_private_key(private_key_file.read(),password=None,backend=default_backend())# 从文件加载公钥with open("public.pem", "rb") as public_pem_file:public_key = serialization.load_pem_public_key(public_pem_file.read(),backend=default_backend())

4、公钥加密私钥解密

from cryptography.hazmat.backends import default_backendfrom cryptography.hazmat.primitives import serializationfrom cryptography.hazmat.primitives import hashesfrom cryptography.hazmat.primitives.asymmetric import padding# 公钥解密message = 'Hello'encrypted = public_key.encrypt(plaintext=message.encode('utf-8'),padding=padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),algorithm=hashes.SHA256(),label=None))print(encrypted)# b'm\xf2\x8d\xa84\xbe\x13\xe1...'# 私钥解密original_message = private_key.decrypt(ciphertext=encrypted,padding=padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),algorithm=hashes.SHA256(),label=None))print(original_message.decode('utf-8'))# Hello

5、私钥签名公钥验签

# -*- coding: utf-8 -*-from cryptography.hazmat.backends import default_backendfrom cryptography.hazmat.primitives import serializationfrom cryptography.hazmat.primitives import hashesfrom cryptography.hazmat.primitives.asymmetric import padding# 私钥签名message = 'Hello'signature = private_key.sign(data=message.encode('utf-8'),padding=padding.PSS(mgf=padding.MGF1(hashes.SHA256()),salt_length=padding.PSS.MAX_LENGTH),algorithm=hashes.SHA256())print(signature)# b'm\xf2\x8d\xa84\xbe\x13\xe1...'# 公钥验签 如果验证失败抛出异常cryptography.exceptions.InvalidSignaturepublic_key.verify(signature=signature,data='Hello'.encode('utf-8'),padding=padding.PSS(mgf=padding.MGF1(hashes.SHA256()),salt_length=padding.PSS.MAX_LENGTH),algorithm=hashes.SHA256())

源码

RSAPrivateKey源码

cryptography/hazmat/primitives/asymmetric/rsa.py

class RSAPrivateKey(metaclass=abc.ABCMeta):@abc.abstractmethoddef decrypt(self, ciphertext: bytes, padding: AsymmetricPadding) -> bytes:"""Decrypts the provided ciphertext."""@abc.abstractpropertydef key_size(self) -> int:"""The bit length of the public modulus."""@abc.abstractmethoddef public_key(self) -> "RSAPublicKey":"""The RSAPublicKey associated with this private key."""@abc.abstractmethoddef sign(self,data: bytes,padding: AsymmetricPadding,algorithm: typing.Union[asym_utils.Prehashed, hashes.HashAlgorithm],) -> bytes:"""Signs the data."""@abc.abstractmethoddef private_numbers(self) -> "RSAPrivateNumbers":"""Returns an RSAPrivateNumbers."""@abc.abstractmethoddef private_bytes(self,encoding: _serialization.Encoding,format: _serialization.PrivateFormat,encryption_algorithm: _serialization.KeySerializationEncryption,) -> bytes:"""Returns the key serialized as bytes."""

RSAPublicKey源码

cryptography/hazmat/primitives/asymmetric/rsa.py

class RSAPublicKey(metaclass=abc.ABCMeta):@abc.abstractmethoddef encrypt(self, plaintext: bytes, padding: AsymmetricPadding) -> bytes:"""Encrypts the given plaintext."""@abc.abstractpropertydef key_size(self) -> int:"""The bit length of the public modulus."""@abc.abstractmethoddef public_numbers(self) -> "RSAPublicNumbers":"""Returns an RSAPublicNumbers"""@abc.abstractmethoddef public_bytes(self,encoding: _serialization.Encoding,format: _serialization.PublicFormat,) -> bytes:"""Returns the key serialized as bytes."""@abc.abstractmethoddef verify(self,signature: bytes,data: bytes,padding: AsymmetricPadding,algorithm: typing.Union[asym_utils.Prehashed, hashes.HashAlgorithm],) -> None:"""Verifies the signature of the data."""@abc.abstractmethoddef recover_data_from_signature(self,signature: bytes,padding: AsymmetricPadding,algorithm: typing.Optional[hashes.HashAlgorithm],) -> bytes:"""Recovers the original data from the signature."""

参考文章

使用cryptography进行RSA加密

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。