首页 > 其他分享 >10.31

10.31

时间:2024-12-02 23:10:36浏览次数:2  
标签:String 10.31 System println data public out

次实验属于模仿型实验,通过本次实验学生将掌握以下内容:

1、理解工厂方法模式的动机,掌握该模式的结构;

2、能够利用工厂方法模式解决实际问题。

 

 

[实验任务一]:加密算法

目前常用的加密算法有DES(Data Encryption Standard)和IDEA(International Data Encryption Algorithm)国际数据加密算法等,请用工厂方法实现加密算法系统。

实验要求:

1. 画出对应的类图;

 

2. 提交该系统的代码,该系统务必是一个可以能够直接使用的系统,查阅资料完成相应加密算法的实现;

  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();

 

}

 

标签:String,10.31,System,println,data,public,out
From: https://www.cnblogs.com/xscya/p/18582986

相关文章

  • 10.31日报
    完成设计模式实验:实验10:组合模式本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:1、理解组合模式的动机,掌握该模式的结构;2、能够利用组合模式解决实际问题。     [实验任务一]:组合模式用透明组合模式实现教材中的“文件夹浏览”这个例子。实验要......
  • 10.31
    今天我们再来实现上述个人信息添加的前端代码。 1、add.html<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title>添加个人信息</title><style>body{font-family:Arial,san......
  • 10.31
    publicclassUserServlet extendsHttpServlet{    @Override    protectedvoiddoGet(HttpServletRequestreq,HttpServletResponseresp)throwsServletException,IOException{        StringrequestURL=req.getRequestURL().toString();     ......
  • 10.31
    今日学习内容<%@pageimport="java.sql.DriverManager"%><%@pageimport="java.sql.*"%><%--CreatedbyIntelliJIDEA.TochangethistemplateuseFile|Settings|FileTemplates.--%><%@pagecontentType="text/htm......
  • 10.31
    Java中常见运行时异常异常类型说明ArithmeticException算术错误异常,如以零做除数ArraylndexOutOfBoundException数组索引越界ArrayStoreException向类型不兼容的数组元素赋值ClassCastException类型转换异常IllegalArgumentException使用非法实参调用方法lIIegalStateExcept......
  • 10.31 模拟赛小记
    抽象场。打完人自闭的那种。得分情况:\(80-0-30-30\)。A:从\(0\)走到\(n\)。在\(i\)位置时,等概率走的走到\([i+1,n]\)(视为一步)。求期望步数。哥们赛时,爆搜打表找规律。。。最后写的O(n),没看到第九个数据点没有特判。对于最后一个点1e18,递推式写出来但不会进一步求。遗憾......
  • 大二快乐日记10.31
    Java中常见运行时异常异常类型 说明ArithmeticException 算术错误异常,如以零做除数ArraylndexOutOfBoundException 数组索引越界ArrayStoreException 向类型不兼容的数组元素赋值ClassCastException 类型转换异常IllegalArgumentException 使用非法实参调用方法lIIegalStateExcept......
  • misc 2023.10.31-11.05
    1.a.观察发现,中间有什么一闪而过,那么逐帧分析就可以了。b.将其拖入Stegsolve工具中,进行逐帧分析c.故可得到flag 2.a.将其丢入010中查找flagb.得到flag 3.a.将其丢入winhex中,发现一个txt文件b.就放到linux下试了binwalk发现里面是个zip分析文件:binwalkfilen......
  • 10.31
    今天我们再来实现上述个人信息添加的前端代码。 1、add.html<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title>添加个人信息</title><style>body{font-family:Arial,sans......
  • crypto 2023.10.31-11.05
    1.a.题目后面有"="就先猜一手base64编码,直接复制base64解码解密即可得到flagb.故直接用工具进行解密 2. a.因为是MD5加密,故直接用工具解密 3. a.因为是Url加密,故直接用工具解密 4. a.看题目像是凯撒密码,直接使用工具,并找到flag  5. a.因为key{}里面......