java configuration file encryption algorithm

PropUtils.getProperty("jdbc.username");

public class PropUtils {

    // 本地环境-研发六楼环境
    private static final String devMode = "development";
    // 正式环境
    // private static final String devMode = "production";
    // 测试环境
    //private static final String devMode = "test";

    private static final byte[] KEY = {9, -1, 0, 5, 39, 8, 6, 19};
    private static Properties prop = new Properties();

    static {
        try {
            Properties redis = new Properties();
            Properties kafka = new Properties();
            Properties jdbc = new Properties();

            redis.load(PropUtils.class.getClassLoader().getResourceAsStream("profile/" + devMode + "/redis.properties"));
            kafka.load(PropUtils.class.getClassLoader().getResourceAsStream("profile/" + devMode + "/kafka.properties"));
            jdbc.load(PropUtils.class.getClassLoader().getResourceAsStream("profile/" + devMode + "/jdbc.properties"));

            String[] keys={"jdbc.username","jdbc.password"};
            for (Object key : keys) {
                String keyStr = key.toString();
                String value = jdbc.getProperty(keyStr);
                // 使用工具类的解密算法
                value = SecurityUtil.decryptDes(value, KEY);
                jdbc.setProperty(keyStr, value);
            }
            prop.putAll(redis);
            prop.putAll(kafka);
            prop.putAll(jdbc);

        } catch (IOException e) {
            log.error("加载配置文件失败!", e);
            System.exit(1);
        }
    }

    public static String getProperty(String p) {
        return prop.getProperty(p);
    }

    public static int getInt(String p) {
        return Integer.parseInt(prop.getProperty(p));
    }

    public static boolean getBoolean(String p) {
        return Boolean.parseBoolean(prop.getProperty(p));
    }

    public static String getDevMode() {
        return devMode;
    }
}

DES encryption

Tools --SecurityUtil

public final class SecurityUtil {  
    private SecurityUtil() {  
    }  
  
    public static final String CHARSET = "UTF-8";  
  
    /** 
     * BASE64解码 
     *  
     * @param key 
     * @return 
     * @throws Exception 
     */  
    public static final byte[] decryptBASE64(String key) {  
        try {  
            return new BASE64Encoder().decode(key);  
        } catch (Exception e) {  
            throw new RuntimeException("解密错误,错误信息:", e);  
        }  
    }  
  
    /** 
     * BASE64编码 
     *  
     * @param key 
     * @return 
     * @throws Exception 
     */  
    public static final String encryptBASE64(byte[] key) {  
        try {  
            return new BASE64Encoder().encode(key);  
        } catch (Exception e) {  
            throw new RuntimeException("加密错误,错误信息:", e);  
        }  
    }  
  
  
    /** 
     * 数据解密,算法(DES) 
     *  
     * @param cryptData 
     *            加密数据 
     * @return 解密后的数据 
     */  
    public static final String decryptDes(String cryptData, byte[] key) {  
        String decryptedData = null;  
        try {  
            // 把字符串解码为字节数组,并解密  
            decryptedData = new String(DESCoder.decrypt(decryptBASE64(cryptData), key));  
        } catch (Exception e) {  
            throw new RuntimeException("解密错误,错误信息:", e);  
        }  
        return decryptedData;  
    }  
  
    /** 
     * 数据加密,算法(DES) 
     *  
     * @param data 
     *            要进行加密的数据 
     * @return 加密后的数据 
     */  
    public static final String encryptDes(String data, byte[] key) {  
        String encryptedData = null;  
        try {  
            // 加密,并把字节数组编码成字符串  
            encryptedData = encryptBASE64(DESCoder.encrypt(data.getBytes(), key));  
        } catch (Exception e) {  
            throw new RuntimeException("加密错误,错误信息:", e);  
        }  
        return encryptedData;  
    }  

  
    public static void main(String[] args) {//ROOT为要加密的明文  
        byte[] KEY = {9, -1, 0, 5, 39, 8, 6, 19};
        String encrypt = SecurityUtil.encryptDes("ROOT", KEY);  
        System.out.println(encrypt);  
        System.out.println(SecurityUtil.decryptDes(encrypt, KEY));  
    }  
  
} 

DESCoder 

import java.security.InvalidKeyException;  
import java.security.Key;  
import java.security.NoSuchAlgorithmException;  
import java.security.SecureRandom;  
import java.security.spec.InvalidKeySpecException;  
  
import javax.crypto.BadPaddingException;  
import javax.crypto.Cipher;  
import javax.crypto.IllegalBlockSizeException;  
import javax.crypto.KeyGenerator;  
import javax.crypto.NoSuchPaddingException;  
import javax.crypto.SecretKey;  
import javax.crypto.SecretKeyFactory;  
import javax.crypto.spec.DESKeySpec;  
  
/** 
 * DES安全编码组件 
 *  
 * @author du 
 * @version 1.0 
 * @since 1.0 
 */  
public abstract class DESCoder {  
  
    /** 
     * 密钥算法 <br> 
     * Java 6 只支持56bit密钥 <br> 
     * Bouncy Castle 支持64bit密钥 
     */  
    public static final String KEY_ALGORITHM = "DES";  
  
    /** 
     * 加密/解密算法 / 工作模式 / 填充方式 
     */  
    public static final String CIPHER_ALGORITHM = "DES/ECB/PKCS5PADDING";  
  
    /** 
     * 转换密钥 
     *  
     * @param key 二进制密钥 
     * @return Key 密钥 
     * @throws InvalidKeyException 
     * @throws NoSuchAlgorithmException 
     * @throws InvalidKeySpecException 
     * @throws Exception 
     */  
    private static Key toKey(byte[] key) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException {  
        // 实例化DES密钥材料  
        DESKeySpec dks = new DESKeySpec(key);  
        // 实例化秘密密钥工厂  
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(KEY_ALGORITHM);  
        // 生成秘密密钥  
        SecretKey secretKey = keyFactory.generateSecret(dks);  
        return secretKey;  
    }  
  
    /** 
     * 解密 
     *  
     * @param data 待解密数据 
     * @param key 密钥 
     * @return byte[] 解密数据 
     * @throws InvalidKeySpecException 
     * @throws NoSuchAlgorithmException 
     * @throws InvalidKeyException 
     * @throws NoSuchPaddingException 
     * @throws BadPaddingException 
     * @throws IllegalBlockSizeException 
     * @throws Exception 
     */  
    public static byte[] decrypt(byte[] data, byte[] key) throws InvalidKeyException, NoSuchAlgorithmException,  
            InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {  
        // 还原密钥  
        Key k = toKey(key);  
        // 实例化  
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);  
        // 初始化,设置为解密模式  
        cipher.init(Cipher.DECRYPT_MODE, k);  
        // 执行操作  
        return cipher.doFinal(data);  
    }  
  
    /** 
     * 加密 
     *  
     * @param data 待加密数据 
     * @param key 密钥 
     * @return byte[] 加密数据 
     * @throws NoSuchPaddingException 
     * @throws NoSuchAlgorithmException 
     * @throws InvalidKeyException 
     * @throws BadPaddingException 
     * @throws IllegalBlockSizeException 
     * @throws InvalidKeySpecException 
     * @throws Exception 
     */  
    public static byte[] encrypt(byte[] data, byte[] key) throws NoSuchAlgorithmException, NoSuchPaddingException,  
            InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidKeySpecException {  
        // 还原密钥  
        Key k = toKey(key);  
        // 实例化  
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);  
        // 初始化,设置为加密模式  
        cipher.init(Cipher.ENCRYPT_MODE, k);  
        // 执行操作  
        return cipher.doFinal(data);  
    }  
  
    /** 
     * 生成密钥 <br> 
     * Java 6 只支持56bit密钥 <br> 
     * Bouncy Castle 支持64bit密钥 <br> 
     *  
     * @return byte[] 二进制密钥 
     * @throws NoSuchAlgorithmException 
     * @throws Exception 
     */  
    public static byte[] initKey() throws NoSuchAlgorithmException {  
        /* 
         * 实例化密钥生成器 
         *  
         * 若要使用64bit密钥注意替换 将下述代码中的KeyGenerator.getInstance(CIPHER_ALGORITHM); 
         * 替换为KeyGenerator.getInstance(CIPHER_ALGORITHM, "BC"); 
         */  
        KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);  
        /* 
         * 初始化密钥生成器 若要使用64bit密钥注意替换 将下述代码kg.init(56); 替换为kg.init(64); 
         */  
        kg.init(56, new SecureRandom());  
        // 生成秘密密钥  
        SecretKey secretKey = kg.generateKey();  
        // 获得密钥的二进制编码形式  
        return secretKey.getEncoded();  
    }  
}

BASE64Encoder 

import java.io.ByteArrayInputStream;  
import java.io.ByteArrayOutputStream;  
import java.io.IOException;  
import java.io.InputStream;  
import java.io.OutputStream;  
import java.io.PushbackInputStream;  
  
/** 
 * 密码器类 
 *  
 * @author du 
 * @since 2017-11-19 
 */  
public class BASE64Encoder {  
  
    /** 
     * 译码数据源 
     */  
    private static final char[] PEM_ARRAY = {  
        // 0  1   2   3    4    5    6    7  
        'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', // 0  
        'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', // 1  
        'q', 'r', 's', 't', 'u', 'v', 'w', 'x', // 2  
        'y', 'z', '1', '2', '3', '4', '5', '6', // 3  
        '7', '8', '9', '0', 'A', 'B', 'C', 'D', // 4  
        'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', // 5  
        'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', // 6  
        'U', 'V', 'W', 'X', 'Y', 'Z', '+', '/' // 7  
    };  
  
    private static final byte[] pem_convert_array = new byte[256];  
  
    private byte[] decode_buffer = new byte[4];  
  
    public BASE64Encoder() {  
    }  
  
    /** 
     * 编码 
     */  
    public String encode(byte[] bt) {  
        int totalBits = bt.length * 8;  
        int nn = totalBits % 6;  
        int curPos = 0;// process bits  
        StringBuilder toReturn = new StringBuilder(32);  
        while (curPos < totalBits) {  
            int bytePos = curPos / 8;  
            switch (curPos % 8) {  
            case 0:  
                toReturn.append(PEM_ARRAY[(bt[bytePos] & 0xfc) >> 2]);  
                break;  
            case 2:  
                toReturn.append(PEM_ARRAY[(bt[bytePos] & 0x3f)]);  
                break;  
            case 4:  
                if (bytePos == bt.length - 1) {  
                    toReturn.append(PEM_ARRAY[((bt[bytePos] & 0x0f) << 2) & 0x3f]);  
                } else {  
                    int pos = (((bt[bytePos] & 0x0f) << 2) | ((bt[bytePos + 1] & 0xc0) >> 6)) & 0x3f;  
                    toReturn.append(PEM_ARRAY[pos]);  
                }  
                break;  
            case 6:  
                if (bytePos == bt.length - 1) {  
                    toReturn.append(PEM_ARRAY[((bt[bytePos] & 0x03) << 4) & 0x3f]);  
                } else {  
                    int pos = (((bt[bytePos] & 0x03) << 4) | ((bt[bytePos + 1] & 0xf0) >> 4)) & 0x3f;  
                    toReturn.append(PEM_ARRAY[pos]);  
                }  
                break;  
            default:  
                break;  
            }  
            curPos += 6;  
        }  
        if (nn == 2) {  
            toReturn.append("==");  
        } else if (nn == 4) {  
            toReturn.append("=");  
        }  
        return toReturn.toString();  
    }  
  
    /** 
     * 解码 
     */  
    public byte[] decode(String str) throws IOException {  
        byte[] arrayOfByte = str.getBytes();  
        ByteArrayInputStream inputStream = new ByteArrayInputStream(arrayOfByte);  
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();  
        decodeBuffer(inputStream, outputStream);  
        return outputStream.toByteArray();  
    }  
  
    private void decodeBuffer(InputStream paramInputStream, OutputStream paramOutputStream) throws IOException {  
        PushbackInputStream localPushbackInputStream = new PushbackInputStream(paramInputStream);  
        int j = 0;  
        while (true) {  
            try {  
                int k = bytesPerLine();  
                int i = 0;  
                if (i + bytesPerAtom() < k) {  
                    decodeAtom(localPushbackInputStream, paramOutputStream, bytesPerAtom());  
                    j += bytesPerAtom();  
                    i += bytesPerAtom();  
                    continue;  
                }  
  
                if (i + bytesPerAtom() == k) {  
                    decodeAtom(localPushbackInputStream, paramOutputStream, bytesPerAtom());  
                    j += bytesPerAtom();  
                } else {  
                    decodeAtom(localPushbackInputStream, paramOutputStream, k - i);  
                    j += k - i;  
                }  
            } catch (RuntimeException e) {  
                String.valueOf(j);  
                break;  
            }  
        }  
    }  
  
    private int bytesPerAtom() {  
        return 4;  
    }  
  
    private int bytesPerLine() {  
        return 72;  
    }  
  
    private void decodeAtom(PushbackInputStream paramPushbackInputStream, OutputStream paramOutputStream, int paramInt)  
        throws IOException {  
        int i;  
        int j = -1;  
        int k = -1;  
        int m = -1;  
        int n = -1;  
  
        if (paramInt < 2) {  
            throw new java.lang.ArrayStoreException("BASE64Decoder: Not enough bytes for an atom.");  
        }  
        do {  
            i = paramPushbackInputStream.read();  
            if (i == -1) {  
                throw new RuntimeException();  
            }  
        } while ((i == 10) || (i == 13));  
        this.decode_buffer[0] = (byte)i;  
  
        i = readFully(paramPushbackInputStream, this.decode_buffer, 1, paramInt - 1);  
        if (i == -1) {  
            throw new RuntimeException();  
        }  
  
        if ((paramInt > 3) && (this.decode_buffer[3] == 61)) {  
            paramInt = 3;  
        }  
        if ((paramInt > 2) && (this.decode_buffer[2] == 61)) {  
            paramInt = 2;  
        }  
        switch (paramInt) {  
        case 4:  
            n = pem_convert_array[(this.decode_buffer[3] & 0xFF)];  
        case 3:  
            m = pem_convert_array[(this.decode_buffer[2] & 0xFF)];  
        case 2:  
            k = pem_convert_array[(this.decode_buffer[1] & 0xFF)];  
            j = pem_convert_array[(this.decode_buffer[0] & 0xFF)];  
        }  
  
        switch (paramInt) {  
        case 2:  
            paramOutputStream.write((byte)(j << 2 & 0xFC | k >>> 4 & 0x3));  
            break;  
        case 3:  
            paramOutputStream.write((byte)(j << 2 & 0xFC | k >>> 4 & 0x3));  
            paramOutputStream.write((byte)(k << 4 & 0xF0 | m >>> 2 & 0xF));  
            break;  
        case 4:  
            paramOutputStream.write((byte)(j << 2 & 0xFC | k >>> 4 & 0x3));  
            paramOutputStream.write((byte)(k << 4 & 0xF0 | m >>> 2 & 0xF));  
            paramOutputStream.write((byte)(m << 6 & 0xC0 | n & 0x3F));  
        }  
    }  
  
    private int readFully(InputStream paramInputStream, byte[] paramArrayOfByte, int paramInt1, int paramInt2)  
        throws IOException {  
        for (int i = 0; i < paramInt2; i++) {  
            int j = paramInputStream.read();  
            if (j == -1) {  
                return i == 0 ? -1 : i;  
            }  
            paramArrayOfByte[(i + paramInt1)] = (byte)j;  
        }  
        return paramInt2;  
    }  
  
    static {  
        for (int i = 0; i < 255; i++) {  
            pem_convert_array[i] = -1;  
        }  
        for (int i = 0; i < PEM_ARRAY.length; i++)  
            pem_convert_array[PEM_ARRAY[i]] = (byte)i;  
    }  
}

Reference: https://www.iteye.com/blog/dushen-2405528

AES algorithm

Tools --AESUtil 

public class AESUtil {
	private static String key= "123456";
	/**
	 * 加密
	 * @param content待加密内容
	 * @param key 加密的密钥
	 * @return
	 */
	public static String encrypt(String content, String key) {
		try {
			KeyGenerator kgen = KeyGenerator.getInstance("AES");//构造密钥生成器,指定为AES算法,不区分大小写
			kgen.init(128, new SecureRandom(key.getBytes()));
			SecretKey secretKey = kgen.generateKey();
			byte[] enCodeFormat = secretKey.getEncoded();
			SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
			Cipher cipher = Cipher.getInstance("AES");
			byte[] byteContent = content.getBytes("utf-8");
			cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);//ENCRYPT_MODE指加密操作
			byte[] byteRresult = cipher.doFinal(byteContent);
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < byteRresult.length; i++) {
				String hex = Integer.toHexString(byteRresult[i] & 0xFF);
				if (hex.length() == 1) {
					hex = '0' + hex;
				}
				sb.append(hex.toUpperCase());
			}
			return sb.toString();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		}
		return null;
	}	
	/**
	 * 解密 
	 * @param content 待解密内容
	 * @param key 解密的密钥
	 * @return
	 */
	public static String decrypt(String content, String key) {
		if (content.length() < 1)
			return null;
		byte[] byteRresult = new byte[content.length() / 2];
		for (int i = 0; i < content.length() / 2; i++) {
			int high = Integer.parseInt(content.substring(i * 2, i * 2 + 1), 16);
			int low = Integer.parseInt(content.substring(i * 2 + 1, i * 2 + 2),16);
			byteRresult[i] = (byte) (high * 16 + low);
		}
		try {
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
		    SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");  
		    secureRandom.setSeed(key.getBytes()); 
			kgen.init(128, secureRandom);
			SecretKey secretKey = kgen.generateKey();
			byte[] enCodeFormat = secretKey.getEncoded();
			SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
			Cipher cipher = Cipher.getInstance("AES");
			cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);//Decrypt_mode指解密操作
			byte[] result = cipher.doFinal(byteRresult);
			return new String(result,"utf-8");//不加utf-8,中文时会乱码
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		}catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	//重载的方法,使用默认密钥
	public static String decrypt(String content) {
		return decrypt(content, key);
	}
	public static String encrypt(String content) {
		return encrypt(content, key);
	}
}

Reference: https://blog.csdn.net/qq_23888451/article/details/84658360

Published 49 original articles · won praise 7 · views 10000 +

Guess you like

Origin blog.csdn.net/csdnzhang365/article/details/103464041