1、理解工厂方法模式的动机,掌握该模式的结构;
2、能够利用工厂方法模式解决实际问题。
[实验任务一]:加密算法
目前常用的加密算法有DES(Data Encryption Standard)和IDEA(International Data Encryption Algorithm)国际数据加密算法等,请用工厂方法实现加密算法系统。
1. 类图
依赖命令pip install pycryptodome
from abc import ABC, abstractmethod
from Crypto.Cipher import DES, IDEA
# 抽象加密器类
class Encryptor(ABC):
@abstractmethod
def encrypt(self, data):
pass
@abstractmethod
def decrypt(self, encrypted_data):
pass
# DES加密器类
class DESEncryptor(Encryptor):
def __init__(self, key):
self.key = key
self.des = DES.new(self.key, DES.MODE_ECB)
def encrypt(self, data):
data = data + b' ' * (8 - len(data) % 8)
return self.des.encrypt(data)
def decrypt(self, encrypted_data):
return self.des.decrypt(encrypted_data).rstrip()
# IDEA加密器类
class IDEAEncryptor(Encryptor):
def __init__(self, key):
self.key = key
self.idea = IDEA.new(self.key, IDEA.MODE_ECB)
def encrypt(self, data):
data = data + b' ' * (8 - len(data) % 8)
return self.idea.encrypt(data)
def decrypt(self, encrypted_data):
return self.idea.decrypt(encrypted_data).rstrip()
# 加密器工厂类
class EncryptorFactory:
@staticmethod
def create_encryptor(algorithm_type, key):
if algorithm_type == 'DES':
return DESEncryptor(key)
elif algorithm_type == 'IDEA':
return IDEAEncryptor(key)
key = b'12345678'
data = b'Hello, World!'
# 使用DES加密
des_encryptor = EncryptorFactory.create_encryptor('DES', key)
encrypted_data_des = des_encryptor.encrypt(data)
decrypted_data_des = des_encryptor.decrypt(encrypted_data_des)
print("DES加密后:", encrypted_data_des)
print("DES解密后:", decrypted_data_des)
# 使用IDEA加密
idea_encryptor = EncryptorFactory.create_encryptor('IDEA', key)
encrypted_data_idea = idea_encryptor.encrypt(data)
decrypted_data_idea = idea_encryptor.decrypt(encrypted_data_idea)
print("IDEA加密后:", encrypted_data_idea)
print("IDEA解密后:", decrypted_data_idea)
标签:方法,self,des,idea,模式,工厂,key,encrypted,data From: https://www.cnblogs.com/aixin52129211/p/18498145