11.3日学习笔记

实验3:工厂方法模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解工厂方法模式的动机,掌握该模式的结构;
2、能够利用工厂方法模式解决实际问题。

[实验任务一]:加密算法
目前常用的加密算法有DES(Data Encryption Standard)和IDEA(International Data Encryption Algorithm)国际数据加密算法等,请用工厂方法实现加密算法系统。
实验要求:
1.画出对应的类图;
2.提交该系统的代码,该系统务必是一个可以能够直接使用的系统,查阅资料完成相应加密算法的实现;
3.注意编程规范。

一、类图设计
Mermaid

classDiagram
class EncryptionAlgorithm {
<>
+encrypt(data: String): String
+decrypt(data: String): String
}

class DESAlgorithm {
    +encrypt(data: String): String
    +decrypt(data: String): String
}

class IDEAAlgorithm {
    +encrypt(data: String): String
    +decrypt(data: String): String
}

class EncryptionFactory {
    <<interface>>
    +createAlgorithm(): EncryptionAlgorithm
}

class DESFactory {
    +createAlgorithm(): EncryptionAlgorithm
}

class IDEAFactory {
    +createAlgorithm(): EncryptionAlgorithm
}

class Client {
    -factory: EncryptionFactory
    +encryptData(data: String): String
    +decryptData(data: String): String
}

EncryptionFactory ..> EncryptionAlgorithm : creates
DESFactory ..|> EncryptionFactory
IDEAFactory ..|> EncryptionFactory
DESFactory ..> DESAlgorithm : creates
IDEAFactory ..> IDEAAlgorithm : creates
EncryptionAlgorithm <|.. DESAlgorithm
EncryptionAlgorithm <|.. IDEAAlgorithm
Client ..> EncryptionFactory : uses

二、代码实现

  1. 加密算法接口和实现类
    java

// EncryptionAlgorithm.java
public interface EncryptionAlgorithm {
String encrypt(String data) throws Exception;
String decrypt(String data) throws Exception;
}

// DESAlgorithm.java
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class DESAlgorithm implements EncryptionAlgorithm {
private static final String ALGORITHM = "DES";
private SecretKey key;

public DESAlgorithm() throws Exception {
    // 生成密钥
    KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM);
    keyGen.init(56); // DES使用56位密钥
    this.key = keyGen.generateKey();
}

@Override
public String encrypt(String data) throws Exception {
    Cipher cipher = Cipher.getInstance(ALGORITHM);
    cipher.init(Cipher.ENCRYPT_MODE, key);
    byte[] encryptedBytes = cipher.doFinal(data.getBytes());
    return Base64.getEncoder().encodeToString(encryptedBytes);
}

@Override
public String decrypt(String data) throws Exception {
    Cipher cipher = Cipher.getInstance(ALGORITHM);
    cipher.init(Cipher.DECRYPT_MODE, key);
    byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(data));
    return new String(decryptedBytes);
}

}

// IDEAAlgorithm.java
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class IDEAAlgorithm implements EncryptionAlgorithm {
private static final String ALGORITHM = "IDEA";
private SecretKey key;

public IDEAAlgorithm() throws Exception {
    // 生成密钥
    KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM);
    keyGen.init(128); // IDEA使用128位密钥
    this.key = keyGen.generateKey();
}

@Override
public String encrypt(String data) throws Exception {
    Cipher cipher = Cipher.getInstance(ALGORITHM);
    cipher.init(Cipher.ENCRYPT_MODE, key);
    byte[] encryptedBytes = cipher.doFinal(data.getBytes());
    return Base64.getEncoder().encodeToString(encryptedBytes);
}

@Override
public String decrypt(String data) throws Exception {
    Cipher cipher = Cipher.getInstance(ALGORITHM);
    cipher.init(Cipher.DECRYPT_MODE, key);
    byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(data));
    return new String(decryptedBytes);
}

}
2. 工厂接口和实现类
java

// EncryptionFactory.java
public interface EncryptionFactory {
EncryptionAlgorithm createAlgorithm() throws Exception;
}

// DESFactory.java
public class DESFactory implements EncryptionFactory {
@Override
public EncryptionAlgorithm createAlgorithm() throws Exception {
return new DESAlgorithm();
}
}

// IDEAFactory.java
public class IDEAFactory implements EncryptionFactory {
@Override
public EncryptionAlgorithm createAlgorithm() throws Exception {
return new IDEAAlgorithm();
}
}
3. 客户端类
java

// Client.java
public class Client {
private EncryptionFactory factory;
private EncryptionAlgorithm algorithm;

public Client(EncryptionFactory factory) throws Exception {
    this.factory = factory;
    this.algorithm = factory.createAlgorithm();
}

public String encryptData(String data) throws Exception {
    return algorithm.encrypt(data);
}

public String decryptData(String encryptedData) throws Exception {
    return algorithm.decrypt(encryptedData);
}

public void setFactory(EncryptionFactory factory) throws Exception {
    this.factory = factory;
    this.algorithm = factory.createAlgorithm();
}

}
4. 测试类
java

// EncryptionTest.java
import java.util.Scanner;

public class EncryptionTest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

    try {
        System.out.println("=== 加密算法系统 ===");
        System.out.println("1. DES加密算法");
        System.out.println("2. IDEA加密算法");
        System.out.print("请选择加密算法(1-2): ");
        
        int choice = scanner.nextInt();
        scanner.nextLine(); // 消费换行符
        
        EncryptionFactory factory = null;
        String algorithmName = "";
        
        switch (choice) {
            case 1:
                factory = new DESFactory();
                algorithmName = "DES";
                break;
            case 2:
                factory = new IDEAFactory();
                algorithmName = "IDEA";
                break;
            default:
                System.out.println("无效选择!");
                return;
        }
        
        Client client = new Client(factory);
        
        while (true) {
            System.out.println("\n=== " + algorithmName + "加密系统 ===");
            System.out.println("1. 加密数据");
            System.out.println("2. 解密数据");
            System.out.println("3. 切换加密算法");
            System.out.println("4. 退出");
            System.out.print("请选择操作(1-4): ");
            
            int operation = scanner.nextInt();
            scanner.nextLine(); // 消费换行符
            
            switch (operation) {
                case 1:
                    System.out.print("请输入要加密的文本: ");
                    String plainText = scanner.nextLine();
                    String encrypted = client.encryptData(plainText);
                    System.out.println("加密结果: " + encrypted);
                    break;
                    
                case 2:
                    System.out.print("请输入要解密的文本: ");
                    String encryptedText = scanner.nextLine();
                    String decrypted = client.decryptData(encryptedText);
                    System.out.println("解密结果: " + decrypted);
                    break;
                    
                case 3:
                    System.out.println("\n=== 切换加密算法 ===");
                    System.out.println("1. DES加密算法");
                    System.out.println("2. IDEA加密算法");
                    System.out.print("请选择加密算法(1-2): ");
                    
                    int newChoice = scanner.nextInt();
                    scanner.nextLine();
                    
                    switch (newChoice) {
                        case 1:
                            client.setFactory(new DESFactory());
                            algorithmName = "DES";
                            System.out.println("已切换到DES算法");
                            break;
                        case 2:
                            client.setFactory(new IDEAFactory());
                            algorithmName = "IDEA";
                            System.out.println("已切换到IDEA算法");
                            break;
                        default:
                            System.out.println("无效选择!");
                    }
                    break;
                    
                case 4:
                    System.out.println("感谢使用!");
                    return;
                    
                default:
                    System.out.println("无效选择!");
            }
        }
        
    } catch (Exception e) {
        System.err.println("错误: " + e.getMessage());
        e.printStackTrace();
    } finally {
        scanner.close();
    }
}

}
三、使用说明
编译运行:
bash

javac *.java
java EncryptionTest
功能特点:
支持DES和IDEA两种加密算法
可以动态切换加密算法
提供加密和解密功能
使用Base64编码显示加密结果
注意事项:
需要Java 8或更高版本
IDEA算法可能需要额外的加密库支持(如Bouncy Castle)
每次实例化都会生成新的密钥
四、扩展建议
可以添加AES、RSA等其他加密算法
实现密钥的保存和加载功能
添加文件加密/解密功能
实现加密强度配置

posted @ 2025-11-03 23:30  头发少的文不识  阅读(5)  评论(0)    收藏  举报