📅  最后修改于: 2023-12-03 15:12:46.805000             🧑  作者: Mango
这是门|门IT 2007年的第三个问题,要求程序员们写出一个程序来解决具体的问题。
问题3要求程序员们写一个程序来进行数据加密和解密,包括对称加密、非对称加密以及哈希算法的实现。
程序应该能够支持以下操作:
import hashlib
from Crypto.Cipher import AES
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding, rsa
def symmetric_encrypt(key, data):
cipher = AES.new(key, AES.MODE_EAX)
nonce = cipher.nonce
ciphertext, tag = cipher.encrypt_and_digest(data)
return nonce + ciphertext + tag
def symmetric_decrypt(key, data):
nonce = data[:16]
ciphertext = data[16:-16]
tag = data[-16:]
cipher = AES.new(key, AES.MODE_EAX, nonce=nonce)
return cipher.decrypt_and_verify(ciphertext, tag)
def asymmetric_encrypt(pubkey, data):
ciphertext = pubkey.encrypt(data, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None))
return ciphertext
def asymmetric_decrypt(privkey, data):
plaintext = privkey.decrypt(data, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None))
return plaintext
def hash_data(data, algorithm='sha256'):
hash_func = hashlib.new(algorithm)
hash_func.update(data)
return hash_func.hexdigest()
# 示例用法
# 对称加密和解密:
key = b'1234567890123456'
data = b'This is a test message'
ciphertext = symmetric_encrypt(key, data)
plaintext = symmetric_decrypt(key, ciphertext)
assert plaintext == data
# 非对称加密和解密:
privkey = rsa.generate_private_key(
public_exponent=65537,
key_size=2048
)
pubkey = privkey.public_key()
data = b'This is a test message'
ciphertext = asymmetric_encrypt(pubkey, data)
plaintext = asymmetric_decrypt(privkey, ciphertext)
assert plaintext == data
# 哈希算法:
data = b'This is a test message'
hash_value = hash_data(data)
assert hash_value == 'cc9f1fc4b03842f6130d6752113fc30c85b766dd1068500e135650fb37312cea'
数据加密和解密是程序员经常需要处理的任务之一。本问题中所涉及到的对称加密、非对称加密以及哈希算法也是常用的加密方法。在实际使用中,需要根据具体的需求选择合适的加密算法和加密密钥。