java-配置文件加密算法

目录

工具类-PropUtils.java

DES加密

工具类--SecurityUtil

DESCoder 

BASE64Encoder 

AES算法

工具类--AESUtil 

SHA256算法

工具类


工具类-PropUtils.java

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加密

工具类--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;  
    }  
}

参考:https://www.iteye.com/blog/dushen-2405528

AES算法

工具类--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);
	}
}

参考:https://blog.csdn.net/qq_23888451/article/details/84658360

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

SHA256算法

工具类

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Sha256 {
 
    /**
    * 利用java原生的类实现SHA256加密
    * @param str 加密后的报文
    * @return
    */
    public static String getSHA256(String str){
      MessageDigest messageDigest;
     String encodestr = "";
     try {
      messageDigest = MessageDigest.getInstance("SHA-256");
      messageDigest.update(str.getBytes("UTF-8"));
      encodestr = byte2Hex(messageDigest.digest());
     } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
     } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
     }
     return encodestr;
    }
    /**
    * 将byte转为16进制
    * @param bytes
    * @return
    */
    private static String byte2Hex(byte[] bytes){
     StringBuffer stringBuffer = new StringBuffer();
     String temp = null;
     for (int i=0;i<bytes.length;i++){
      temp = Integer.toHexString(bytes[i] & 0xFF);
      if (temp.length()==1){
      //1得到一位的进行补0操作
      stringBuffer.append("0");
      }
      stringBuffer.append(temp);
     }
     return stringBuffer.toString();
    }

}

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
文件加密解密算法(Java源码) java,file,算法,加密解密,java源码 package com.crypto.encrypt; import java.security.SecureRandom; import java.io.*; import javax.crypto.spec.DESKeySpec; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.Cipher; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import javax.crypto.NoSuchPaddingException; import javax.crypto.BadPaddingException; import javax.crypto.IllegalBlockSizeException; import java.lang.reflect.Constructor; import java.security.spec.KeySpec; import java.lang.reflect.InvocationTargetException; public class EncryptData { private String keyfile=null; public EncryptData() { } public EncryptData(String keyfile) { this.keyfile=keyfile; } /** * 加密文件 * @param filename String 源路径 * @param filenamekey String 加密后的路径 */ public void createEncryptData(String filename,String filenamekey) throws IllegalStateException, IllegalBlockSizeException, BadPaddingException, NoSuchPaddingException, InvalidKeySpecException, NoSuchAlgorithmException, InvalidKeyException, IOException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, ClassNotFoundException, IllegalStateException, IllegalBlockSizeException, BadPaddingException, NoSuchPaddingException, InvalidKeySpecException, NoSuchAlgorithmException, InvalidKeyException, IOException { //验证keyfile if(keyfile==null || keyfile.equals("")) { throw new NullPointerException("无效的key文件路径"); } encryptData(filename,filenamekey); } /** * 加密类文件 * @param filename String 原始的类文件 * @param encryptfile String 加密后的类文件 * @throws IOException * @throws InvalidKeyException * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException * @throws NoSuchPaddingException * @throws NoSuchAlgorithmException * @throws BadPaddingException * @throws IllegalBlockSizeException * @throws IllegalStateException */ private void encryptData(String filename,String encryptfile) throws IOException, InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException, IllegalStateException, ClassNotFoundException, SecurityException, NoSuchMethodException, InvocationTargetException, IllegalArgumentException, IllegalAccessException, InstantiationException { byte data[]=Util.readFile(filename); // 执行加密操作 byte encryptedClassData[] = getencryptData(data); // 保存加密后的文件,覆盖原有的类文件。 Util.writeFile(encryptedClassData,encryptfile); } /** * 直接获得加密数据 * @param bytes byte[] * @throws IllegalStateException * @throws IllegalBlockSizeException * @throws BadPaddingException * @throws InvalidKeyException * @throws NoSuchPaddingException * @throws InvalidKeySpecException * @throws NoSuchAlgorithmException * @throws InstantiationException * @throws IllegalAccessException * @throws IllegalArgumentException * @throws InvocationTargetException * @throws NoSuchMethodException * @throws SecurityException * @throws ClassNotFoundException * @throws IOException * @return byte[] */ public byte[] createEncryptData(byte[] bytes) throws IllegalStateException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchPaddingException, InvalidKeySpecException, NoSuchAlgorithmException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, ClassNotFoundException, IOException { bytes=getencryptData(bytes); return bytes; } private byte[] getencryptData(byte[] bytes) throws IOException, ClassNotFoundException, SecurityException, NoSuchMethodException, InvocationTargetException, IllegalArgumentException, IllegalAccessException, InstantiationException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, IllegalStateException { // 产生一个可信任的随机数源 SecureRandom sr = new SecureRandom(); //从密钥文件key Filename中得到密钥数据 byte[] rawKeyData = Util.readFile(keyfile); // 从原始密钥数据创建DESKeySpec对象 Class classkeyspec=Class.forName(Util.getValue("keyspec")); Constructor constructor = classkeyspec.getConstructor(new Class[]{byte[].class}); KeySpec dks = (KeySpec) constructor.newInstance(new Object[]{rawKeyData}); // 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(Util.getAlgorithm()); SecretKey key = keyFactory.generateSecret(dks); // Cipher对象实际完成加密操作 Cipher cipher = Cipher.getInstance(Util.getAlgorithm()); // 用密钥初始化Cipher对象 cipher.init(Cipher.ENCRYPT_MODE, key, sr); // 执行加密操作 bytes = cipher.doFinal(bytes); // 返回字节数组 return bytes; } /** * 设置key文件路径 * @param keyfile String */ public void setKeyFile(String keyfile) { this.keyfile=keyfile; } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值