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

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

Python环境设置

哈希值

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

示例:AES填充

# 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]")
# 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

参阅 - 亚图跨际

你可能感兴趣的:(Python,交叉知识,python,安全)