# Python对称和非对称加密算法及网传输层安全(TLS)

{% tabs %}
{% tab title="关键词" %}
Python | 对称加密 | 非对称加密 | 算法 | 网传输层安全(TLS) | 哈希值 | 块密码 | 流密码 | AES | RSA | 消息验证码 (MAC) | 迪菲赫尔曼非对称加密 | 椭园曲线迪菲赫尔曼非对称加密 | 伽罗瓦/计数器模式(AES-GCM) | 带有密码块链接消自认证码的计数器(AES-CCM) | ChaCha20-Poly1305 | 服务器/客户端 | 网络传输层安全 (TLS) | OpenSSL
{% endtab %}

{% tab title="梗概" %}
了解 AES 等分组密码的算法和模式，使用消息完整性和/或数字签名来保护消息，利用现代对称密码，例如 AES-GCM 和 CHACHA，发现如果使用不安全的填充，RSA 加密是如何被破解的，使用 TLS 连接进行安全通信。

#### **Python环境设置**

#### **哈希值**

#### **对称加密与非对称加密及结合算法**

示例：AES填充

```python
# NEVER USE: ECB is not secure!
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend

# Alice and Bob's Shared Key
test_key = bytes.fromhex('00112233445566778899AABBCCDDEEFF')

aesCipher = Cipher(algorithms.AES(test_key),
                   modes.ECB(),
                   backend=default_backend())
aesEncryptor = aesCipher.encryptor()
aesDecryptor = aesCipher.decryptor()

message = b"""
FROM: FIELD AGENT ALICE
TO: FIELD AGENT BOB
RE: Meeting
DATE: 2001-1-1

Meet me today at the docks at 2300."""

message += b"E" * (-len(message) % 16)
ciphertext = aesEncryptor.update(message)

print("plaintext:",message)
print("ciphertext:",ciphertext.hex())
recovered = aesDecryptor.update(ciphertext)
print("recovered:",recovered)
if(message==recovered): print("[PASS]")
else: print("[FAIL]")
```

```python
# NEVER USE THIS. ECB IS _NOT_ SECURE!!!
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend

test_key = bytes.fromhex('00112233445566778899AABBCCDDEEFF')

aesCipher = Cipher(algorithms.AES(test_key), modes.ECB(), backend=default_backend())
aesEncryptor = aesCipher.encryptor()
aesDecryptor = aesCipher.decryptor()

import sys

ifile, ofile = sys.argv[1:3]
with open(ifile, "rb") as reader:
    with open(ofile, "wb+") as writer:
        image_data = reader.read()
        header, body = image_data[:54], image_data[54:]
        body += b"\\x00"*(16-(len(body)%16))
        writer.write(header + aesEncryptor.update(body))
```

#### **消息认证**

#### **身份验证和网络认证协议**

#### **Python 实践 TLS**
{% endtab %}
{% endtabs %}

{% content-ref url="../zhi-dian-mi-jin-brief" %}
[zhi-dian-mi-jin-brief](../zhi-dian-mi-jin-brief)
{% endcontent-ref %}
