python模块 — cryptography

1、cryptography模块

cryptography模块是Python中用于密码学操作的核心模块。它提供了各种密码学算法、密钥生成、加密、解密、签名和验证等功能。

官网地址:cryptography · PyPI

版本要求:Python 3.7+

安装:pip install cryptography

文档:Welcome to pyca/cryptography — Cryptography 42.0.0.dev1 documentation

以下是cryptography模块的核心模块:

  • `cryptography.hazmat.primitives`:该模块包含了密码学原语(primitives),如散列函数、对称加密、非对称加密、消息认证码等。这些原语供开发人员直接使用。
  • `cryptography.hazmat.primitives.asymmetric`:该模块包含了非对称加密相关的原语,如RSA、椭圆曲线加密(ECC)等。
  • `cryptography.hazmat.primitives.symmetric`:该模块包含了对称加密相关的原语,如AES、DES等。
  • `cryptography.hazmat.primitives.hashes`:该模块包含了各种散列函数,如SHA-256、SHA-512、MD5等。
  • `cryptography.hazmat.primitives.serialization`:该模块包含了序列化和反序列化密码学对象的功能,如将私钥、公钥和证书转换为不同格式的字节字符串。
  • `cryptography.hazmat.primitives.padding`:该模块包含了各种填充方案,用于在加密和解密数据时填充数据块。
  • `cryptography.hazmat.primitives.ciphers`:该模块包含了低级别的加密原语,如AES、DES等加密算法的底层接口。
  •  `cryptography.hazmat.primitives.keywrap`:该模块包含了对称密钥包装和解包装的功能,用于加密和解密对称密钥。

2、生成秘钥

2.1 生成私钥

在cryptography模块中,使用cryptography.hazmat.primitives.asymmetric.rsa模块的generate_private_key()方法生成了一个RSA私钥对象。

语法格式:

def generate_private_key(
    public_exponent: int, key_size: int, backend=None
) -> RSAPrivateKey

参数说明:

  • `public_exponent`:公钥指数,是RSA算法中公钥的一部分,通常选择一个固定的值,如65537(即0x10001)。这是一个安全且常见的选项。
  • `key_size`:密钥长度,用于确定生成的RSA私钥的强度,即位数。常见的密钥长度包括2048、3072和4096等。较长的密钥长度提供更大的安全性,但也需要更长的加密和解密时间。
  • `backend`:可选参数,默认值为 `None`,这个参数用于指定加密库的后端实现。如果不提供后端参数,默认情况下将使用适当的后端。
  • 返回值:`RSAPrivateKey`,这是 `cryptography.hazmat.primitives.asymmetric.rsa` 模块中表示RSA私钥的类。

以下是一个使用`generate_private_key()`方法的示例:

from cryptography.hazmat.primitives.asymmetric import rsa

# 生成RSA私钥
private_key = rsa.generate_private_key(
    public_exponent=65537,
    key_size=2048
)

在上面的示例中,`generate_private_key()`方法生成了一个RSA私钥对象。我们使用参数`public_exponent=65537`和`key_size=2048`来定义生成的私钥的公钥指数和密钥长度。

注意,私钥是非常敏感的信息,需要妥善保管,并在必要时进行严格的访问控制。

2.2 生成公钥

在`cryptography`库中,可以通过私钥生成对应的公钥。公钥可以通过私钥对象的`public_key()`方法获得公钥对象。

语法格式:

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

以下是使用私钥对象的'public_key()'方法生成公钥的示例代码:

from cryptography.hazmat.primitives.asymmetric import rsa

# 生成RSA私钥
private_key = rsa.generate_private_key(
    public_exponent=65537,
    key_size=2048,
)

# 生成RSA公钥
public_key = private_key.public_key()

在上述示例中,我们使用私钥对象的`public_key()`方法获得了对应的公钥对象。

注意,私钥和公钥配对使用,私钥用于加密和签名,而公钥用于解密和验证签名。私钥是敏感信息,需要妥善保管,不应泄露给他人。公钥可以公开传播给其他人,以便其他人使用。

3、保存秘钥

将生成的秘钥序列化成字节序列,然后保存成pem格式。

3.1 序列化私钥

在cryptography库中,可以使用serialization模块中的'private_bytes()'函数将私钥序列化为字节流表示。

语法格式:

    def private_bytes(
        self,
        encoding: _serialization.Encoding,
        format: _serialization.PrivateFormat,
        encryption_algorithm: _serialization.KeySerializationEncryption,
    ) -> bytes:
        """
        Returns the key serialized as bytes.
        """

参数说明:

`encoding`:编码,这个参数用于指定私钥在序列化时使用的编码方式。`_serialization.Encoding` 是一个枚举类,常用的取值包括:
       - `PEM`:使用 Base64 编码将私钥序列化为文本格式。
       - `DER`:将私钥序列化为二进制格式。

`format`:秘钥格式,这个参数用于指定私钥序列化时的格式。`_serialization.PrivateFormat` 是一个枚举类,常用的取值包括:
        -`PKCS8`:使用 PKCS#8 格式序列化私钥。
        -`TraditionalOpenSSL`:使用传统的 OpenSSL 格式序列化私钥。

`encryption_algorithm`:加密算法,这个参数用于指定是否对私钥进行加密。`_serialization.KeySerializationEncryption` 是一个枚举类,常用的取值包括:
        -`NoEncryption`:不对私钥进行加密,私钥将以明文形式序列化。
        -`BestAvailableEncryption`:使用可用的最佳加密算法对私钥进行加密。

返回值:`bytes`:私钥序列化后的字节流表示。

以下是将私钥序列化为字节流的示例代码:

from cryptography.hazmat.primitives import serialization

# 假设私钥对象为 private_key

# 将私钥使用 PEM 格式序列化为文本格式
private_key_bytes = private_key.private_bytes(
    encoding=serialization.Encoding.PEM,
    format=serialization.PrivateFormat.PKCS8,
    encryption_algorithm=serialization.NoEncryption()
)

print(private_key_bytes)

在上述示例中,我们使用 `private_bytes()` 方法将私钥序列化为字节流表示。我们指定了参数 `encoding` 为 `PEM`,`format` 为 `PKCS8`,`encryption_algorithm` 为 `NoEncryption`,表示不对私钥进行加密。通过打印 `private_key_bytes` 可以查看私钥的字节流表示。

3.2 序列化公钥

在`cryptography`库中,可以使用serialization模块中的`public_bytes()`函数将公钥序列化为字节流表示。

语法格式:

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

参数说明:

 `encoding`:编码,这个参数用于指定序列化公钥时使用的编码方式。`_serialization.Encoding` 是一个枚举类,常用的取值包括:
   - `PEM`:使用 Base64 编码将公钥序列化为文本格式。
   - `DER`:将公钥序列化为二进制格式。

`format`:公钥格式,这个参数用于指定公钥序列化时的格式。`_serialization.PublicFormat` 是一个枚举类,常用的取值包括:
   - `SubjectPublicKeyInfo`:SubjectPublicKeyInfo是PKCS#8格式中用于表示公钥的一种结构。

返回值:`bytes`:公钥序列化后的字节流表示。

以下是将公钥序列化为字节流的示例代码:

from cryptography.hazmat.primitives import serialization

# 假设公钥对象为 public_key

# 使用 PEM 格式将公钥序列化为字节流
public_key_bytes = public_key.public_bytes(
    encoding=serialization.Encoding.PEM,
    format=serialization.PublicFormat.SubjectPublicKeyInfo
)

print(public_key_bytes)

在上面的示例中,我们使用公钥对象的`public_bytes()`方法将公钥序列化为字节流。其中,我们指定了序列化的格式为PEM,并且使用`SubjectPublicKeyInfo`格式表示公钥。

通过选择适当的编码方式(如PEM或DER)以及公钥的格式(如SubjectPublicKeyInfo),可以将公钥序列化为字节流。这样,您可以将公钥保存到文件或通过网络传输,以便其他人使用。

3.3 保存公私钥

以下是一个将公私钥保存为pem格式的示例代码:

from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization

# 生成RSA私钥
private_key = rsa.generate_private_key(
    public_exponent=65537,
    key_size=2048,
)

# 获取公钥
public_key = private_key.public_key()

# 将私钥保存为pem格式
with open('private_key.pem', 'wb') as file:
    # 将私钥序列化为字节流
    private_key_bytes = private_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.PKCS8,
        encryption_algorithm=serialization.NoEncryption()
    )
    file.write(private_key_bytes)

# 将公钥保存为pem格式
with open('public_key.pem', 'wb') as file:
    # 将公钥序列化为字节流
    public_key_bytes = public_key.public_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PublicFormat.SubjectPublicKeyInfo
    )
    file.write(public_key_bytes)

4、加载秘钥

4.1 加载pem格式的公钥

在cryptography库中,使用serialization模块的`load_pem_public_key()`方法加载pem格式的公钥。

语法格式:

def load_pem_public_key(data: bytes, backend=None) -> _PUBLIC_KEY_TYPES:

参数说明:

  • data:要加载的PEM格式的公钥数据,是一个`bytes`类型的对象。该参数可以是一个公钥文件的内容,也可以是PEM格式的公钥字符串。
  • backend:(可选)要使用的加密后端实现的实例。
  • 返回值:`_PUBLIC_KEY_TYPES`:根据加载的公钥类型不同,返回的对象会有所不同。例如,如果加载的是RSA公钥,则返回`cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey`对象。 

以下是一个示例代码,演示了如何加载PEM格式的公钥:

from cryptography.hazmat.primitives import serialization


# 读取PEM格式的公钥
def loader_public_key():
    with open('public_key.pem', 'rb') as file:
        public_key = serialization.load_pem_public_key(
            file.read()
        )
    return public_key

4.2 加载pem格式的私钥

在cryptography库中,使用serialization模块的'load_pem_private_key()'方法加载pem格式的私钥。

语法格式:

def load_pem_private_key(
    data: bytes, password: typing.Optional[bytes], backend=None
) -> _PRIVATE_KEY_TYPES:

参数说明:

  • data:要加载的PEM格式的私钥数据,是一个`bytes`类型的对象。可以是一个私钥文件的内容,也可以是PEM格式的私钥字符串。
  • password:(可选)私钥的密码,是一个`bytes`类型的对象。如果私钥受密码保护,则需要提供密码以解密私钥。如果私钥没有密码,则可以将该参数设置为`None`。
  • backend:(可选)要使用的加密后端实现的实例。
  • 返回值:_PRIVATE_KEY_TYPES:根据加载的私钥类型不同,返回的对象会有所不同。例如,如果加载的是RSA私钥,则返回`cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey`对象。

以下是一个示例代码,演示了如何使用`load_pem_private_key`方法加载PEM格式的私钥:

from cryptography.hazmat.primitives import serialization


# 读取PEM格式的私钥
def loader_private_key():
    with open('private_key.pem', 'rb') as file:
        private_key = serialization.load_pem_private_key(
            file.read(),
            password=None
        )
    return private_key

5、加解和解密

5.1 加密

在cryptography模块中,使用cryptography.hazmat.primitives.asymmetric.rsa模块的RSAPublicKey.encrypt()方法对明文数据进行加密。

语法格式:

def encrypt(self, plaintext: bytes, padding: AsymmetricPadding) -> bytes:

参数说明:

  • plaintext:要加密的原始数据,是一个`bytes`类型的对象。
  • padding:使用的填充方案,是一个`AsymmetricPadding`类型的对象。可以使用`padding.PKCS1v15`、`padding.OAEP`等填充方案。
  • 返回值:加密后的数据,是一个`bytes`类型的对象。

以下是一个示例代码,演示了如何使用cryptography模块对数据进行公钥加密:

from cryptography.hazmat.primitives.asymmetric import rsa, padding

# 假设您已有一个RSA公钥用于加密
public_key = ...

# 要加密的数据
data = b"Hello, world!"

# 使用公钥对数据进行加密
ciphertext = public_key.encrypt(
    data,
    padding.OAEP(
        mgf=padding.MGF1(algorithm=hashes.SHA256()),
        algorithm=hashes.SHA256(),
        label=None
    )
)

# 将加密后的数据存储或传递给需要解密的地方

5.2 解密

在cryptography模块中,使用cryptography.hazmat.primitives.asymmetric.rsa模块RSAPrivateKey.decrypt()方法对加密后的密文进行解密。

语法格式:

def decrypt(self, ciphertext: bytes, padding: AsymmetricPadding) -> bytes:

参数说明:

  • ciphertext:要解密的密文数据,是一个bytes类型的对象。
  • padding:使用的填充方案,是一个AsymmetricPadding类型的对象。可以使用padding.PKCS1v15、padding.OAEP等填充方案。
  • 返回值:解密后的原始数据,是一个bytes类型的对象。

以下是一个示例代码,演示了如何使用cryptography模块对数据进行私钥解密:

from cryptography.hazmat.primitives.asymmetric import rsa, padding

# 假设您已有一个RSA私钥用于解密
private_key = ...

# 要解密的数据
ciphertext = ...

# 使用私钥对数据进行解密
plaintext = private_key.decrypt(
    ciphertext,
    padding.OAEP(
        mgf=padding.MGF1(algorithm=hashes.SHA256()),
        algorithm=hashes.SHA256(),
        label=None
    )
)

6、签名和验签

6.1 签名(sign)

在cryptography模块中,使用cryptography.hazmat.primitives.asymmetric.rsa模块的RSAPrivateKey.sign()方法进行签名。

语法格式:

    def sign(
        self,
        data: bytes,
        padding: AsymmetricPadding,
        algorithm: typing.Union[asym_utils.Prehashed, hashes.HashAlgorithm],
    ) -> bytes:

参数说明:

  • data:要签名的数据,是一个bytes类型的对象。
  • padding:使用的填充方案,是一个AsymmetricPadding类型的对象。可以使用padding.PKCS1v15、padding.PSS等填充方案。
  • algorithm:使用的哈希算法,可以是asym_utils.Prehashed类型的对象或hashes.HashAlgorithm类型的对象。
  • 返回值:签名结果,是一个bytes类型的对象。

以下是一个示例代码,展示了如何使用cryptography模块对数据进行签名:

from cryptography.hazmat.primitives import hashing, serialization
from cryptography.hazmat.primitives.asymmetric import rsa, padding

# 假设您已有一个RSA私钥供签名使用
private_key = ...

# 要签名的数据
data = b"Hello, world!"

# 使用私钥对数据进行签名
signature = private_key.sign(
    data,
    padding.PSS(
        mgf=padding.MGF1(hashes.SHA256()),
        salt_length=padding.PSS.MAX_LENGTH
    ),
    hashing.SHA256()
)

# 将签名存储或传递给需要验证签名的地方

6.2 验签(verify)

在cryptography模块中,使用cryptography.hazmat.primitives.asymmetric.rsa模块的RSAPublicKey.verify()方法进行验签。

语法格式:

    def verify(
        self,
        signature: bytes,
        data: bytes,
        padding: AsymmetricPadding,
        algorithm: typing.Union[asym_utils.Prehashed, hashes.HashAlgorithm],
    ) -> None:

参数说明:

  • signature:要验证的签名,是一个`bytes`类型的对象。
  • data:要验证的原始数据,是一个`bytes`类型的对象。
  • padding:使用的填充方案,是一个`AsymmetricPadding`类型的对象。可以使用`padding.PKCS1v15`、`padding.PSS`等填充方案。
  • algorithm:使用的哈希算法,可以是`asym_utils.Prehashed`类型的对象或`hashes.HashAlgorithm`类型的对象。
  • 返回值:无,如果验证通过,不会返回任何内容。如果验证失败,会触发`InvalidSignature`异常。

以下是一个示例代码,演示了如何使用cryptography模块对签名进行验证:

from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import rsa, padding

# 假设您已有一个RSA公钥供验签使用
public_key = ...

# 要验证的数据和签名
data = b"Hello, world!"
signature = ...

# 使用公钥进行签名验证
try:
    public_key.verify(
        signature,
        data,
        padding.PSS(
            mgf=padding.MGF1(hashes.SHA256()),
            salt_length=padding.PSS.MAX_LENGTH
        ),
        hashes.SHA256()
    )
    print("Signature is valid.")
except InvalidSignature:
    print("Signature is invalid.")

注意:在进行验签时,您需要使用相同的填充方案来对接收到的签名进行验证。如果填充方案不匹配,验证过程将会失败。


reference:

cryptography · PyPI

Welcome to pyca/cryptography — Cryptography 42.0.0.dev1 documentation

  • 6
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Python 3.4 中的 `cryptography` 是一个强大的密码学库,提供了许多密码学相关的功能和工具。它支持很多常见的加密算法,如 AES、RSA、DSA 等,同时还提供了许多其他密码学算法和协议的实现。 `cryptography` 库的使用非常简单,可以轻松地将其集成到你的程序中。首先,你需要安装 `cryptography` 库,可以使用 `pip` 命令进行安装安装完成后,你就可以在你的程序中导入 `cryptography` 模块,并开始使用其中的功能了。 例如,你可以使用 `cryptography` 来生成随机数、生成和验证数字签名、进行加密和解密等。对于加密和解密,`cryptography` 提供了简单易用的 API,你可以使用不同的密码算法对数据进行加密和解密,并且还可以设置密码的模式和填充方式等。 此外,`cryptography` 还提供了一些密码安全相关的功能,如密码哈希、安全随机数生成等。密码哈希是一种单向函数,可以将任意长度的数据转换为固定长度的哈希值,常用于密码存储和验证。安全随机数生成可以生成高质量的随机数,用于密码生成、加密密钥的生成等场景。 总之,Python 3.4 中的 `cryptography` 是一个功能强大的密码学库,提供了许多密码学相关的功能和工具,可以帮助开发者实现各种密码学操作和保护数据的安全。无论你是在开发网络应用还是进行数据加密,都可以考虑使用 `cryptography` 来提供安全的解决方案。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值