英语术语

WordsExplanations
symmetric cipher对称加密
message digest类似 md5, sha1 等等

安装

pip install cryptography

AES 加密

使用 Fernet class 实现

  • 注意

    • 这里 Fernet 需要的 key 是二进制的
    • key 有特定的格式要求

      • 因此,可以直接使用 Fernet.generate_key()制作的 key(避免麻烦)

制作 key

自动制作

Fernet.generate_key()

1
2
3
4
from cryptography.fernet import Fernet

key = Fernet.generate_key()
# eg: key = b'FL8mAELPAushbhzhu6Yx4tJLxumu8KqQjCLHsOJs1Zo='

手动制作

  • 密码添加 salt 方法

    1. 使用自己设定的密码
    2. 加入 salt

      • os.uname(16)
      • 或自定义 b'anything'
    3. 通过密码偏移函数处理

      • key deviation function
      • 经过 base64 编码 encode
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import base64
import os
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC

password_provided = "password" # This is input in the form of a string
password = password_provided.encode() # Convert to type bytes
salt = b'salt_' # CHANGE THIS - recommend using a key from os.urandom(16), must be of type bytes
salt = os.urandom(16)

kdf = PBKDF2HMAC(
    algorithm=hashes.SHA256(),
    length=32,
    salt=salt,
    iterations=100000,
    backend=default_backend()
)

# * 验证 kdf 生成的key shifou 正确
kdf.verify(password, kdf.derive(password))

key = base64.urlsafe_b64encode(kdf.derive(password)) # Can only use kdf once

加密解密

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
from cryptography.fernet import Fernet

key = Fernet.generate_key()

aesObj = Fernet(key)

raw_data = 'That is a wonderful day.'

encrypted = aesObj.encrypt(raw_data.encode('utf-8'))
decrypted = aesObj.decrypt(encrypted).decode('utf-8')

模块架构

  • 分成两大部分

    • safe cryptographic recipes layer

      • 可以直接使用的,已经配置好的接口与方案
      • 安全,易用
    • hazardous material layer

      • 自定义加密配置,自我管理风险
      • 个性化,有风险,要求高

X.509

https 和 ssl 背后使用的加密方法