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源码

文档

  • https://github.com/pyca/cryptography
  • https://pypi.org/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_backend
from cryptography.hazmat.primitives import serialization
from 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_backend
from 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_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives import hashes
from 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_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives import hashes
from 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.InvalidSignature
public_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.abstractmethod
    def decrypt(self, ciphertext: bytes, padding: AsymmetricPadding) -> bytes:
        """
        Decrypts the provided ciphertext.
        """

    @abc.abstractproperty
    def key_size(self) -> int:
        """
        The bit length of the public modulus.
        """

    @abc.abstractmethod
    def public_key(self) -> "RSAPublicKey":
        """
        The RSAPublicKey associated with this private key.
        """

    @abc.abstractmethod
    def sign(
        self,
        data: bytes,
        padding: AsymmetricPadding,
        algorithm: typing.Union[asym_utils.Prehashed, hashes.HashAlgorithm],
    ) -> bytes:
        """
        Signs the data.
        """

    @abc.abstractmethod
    def private_numbers(self) -> "RSAPrivateNumbers":
        """
        Returns an RSAPrivateNumbers.
        """

    @abc.abstractmethod
    def 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.abstractmethod
    def encrypt(self, plaintext: bytes, padding: AsymmetricPadding) -> bytes:
        """
        Encrypts the given plaintext.
        """

    @abc.abstractproperty
    def key_size(self) -> int:
        """
        The bit length of the public modulus.
        """

    @abc.abstractmethod
    def public_numbers(self) -> "RSAPublicNumbers":
        """
        Returns an RSAPublicNumbers
        """

    @abc.abstractmethod
    def public_bytes(
        self,
        encoding: _serialization.Encoding,
        format: _serialization.PublicFormat,
    ) -> bytes:
        """
        Returns the key serialized as bytes.
        """

    @abc.abstractmethod
    def verify(
        self,
        signature: bytes,
        data: bytes,
        padding: AsymmetricPadding,
        algorithm: typing.Union[asym_utils.Prehashed, hashes.HashAlgorithm],
    ) -> None:
        """
        Verifies the signature of the data.
        """

    @abc.abstractmethod
    def recover_data_from_signature(
        self,
        signature: bytes,
        padding: AsymmetricPadding,
        algorithm: typing.Optional[hashes.HashAlgorithm],
    ) -> bytes:
        """
        Recovers the original data from the signature.
        """

参考文章

    1. 使用cryptography进行RSA加密

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
扎眼的阳光的头像扎眼的阳光普通用户
上一篇 2023年11月28日
下一篇 2023年11月28日

相关推荐