编程知识 cdmana.com

Java -- desutil encryption and decryption tool class

The tool class code is as follows :

package util;


import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;

/**
 * 3DES Encryption utility class 
 *
 * @author shijing
 * @DATE 2020/9/15 11:22
 */
public class DESUtils {


    /**
     *  Set a private key at will ( The length must be 24 position )
     */
    public static final String SECRET_KEY = "ABCDEFGHIJKLMN1234567890";

    /**
     *  encryption 
     *
     * @param inStr      What needs to be encrypted 
     * @param secretKey  secret key 
     * @return  Encrypted data 
     */

    public static String encrypt(String inStr, String secretKey) {

        SecretKey deskey = new SecretKeySpec(secretKey.getBytes(), "DESede");

        Cipher cipher;

        String outStr = null;

        try {

            cipher = Cipher.getInstance("DESede");

            cipher.init(Cipher.ENCRYPT_MODE, deskey);

            outStr = byte2hex(cipher.doFinal(inStr.getBytes()));

        } catch (Exception e) {

            System.err.println("3DES Encryption abnormal "+ e.getMessage());
        }
        System.out.println("3DES Encrypted string :" + outStr);

        return outStr;

    }

    /**
     *  Decrypt 
     *
     * @param inStr      Content to decrypt 
     * @param secretKey  secret key 
     * @return  Decrypted data 
     */

    public static String decrypt(String inStr, String secretKey) {

        SecretKey deskey = new SecretKeySpec(secretKey.getBytes(), "DESede");

        Cipher cipher;
        String outStr = null;

        try {

            cipher = Cipher.getInstance("DESede");

            cipher.init(Cipher.DECRYPT_MODE, deskey);

            outStr = new String(cipher.doFinal(hex2byte(inStr)));

        } catch (Exception e) {

            System.err.println("3DES Decryption abnormal "+e.getMessage());

        }
        System.out.println("3DES Decrypted data :" + outStr);

        return outStr;

    }

    /**
     *  Turn into 16 Base string method 
     *
     * @param digest  The byte group that needs to be converted 
     * @return  Converted String 
     */

    private static String byte2hex(byte[] digest) {

        StringBuffer hs = new StringBuffer();

        String stmp = "";

        for (int n = 0; n < digest.length; n++) {

            stmp = Integer.toHexString(digest[n] & 0XFF);

            if (stmp.length() == 1) {

                hs.append("0" + stmp);

            } else {

                hs.append(stmp);

            }

        }

        return hs.toString().toUpperCase();

    }

    /**
     *  16 to binary 
     *
     * @param hexStr  To be converted 16 Base string 
     * @return  Byte group binary 
     */

    public static byte[] hex2byte(String hexStr) {

        if (hexStr == null)

            return null;

        hexStr = hexStr.trim();

        int len = hexStr.length();

        if (len == 0 || len % 2 == 1)

            return null;

        byte[] digest = new byte[len / 2];

        try {

            for (int i = 0; i < hexStr.length(); i += 2) {

                digest[i / 2] = (byte) Integer.decode("0x" + hexStr.substring(i, i + 2)).intValue();

            }
            return digest;

        } catch (Exception e) {

            return null;

        }

    }


    public static void main(String[] args) {
//        String pwd = "11111111";
//        String encrypt = encrypt(pwd,SECRET_KEY);
//        System.out.println(encrypt);
//
//        System.out.println(decrypt("6AFD5420C5BB8F4F",SECRET_KEY));
//        System.out.println(decrypt(encrypt,SECRET_KEY));

        int num = 0;
        do {
            Scanner sc = new Scanner(System.in);
            System.out.println(" Please enter the type number to encrypt : 1、 Encrypted account password string    2、 encryption xsd file   3、 Decrypt data ");
            String str = sc.nextLine();
            if (str.equals("1")) {
                System.out.println(" Please enter the data to be encrypted :");
                String data = sc.nextLine();
                System.out.println(" The encrypted data is :" + encrypt(data, SECRET_KEY));
            } else if(str.equals("2")){
                System.out.println(" Please enter the... To be encrypted xsd route :");
                String xsdPath = sc.nextLine();
                System.out.println(" Encrypted xsd The content is :" + encryptXsd(xsdPath));
            } else {
                System.out.println(" Please enter the data to be decrypted :");
                String data = sc.nextLine();
                System.out.println(" The decrypted data is :" + decrypt(data, SECRET_KEY));
            }
            System.out.println(" Do you want to continue ? 0  continue , 1  sign out ");
            num = sc.nextInt();
        } while (num==0);
        System.exit(0);

    }



    public static String encryptXsd(String xsdPath){
        ByteArrayInputStream bytein = null;
        String data = null;
//        String xsdPath = "xsd/pacs.008.001.06.xsd";
        try{
            BufferedReader bufferedReader = Files.newBufferedReader(Paths.get(DESUtils.class.getClassLoader().getResource(xsdPath).toURI())) ;
            StringBuilder stringBuilder = new StringBuilder();
            String liner = "";
            while ((liner = bufferedReader.readLine()) != null) {
                stringBuilder.append(liner);
            }
            System.out.println(" Read the xsd Content :" + stringBuilder.toString());
            data = encrypt(stringBuilder.toString(),SECRET_KEY);
            System.out.println(" Encrypted content :" + data);
            bytein = new ByteArrayInputStream(data.getBytes());
            String decStr = decrypt(data,SECRET_KEY);
            System.out.println(" Content after decryption :" + decStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  data;
    }
}

Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .

版权声明
本文为[The blank of writing memory]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201224104023987a.html

Scroll to Top