首页 > 编程语言 >工厂方法模式--Java代码实现

工厂方法模式--Java代码实现

时间:2023-10-13 22:22:05浏览次数:49  
标签:Java String -- 代码 return int key new byte

1、画类图

2、Java代码实现

其中可知,

PWFactory、PW类均为接口类;

并且,DESFactory、IDEAFactory类均要实现PWFactory接口;

DES、IDEA类均要实现PW接口;

具体代码如下:

//PWFactory.java
package org.example;

public interface PWFactory {
    public PW createProduce();
}

//DESFactory.java
package org.example;

public class DESFactory implements PWFactory{
    @Override
    public PW createProduce() {
        return new DES();
    }
}

//IDEAFactory.java
package org.example;

public class IDEAFactory implements PWFactory{
    @Override
    public PW createProduce() {
        return new IDEA();
    }
}

//PW.java
package org.example;

public interface PW {
    public void show();
}

//DES.java
package org.example;

import javax.crypto.*;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.util.Scanner;

public class DES implements PW{
    @Override
    public void show() throws NoSuchPaddingException, IllegalBlockSizeException, NoSuchAlgorithmException, InvalidKeySpecException, BadPaddingException, InvalidKeyException {
        System.out.println("DES");
        System.out.println("请输入加密内容:");
        Scanner sc=new Scanner(System.in);
        String text=sc.nextLine();
        String password="12345678";
        byte[] result=DES.encrypt(text.getBytes(),password);
        System.out.println("加密后: "+result);

        System.out.println("解密内容: "+result);
        byte[] decodeResult=DES.decrypt(result,password);
        System.out.println("解密后内容: "+(new String(decodeResult)));

    }

    //编码方法
    public static byte[] encrypt(byte[] datasource,String password) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
        //SecureRandom sr=new SecureRandom();
        SecretKeySpec sks=new SecretKeySpec(password.getBytes(),"DES");
        //DESedeKeySpec dss=new DESedeKeySpec(password.getBytes());
        //SecretKeyFactory skf=SecretKeyFactory.getInstance("DES");
        //SecretKey sk=skf.generateSecret(dss);
        Cipher c=Cipher.getInstance("DES");
        c.init(Cipher.ENCRYPT_MODE,sks);
        return c.doFinal(datasource);
    }

    //解码方法
    public static byte[] decrypt(byte[] src,String password) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
        //SecureRandom sr=new SecureRandom();
        //DESedeKeySpec dss=new DESedeKeySpec(password.getBytes());
        SecretKeySpec sks=new SecretKeySpec(password.getBytes(),"DES");
        //SecretKeyFactory skf=SecretKeyFactory.getInstance("DES");
        //SecretKey sk=skf.generateSecret(dss);
        Cipher c=Cipher.getInstance("DES");
        c.init(Cipher.DECRYPT_MODE,sks);
        return c.doFinal(src);
    }

}

//IDEA.java
package org.example;

import java.util.Scanner;

public class IDEA implements PW{
    @Override
    public void show() {
        System.out.println("IDEA");
        System.out.print("请输入加密内容:");
        Scanner out = new Scanner(System.in);
        String str = out.nextLine();
        IDEA idea = new IDEA();
        idea.getKey("aabb");// 生成密匙
        String strEnc = idea.getEncString(str);// 加密字符串,返回String的密文
        System.out.println("加密后:"+strEnc);
        int ll=str.length();
        System.out.println("解密内容:"+strEnc);
        String strDes = idea.getDesString(strEnc,ll);// 把String 类型的密文解密
        System.out.println("解密后:"+strDes);
    }

    private byte[] bytekey;
    public byte[] getKey(String key) {
        int len1 = key.length();
        if (len1 >= 16) {
            key = key.substring(0, 16);
        } else {
            for (int i = 0; i < 16 - len1; i++) {
                key = key.concat("0");
            }
        }
        bytekey = key.getBytes();
        return bytekey;
    }
    public String getEncString(String strMing) {
        byte[] byteMi = null;
        byte[] byteMing = null;
        String strMi = "";
        try {
            return byte2hex(IdeaEncrypt(bytekey, strMing.getBytes(), true));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            byteMing = null;
            byteMi = null;
        }
        return strMi;
    }
    public String getDesString(String strMi,int l) {
        byte[] byteMing = null;
        byte[] byteMi = null;
        String strMing = "";
        try {
            String tmp = new String(IdeaEncrypt(bytekey, hex2byte(strMi.getBytes()), false));
            return tmp.substring(0, l);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            byteMing = null;
            byteMi = null;
        }
        return strMing;
    }
    private byte[] Encrypt(byte[] bytekey, byte[] inputBytes, boolean flag) {
        byte[] encryptCode = new byte[8];
        int[] key = get_subkey(flag, bytekey);
        encrypt(key, inputBytes, encryptCode);
        return encryptCode;
    }
    private int bytesToInt(byte[] inBytes, int startPos) {
        return ((inBytes[startPos] << 8) & 0xff00) + (inBytes[startPos + 1] & 0xff);
    }
    private void intToBytes(int inputInt, byte[] outBytes, int startPos) {
        outBytes[startPos] = (byte) (inputInt >>> 8);
        outBytes[startPos + 1] = (byte) inputInt;
    }
    private int x_multiply_y(int x, int y) {
        if (x == 0) {
            x = 0x10001 - y;
        } else if (y == 0) {
            x = 0x10001 - x;
        } else {
            int tmp = x * y;
            y = tmp & 0xffff;
            x = tmp >>> 16;
            x = (y - x) + ((y < x) ? 1 : 0);
        }
        return x & 0xffff;
    }
    private void encrypt(int[] key, byte[] inbytes, byte[] outbytes) {
        int k = 0;
        int a = bytesToInt(inbytes, 0);
        int b = bytesToInt(inbytes, 2);
        int c = bytesToInt(inbytes, 4);
        int d = bytesToInt(inbytes, 6);
        for (int i = 0; i < 8; i++) {
            a = x_multiply_y(a, key[k++]);
            b += key[k++];
            b &= 0xffff;
            c += key[k++];
            c &= 0xffff;
            d = x_multiply_y(d, key[k++]);
            int tmp1 = b;
            int tmp2 = c;
            c ^= a;
            b ^= d;
            c = x_multiply_y(c, key[k++]);
            b += c;
            b &= 0xffff;
            b = x_multiply_y(b, key[k++]);
            c += b;
            c &= 0xffff;
            a ^= b;
            d ^= c;
            b ^= tmp2;
            c ^= tmp1;
        }
        intToBytes(x_multiply_y(a, key[k++]), outbytes, 0);
        intToBytes(c + key[k++], outbytes, 2);
        intToBytes(b + key[k++], outbytes, 4);
        intToBytes(x_multiply_y(d, key[k]), outbytes, 6);
    }
    private int[] encrypt_subkey(byte[] byteKey) {
        int[] key = new int[52];
        if (byteKey.length < 16) {
            byte[] tmpkey = new byte[16];
            System.arraycopy(byteKey, 0, tmpkey, tmpkey.length - byteKey.length, byteKey.length);
            byteKey = tmpkey;
        }
        for (int i = 0; i < 8; i++) {
            key[i] = bytesToInt(byteKey, i * 2);
        }
        for (int j = 8; j < 52; j++) {
            if ((j & 0x7) < 6) {
                key[j] = (((key[j - 7] & 0x7f) << 9) | (key[j - 6] >> 7)) & 0xffff;
            } else if ((j & 0x7) == 6) {
                key[j] = (((key[j - 7] & 0x7f) << 9) | (key[j - 14] >> 7)) & 0xffff;
            } else {
                key[j] = (((key[j - 15] & 0x7f) << 9) | (key[j - 14] >> 7)) & 0xffff;
            }
        }
        return key;
    }
    private int fun_a(int a) {
        if (a < 2) {
            return a;
        }
        int b = 1;
        int c = 0x10001 / a;
        for (int i = 0x10001 % a; i != 1;) {
            int d = a / i;
            a %= i;
            b = (b + (c * d)) & 0xffff;
            if (a == 1) {
                return b;
            }
            d = i / a;
            i %= a;
            c = (c + (b * d)) & 0xffff;
        }
        return (1 - c) & 0xffff;
    }
    private int fun_b(int b) {
        return (0 - b) & 0xffff;
    }
    private int[] uncrypt_subkey(int[] key) {
        int dec = 52;
        int asc = 0;
        int[] unkey = new int[52];
        int aa = fun_a(key[asc++]);
        int bb = fun_b(key[asc++]);
        int cc = fun_b(key[asc++]);
        int dd = fun_a(key[asc++]);
        unkey[--dec] = dd;
        unkey[--dec] = cc;
        unkey[--dec] = bb;
        unkey[--dec] = aa;
        for (int k1 = 1; k1 < 8; k1++) {
            aa = key[asc++];
            bb = key[asc++];
            unkey[--dec] = bb;
            unkey[--dec] = aa;
            aa = fun_a(key[asc++]);
            bb = fun_b(key[asc++]);
            cc = fun_b(key[asc++]);
            dd = fun_a(key[asc++]);
            unkey[--dec] = dd;
            unkey[--dec] = bb;
            unkey[--dec] = cc;
            unkey[--dec] = aa;
        }
        aa = key[asc++];
        bb = key[asc++];
        unkey[--dec] = bb;
        unkey[--dec] = aa;
        aa = fun_a(key[asc++]);
        bb = fun_b(key[asc++]);
        cc = fun_b(key[asc++]);
        dd = fun_a(key[asc]);
        unkey[--dec] = dd;
        unkey[--dec] = cc;
        unkey[--dec] = bb;
        unkey[--dec] = aa;
        return unkey;
    }
    private int[] get_subkey(boolean flag, byte[] bytekey) {
        if (flag) {
            return encrypt_subkey(bytekey);
        } else {
            return uncrypt_subkey(encrypt_subkey(bytekey));
        }
    }
    private byte[] ByteDataFormat(byte[] data, int unit) {
        int len = data.length;
        int padlen = unit - (len % unit);
        int newlen = len + padlen;
        byte[] newdata = new byte[newlen];
        System.arraycopy(data, 0, newdata, 0, len);
        for (int i = len; i < newlen; i++)
            newdata[i] = (byte) padlen;
        return newdata;
    }
    public byte[] IdeaEncrypt(byte[] idea_key, byte[] idea_data, boolean flag) {
        byte[] format_key = ByteDataFormat(idea_key, 16);
        byte[] format_data = ByteDataFormat(idea_data, 8);
        int datalen = format_data.length;
        int unitcount = datalen / 8;
        byte[] result_data = new byte[datalen];
        for (int i = 0; i < unitcount; i++) {
            byte[] tmpkey = new byte[16];
            byte[] tmpdata = new byte[8];
            System.arraycopy(format_key, 0, tmpkey, 0, 16);
            System.arraycopy(format_data, i * 8, tmpdata, 0, 8);
            byte[] tmpresult = Encrypt(tmpkey, tmpdata, flag);
            System.arraycopy(tmpresult, 0, result_data, i * 8, 8);
        }
        return result_data;
    }
    public static String byte2hex(byte[] b) { // 一个字节的数,
        // 转成16进制字符串
        String hs = "";
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1)
                hs = hs + "0" + stmp;
            else
                hs = hs + stmp;
        }
        return hs.toUpperCase(); // 转成大写
    }
    public static byte[] hex2byte(byte[] b) {
        if ((b.length % 2) != 0)
            throw new IllegalArgumentException("长度不是偶数");
        byte[] b2 = new byte[b.length / 2];
        for (int n = 0; n < b.length; n += 2) {
            String item = new String(b, n, 2);
            b2[n / 2] = (byte) Integer.parseInt(item, 16);
        }
        return b2;
    }
}

//Main.java
package org.example;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) throws NoSuchPaddingException, IllegalBlockSizeException, NoSuchAlgorithmException, InvalidKeySpecException, BadPaddingException, InvalidKeyException {
        PW p;
        PWFactory pwf=null;
        System.out.println("请选择加密算法:1、DES算法;2、IDEA算法");
        Scanner sc=new Scanner(System.in);
        String a=sc.next();
        if(a.equals("1")){
            pwf=new DESFactory();

        }else if(a.equals("2")){
            pwf=new IDEAFactory();
        }else{
            System.out.println("没有这个选项哦~");
        }
        p=pwf.createProduce();
        p.show();
    }
}

DES加密算法:

IDEA加密算法:

标签:Java,String,--,代码,return,int,key,new,byte
From: https://www.cnblogs.com/liuzijin/p/17762577.html

相关文章

  • 144-15
    对满二叉树,知其先序序列,求后序序列直接被代码吧,反正也不难#include<stdio.h>#include<stdlib.h>typedefstructnode{intdata;structnode*lchild,*rchild;}TreeNode,*Tree;voidPreToLat(int*A,intAfront,intArear,int*B,intBfront,intBrear){......
  • Linux终端常见命令
    Linux终端常见命令ls查看当前目录cdnoip跳转到noip文件夹g++a.cpp-std=c++14-O2-oa编译a.cpp,生成了一个名为a的文件(生成的文件没有扩展名,O2大写,-o小写)./a运行amorea.out查看a.out(a.in同理)clear清空终端......
  • QT 给图片添加一层颜色遮罩
    最近公司需求,在一张带有透明度的图片上增加一层颜色遮罩,记录一下。1#include<QImage>2#include<QPainter>34intmain(){5//行数56//加载原始图像7QImageoriginalImage("path/to/your/image.png");89//行数910//创建......
  • go 1
    variable&consteclipsekeymapalt+->=stepintoalt+<-=stepoutctrl+d=deletea:=1cannotbeusedtodeclareglobalvariableonepackageonemain(){}CONSTcanonlydefinebool,number,stringconst( x=16 y)=>y=16......
  • 师生关系
    师生关系目录师生关系我印象深刻的老师对博客的见解我印象深刻的老师我很幸运地遇到了两位化学老师,XYL和CTT。X老师是我初中的化学老师,他的课堂充满活力,他打破了灌输式传授的常态,用自己的言行“演绎”出了初中的化学知识。正因如此,我对化学才有更浓厚的兴趣。高中的CTT老师可谓......
  • 10.19
    今天学习Ajax,   ......
  • 10.12
    上午上了统一建模语言以及体育课,统一建模语言讲了类和功能,老师也对我们的选题进行了修改,体育课,老师讲了蓝球的防守动作,以及三步上篮,最后二十分钟进行了比赛,最后我们以2:1拿下了比赛,很惊险,下午上了数据结构和离散数学,数据结构复习了二叉树的遍历,以及,前序,中序,后序遍历顺序的特点以及......
  • Huawei模拟器的一些问题记录
    1.每次更改配置弹出的命令,使用该命令进行屏蔽。2.进入系统模式system-view命令:<Huawei>--->[Huawei]3.ctrl+z后退出后才能进行save命令4.展示命令:displayportvlandisplayvlan......
  • HCIA-动态路由RIP
    前言路由信息协议RPI(RoutingInformationProtocol)是一种基于距离矢量算法的协议,以跳数作为度量来衡量到达目的网络的距离。RIP主要用于规模较小的网络中。它配置简单、易于维护、适合小型网络RIP简介距离矢量路由协议;属于IGP协议适用于小型网络;有RIPv1、RIPv2两个版本......
  • 每日总结
    10.12从今天开始写总结,其实之前就想开始的,但是操作太复杂了,而且我也懒,不想开始。但是时间一长有些写过的题技巧和方法都忘了,还是写写吧。P7828[CCO2021]SwapSwapSorthttps://www.luogu.com.cn/problem/P7828 这题根号分治,对出现次数不大于S的数直接双指针暴力,对出现次数......