十月二十八日

yblll發表於2024-10-30

[實驗任務一]:加密演算法

目前常用的加密演算法有DES(Data Encryption Standard)和IDEA(International Data Encryption Algorithm)國際資料加密演算法等,請用工廠方法實現加密演算法系統。

複製程式碼
package test3;
import java.lang.reflect.AccessibleObject;
import java.util.Scanner;

import sun.misc.Unsafe;

public class Client {

    public static void disableWarning() {
        try {
            java.lang.reflect.Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
            ((AccessibleObject) theUnsafe).setAccessible(true);
            Unsafe u = (Unsafe) theUnsafe.get(null);
            Class<?> cls = Class.forName("jdk.internal.module.IllegalAccessLogger");
            java.lang.reflect.Field logger = cls.getDeclaredField("logger");
            u.putObjectVolatile(cls, u.staticFieldOffset(logger), null);
        } catch (Exception e) {
        }
    }

    public static void main(String[] args) {
        disableWarning();

        DES des = new DES();
        IDEA idea = new IDEA();
        try {
            int n = 0;

            @SuppressWarnings("resource")
            Scanner in = new Scanner(System.in);
            while (n != 3) {
                System.out.println("請選擇要使用的加密演算法 1.DES加密演算法 2.IDEA加密演算法 3.退出");
                System.out.println("請選擇");
                if (in.hasNextInt()) {
                    n = in.nextInt();
                } else {
                    System.out.println("輸入的不是整數,請重新輸入:");
                    continue;
                }
                switch (n) {
                case 1: {

                    des.work("1787878787878787", "0E329232EA6D0D73");
                    break;
                }
                case 2: {
                    idea.work("8787878787878787", "0E329232EA6D0D73");
                    break;
                }
                }
            }
        }catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}

//run此檔案
複製程式碼
複製程式碼
package test3;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;


public class DES implements Method{
     public void work(String str, String password) {
            String begincode = "人生苦短及時行樂";
            String endcode = null;
            String opencode = null;
            System.out.println("要加密的明文" + begincode);
            String cipherType = "DESede";
            try {

                KeyGenerator keyGen = KeyGenerator.getInstance(cipherType);

                keyGen.init(112);

                SecretKey key = keyGen.generateKey();

                byte[] keyByte = key.getEncoded();

                System.out.println("金鑰是:");
                for (int i = 0; i < keyByte.length; i++) {
                    System.out.print(keyByte[i] + ",");
                }
                System.out.println("");

                Cipher cp = Cipher.getInstance(cipherType);

                cp.init(Cipher.ENCRYPT_MODE, key);
                System.out.println("要加密的字串是:" + begincode);
                byte[] codeStringByte = begincode.getBytes("UTF8");
                System.out.println("要加密的字串對應的位元組碼是:");
                for (int i = 0; i < codeStringByte.length; i++) {
                    System.out.print(codeStringByte[i] + ",");
                }
                System.out.println("");

                byte[] codeStringByteEnd = cp.doFinal(codeStringByte);
                System.out.println("加密後的字串對應的位元組碼是:");
                for (int i = 0; i < codeStringByteEnd.length; i++) {
                    System.out.print(codeStringByteEnd[i] + ",");
                }
                System.out.println("");
                endcode = new String(codeStringByteEnd);
                System.out.println("加密後的字串是:" + endcode);
                System.out.println("");

                cp.init(Cipher.DECRYPT_MODE, key);

                byte[] decodeStringByteEnd = cp.doFinal(codeStringByteEnd);
                System.out.println("解密後的字串對應的位元組碼是:");
                for (int i = 0; i < decodeStringByteEnd.length; i++) {
                    System.out.print(decodeStringByteEnd[i] + ",");
                }
                System.out.println("");
                opencode = new String(decodeStringByteEnd);
                System.out.println("解密後的字串是:" + opencode);
                System.out.println("");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        public static void main(String[] args) {
            // TODO Auto-generated method stub
            System.out.println("DES加密演算法");
            DES des = new DES();
            try {
                des.work("8787878787878787", "0E329232EA6D0D73");

            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
    
}
複製程式碼
複製程式碼
package test3;

public class DESFactory implements MethodFactory {
    public DES produceMethod() {
        System.out.println("使用DES演算法");
        return new DES();
    }
}
複製程式碼
複製程式碼
package test3;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;


import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.Security;

public class IDEA implements Method {

    public static final String KEY_ALGORITHM = "IDEA";

    public static final String CIPHER_ALGORITHM = "IDEA/ECB/ISO10126Padding";

    public static byte[] initkey() throws Exception {
        // 加入bouncyCastle支援
        Security.addProvider(new BouncyCastleProvider());

        // 例項化金鑰生成器
        KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
        // 初始化金鑰生成器,IDEA要求金鑰長度為128位
        kg.init(128);
        // 生成金鑰
        SecretKey secretKey = kg.generateKey();
        // 獲取二進位制金鑰編碼形式
        return secretKey.getEncoded();
    }


    private static Key toKey(byte[] key) throws Exception {
        // 例項化DES金鑰
        // 生成金鑰
        SecretKey secretKey = new SecretKeySpec(key, KEY_ALGORITHM);
        return secretKey;
    }


    private static byte[] encrypt(byte[] data, byte[] key) throws Exception {
        // 加入bouncyCastle支援
        Security.addProvider(new BouncyCastleProvider());
        // 還原金鑰
        Key k = toKey(key);
        // 例項化
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        // 初始化,設定為加密模式
        cipher.init(Cipher.ENCRYPT_MODE, k);
        // 執行操作
        return cipher.doFinal(data);
    }


    private static byte[] decrypt(byte[] data, byte[] key) throws Exception {
        // 加入bouncyCastle支援
        Security.addProvider(new BouncyCastleProvider());
        // 還原金鑰
        Key k = toKey(key);
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        // 初始化,設定為解密模式
        cipher.init(Cipher.DECRYPT_MODE, k);
        // 執行操作
        return cipher.doFinal(data);
    }

    public static String getKey() {
        String result = null;
        try {
            result = Base64.encodeBase64String(initkey());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static String ideaEncrypt(String data, String key) {
        String result = null;
        try {
            byte[] data_en = encrypt(data.getBytes(), Base64.decodeBase64(key));
            result = Base64.encodeBase64String(data_en);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static String ideaDecrypt(String data, String key) {
        String result = null;
        try {
            byte[] data_de = decrypt(Base64.decodeBase64(data), Base64.decodeBase64(key));
            ;
            result = new String(data_de);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public void work(String str, String password) {
        String data = "人生苦短及時行樂"; // 要加密的明文
        String key = getKey();
        System.out.println("要加密的原文:" + data);
        System.out.println("金鑰:" + key);
        String data_en = ideaEncrypt(data, key);
        System.out.println("密文:" + data_en);
        String data_de = ideaDecrypt(data_en, key);
        System.out.println("原文:" + data_de);
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println("IDEA加密演算法");
        IDEA idea = new IDEA();
        try {
            idea.work("8787878787878787", "0E329232EA6D0D73");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

}
複製程式碼
複製程式碼
package test3;

public class IDEAFactory implements MethodFactory {
    public IDEA produceMethod() {
        System.out.println("使用IDEA演算法");
        return new IDEA();
    }
}
複製程式碼
複製程式碼
package test3;

public interface Method {
    public void work(String str, String password);

}
複製程式碼
複製程式碼
package test3;

public interface MethodFactory {
    
    public Method produceMethod();

}

相關文章