文件加解密


```java
package com.dstz.base.core.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
import java.util.StringTokenizer;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.lang3.StringUtils;

/**
 * <p></p>
 * @author 周小建
 * @create 2014-12-24
 * @update
 * @className Encrypt
 * extends 
 * implements
 * @version v1.0
 * @description 加密解密接口 
 */
public class Encrypt{
	private static final String password="e_f_codd";
	private static final String encoding="GBK";

	/*
	private final static Encrypt encrypt=new Encrypt();
	public Encrypt(){}
	public static Encrypt getInstance(){
		return encrypt;
	}
	*/

	/**
	 * <p></p>
	 * @author 周小建
	 * @created 2008-12-03
	 * @update
	 * @version v1.0
	 * @description 16进制字符数组
	 */
	private static final String[]hexDigits={"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"};

	/**
	 * <p></p>
	 * @author 周小建
	 * @created 2008-12-03
	 * @update
	 * @version v1.0
	 * @description AES密匙
	 */
	private static final byte[]keyByte={0x11,0x22,0x4F,0x58,(byte)0x88,0x10,0x40,0x38,0x28,0x25,0x79,0x51,(byte)0xCB,(byte)0xDD,0x55,0x66};//16字节的密钥,可以改变

	/**
	 * <p></p>
	 * @author 周小建
	 * @created 2008-12-03
	 * @update
	 * @param byte b
	 * @return String
	 * @throws 
	 * @version v1.0
	 * @description 一位Byte到16进制字符串的转换
	 */
	private static String byteToHexString(byte b){
		int n=b;
		if(n<0)n=256+n;
		int d1=n/16;
		int d2=n%16;
		return hexDigits[d1]+hexDigits[d2];
	}

	/**
	 * <p></p>
	 * @author 周小建
	 * @created 2008-12-03
	 * @update
	 * @param byte b
	 * @return String
	 * @throws 
	 * @version v1.0
	 * @description Byte数组到16进制字符串的转换
	 */
	private static String byteArrayToHexString(byte[] b){
		StringBuffer resultSb=new StringBuffer();
		for(int i=0;i<b.length;i++)resultSb.append(byteToHexString(b[i]));
		return resultSb.toString();
	}

	/**
	 * <p></p>
	 * @author 周小建
	 * @created 2008-12-03
	 * @update
	 * @param String b
	 * @return byte
	 * @throws 
	 * @version v1.0
	 * @description 16进制字符串到Byte转换
	 */
	private static byte HexStringTobyte(String b){
		int By=0;
		String b1=b.substring(0,1);
		int b11=-1;
		String b2=b.substring(1);
		int b12=-1;
		for(int i=0;i<16;i++)if(b1.equals(hexDigits[i]))b11=i;
		for(int i=0;i<16;i++)if(b2.equals(hexDigits[i]))b12=i;
		By=b11*16+b12;
		if(By>256)By=By-256;
		return (byte)By;
	}

	/**
	 * <p></p>
	 * @author 周小建
	 * @created 2008-12-03
	 * @update
	 * @param String b
	 * @return byte[]
	 * @throws 
	 * @version v1.0
	 * @description 16进制字符串到Byte数组的转换
	 */
	private static byte[]HexStringTobyteArray(String b){
		byte[]r=new byte[b.length()/2];
		for(int i=0;i<b.length()/2;i++)r[i]=HexStringTobyte(b.substring(i * 2,i * 2 + 2));
		return r;
	}
	
	/**
	 * <p></p>
	 * @author 周小建
	 * @created 2008-12-03
	 * @update
	 * @param String s
	 * @return String
	 * @throws 
	 * @version v1.0
	 * @description 将16进制编码的字符串转换为带有空格分隔的字符串
	 				比如:F89ADFCA2AE9719817D3575A9540600C ==>  -8 -102 -33 -54 42 -23 113 -104 23 -45 87 90 -107 64 96 12
	 */
	private static String hex2string(String s){
		String ret="";
		for(int i=0;i<s.length()/2;i++)ret+=String.valueOf(Integer.parseInt(s.substring(2*i,2*i+2),16))+" ";
		if(ret.endsWith(" "))return ret.substring(0,ret.length()-1);
		return ret;
	}

	/**
	 * <p></p>
	 * @author 周小建
	 * @created 2008-12-03
	 * @update
	 * @param String str
	 * @return String
	 * @throws 
	 * @version v1.0
	 * @description 将加密的带有空格分隔的字符转换为16进制编码的字符串.
	 				比如:-8 -102 -33 -54 42 -23 113 -104 23 -45 87 90 -107 64 96 12  ==> F89ADFCA2AE9719817D3575A9540600C
	 */
	private static String string2hex(String str){
		String[]split=str.split(" ");
		byte[]b=new byte[split.length];
		for(int i=0;i<split.length;i++)b[i]=Byte.parseByte(split[i]);
		String hs="";
		String stmp="";
		for(int n=0;n<b.length;n++){
			stmp=(Integer.toHexString(b[n] & 0XFF));
			if(stmp.length()==1)hs=hs+"0"+stmp;
			else hs=hs+stmp;
		}
		return hs.toUpperCase();
	}
	
	/**
	 * <p></p>
	 * @author 周小建
	 * @created 2008-12-03
	 * @update
	 * @param byte[]arr
	 * @return String
	 * @throws 
	 * @version v1.0
	 * @description 返回十六进制字符串
	 */
	private static String hex(byte[] arr){
		StringBuffer sb=new StringBuffer();
		for(int i=0;i<arr.length;++i)sb.append(Integer.toHexString((arr[i] & 0xFF) | 0x100).substring(1,3));
		return sb.toString();
	}
	
	private static String getRandomKey(){
		Random ran = new Random();
		int prefix = ran.nextInt(90000000) + 10000000;
		int suffix = ran.nextInt(90000000) + 10000000;
		return String.valueOf(prefix) + String.valueOf(suffix);
	}

	
	//
	/**
	 * <p></p>
	 * @author 周小建
	 * @created 2008-12-03
	 * @update
	 * @param String text
	 * @return String
	 * @throws Exception
	 * @version v1.0
	 * @description 将传进来的明文以AES算法进行加密
	 */
	public static String enCodeAES(String text){
		try{
			byte[]OriByte=text.getBytes(encoding);
			SecretKey key=new SecretKeySpec(keyByte,"AES");//通过SecretKeySpec形成一个key
			Cipher cipher=Cipher.getInstance("AES/ECB/PKCS5Padding");//获得一个私鈅加密类Cipher,ECB是加密方式,PKCS5Padding是填充方法
			cipher.init(Cipher.ENCRYPT_MODE,key);//使用私鈅加密
			byte[]OriCipherText=cipher.doFinal(OriByte);
			String b=byteArrayToHexString(OriCipherText);
			return b;//密码,转换成16进制
		}catch(Exception e){
			e.printStackTrace();
			return "";
		}
	}
	
	/**
	 * <p></p>
	 * @author 周小建
	 * @created 2008-12-03
	 * @update
	 * @param String encryptText
	 * @return String
	 * @throws Exception
	 * @version v1.0
	 * @description 将加密文本进行解密
	 */
	public static String deCodeAES(String encryptText){
		try{
			SecretKey key=new SecretKeySpec(keyByte,"AES");//通过SecretKeySpec形成一个key
			Cipher cipher=Cipher.getInstance("AES/ECB/PKCS5Padding");//获得一个私鈅加密类Cipher,ECB是加密方式,PKCS5Padding是填充方法
			cipher.init(Cipher.DECRYPT_MODE,key);//使用私鈅解密
			byte[]NewCipherText=HexStringTobyteArray(encryptText);
			byte[]newString=cipher.doFinal(NewCipherText);
			return new String(newString,encoding);
		}catch(Exception e){
			e.printStackTrace();
			return "";
		}
	}
	
	/**
	 * <p></p>
	 * @author 周小建
	 * @created 2008-12-03
	 * @update
	 * @param String text
	 * @return String
	 * @throws Exception
	 * @version v1.0
	 * @description 将传进来的明文以PBEWithMD5AndDES算法进行加密
	 */
	public static String encrypt(String text){
		try{
			if(text==null||text.length()==0)return "";
			PBEKeySpec pbks=new PBEKeySpec(password.toCharArray());
			SecretKeyFactory skf=SecretKeyFactory.getInstance("PBEWithMD5AndDES");
			SecretKey k=skf.generateSecret(pbks);
			byte[]salt=new byte[8];
			Random r=new Random();
			r.nextBytes(salt);
			Cipher cp=Cipher.getInstance("PBEWithMD5AndDES");
			PBEParameterSpec ps=new PBEParameterSpec(salt,1000);
			cp.init(Cipher.ENCRYPT_MODE,k,ps);
			byte[]ptext=text.getBytes(encoding);
			byte[]ctext=cp.doFinal(ptext);
			String result="";
			for(int i=0;i<salt.length;i++)result+=salt[i] + " ";
			for(int i=0;i<ctext.length;i++)result+=ctext[i] + " ";
			return string2hex(result);
		}catch(Exception e){
			e.printStackTrace();
			return "";
		}
	}

	/**
	 * <p></p>
	 * @author 周小建
	 * @created 2008-12-03
	 * @update
	 * @param String encryptText
	 * @return String
	 * @throws Exception
	 * @version v1.0
	 * @description 将加密文本进行解密,将密文以PBEWithMD5AndDES算法进行解密
	 */
	public static String decrypt(String encryptText){
		try{
			if(encryptText==null||encryptText.length()==0)return "";
			PBEKeySpec pbks=new PBEKeySpec((password).toCharArray());
			SecretKeyFactory skf=SecretKeyFactory.getInstance("PBEWithMD5AndDES");
			SecretKey k=skf.generateSecret(pbks);
			StringTokenizer st=new StringTokenizer(hex2string(encryptText)," ");
			int num=0;
			byte[] salt=new byte[8];
			while(st.hasMoreTokens()&&num<8){
				salt[num]=(byte)(Integer.parseInt(st.nextToken()));
				num++;
			}
			int count=0;
			byte[]cbtemp=new byte[2000];
			while(st.hasMoreTokens()){
				cbtemp[count]=(byte)(Integer.parseInt(st.nextToken()));
				count++;
			}
			byte[]cb=new byte[count];
			for(int i=0;i<cb.length;i++)cb[i]=cbtemp[i];
			Cipher cp=Cipher.getInstance("PBEWithMD5AndDES");
			PBEParameterSpec ps=new PBEParameterSpec(salt,1000);
			cp.init(Cipher.DECRYPT_MODE,k,ps);
			byte[]ptext=cp.doFinal(cb);
			return new String(ptext);
		}catch(Exception e){
			e.printStackTrace();
			return "";
		}
	}
	
	
	
	
	
	
	/**
	 * <p></p>
	 * @author 周小建
	 * @created 2008-12-03
	 * @update
	 * @param String inputText要加密的内容, String algorithmName加密算法名称:md5或者sha-1,不区分大小写
	 * @return String
	 * @throws 
	 * @version v1.0
	 * @description md5或者sha-1加密
	 */
	private static String encrypt(String inputText,String algorithmName){
		if(inputText==null||"".equals(inputText.trim()))throw new IllegalArgumentException("请输入要加密的内容");
		if(algorithmName==null||"".equals(algorithmName.trim()))algorithmName="md5";
		String encryptText=null;
		try{
			MessageDigest m=MessageDigest.getInstance(algorithmName);
			m.update(inputText.getBytes("UTF8"));
			byte s[]=m.digest();
			//m.digest(inputText.getBytes("UTF8"));
			return hex(s);
		}catch(NoSuchAlgorithmException e){
			e.printStackTrace();
		}catch(UnsupportedEncodingException e){
			e.printStackTrace();
		}
		return encryptText;
	}
	
	/**
	 * <p></p>
	 * @author 周小建
	 * @created 2008-12-03
	 * @update
	 * @param String inputText
	 * @return String
	 * @throws 
	 * @version v1.0
	 * @description md5加密
	 */
	public static String md5(String inputText){
		return encrypt(inputText,"md5");
	}
	
	/**
	 * <p></p>
	 * @author 周小建
	 * @created 2008-12-03
	 * @update
	 * @param String inputText
	 * @return String
	 * @throws 
	 * @version v1.0
	 * @description md5加密
	 */
	/*
	public static String e(String inputText){
		return md5(inputText);
	}
	*/
	
	/**
	 * <p></p>
	 * @author 周小建
	 * @created 2008-12-03
	 * @update
	 * @param String inputText
	 * @return String
	 * @throws 
	 * @version v1.0
	 * @description sha加密
	 */
	public static String sha(String inputText){
		return encrypt(inputText,"sha-1");
	}

	/**
	 * <p></p>
	 * @author 周小建
	 * @created 2008-12-03
	 * @update
	 * @param String inputText
	 * @return String
	 * @throws 
	 * @version v1.0
	 * @description 二次加密,先md5再sha
	 */
	public static String md5AndSha(String inputText){
		return sha(md5(inputText));
	}

	

	
	
	
	
	
	
	
	
	
	/**
	 * 初始化 AES Cipher
	 * @param sKey 公钥
	 * @param cipherMode 密码模式 加密or解密
	 * **/
	public static Cipher initAESCipher(String sKey, int cipherMode) {
		//创建Key gen
		KeyGenerator keyGenerator = null;
		Cipher cipher = null;
		try{
			String VIPARA = "0102030405060708";
			IvParameterSpec zeroIv = new IvParameterSpec(VIPARA.getBytes());
			keyGenerator = KeyGenerator.getInstance("AES");// 1.构造密钥生成器,指定为AES算法,不区分大小写
			SecretKeySpec key = new SecretKeySpec(sKey.getBytes(), "AES");
			cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");//6.根据指定算法AES自成密码器		AES/CBC/PKCS5Padding
			cipher.init(cipherMode, key, zeroIv);// 7.初始化密码器,第一个参数为加密(Encrypt_mode)或者解密解密(Decrypt_mode)操作,第二个参数为使用的KEY
		}catch(Exception e){
			e.printStackTrace();
		}
		return cipher;
	}
	
	public static File aesFile(String key, String sourceFilePath,String destFilePath,boolean override,boolean flag){
		//System.out.printf(sourceFilePath);
		FileInputStream in = null;
		FileOutputStream out = null;
		File destFile = null;
		File sourceFile = null;
		try {
			sourceFile = new File(sourceFilePath);
			if(StringUtils.isBlank(destFilePath)){
				int p=sourceFilePath.lastIndexOf(".");
				destFilePath=sourceFilePath.substring(0,p)+"-EN"+sourceFilePath.substring(p);
			}
			destFile = new File(destFilePath);
			if (sourceFile.exists() && sourceFile.isFile()) {
				if (!destFile.getParentFile().exists())destFile.getParentFile().mkdirs();
				destFile.createNewFile();
				in = new FileInputStream(sourceFile);
				out = new FileOutputStream(destFile);
				Cipher cipher = initAESCipher(key, flag?Cipher.ENCRYPT_MODE:Cipher.DECRYPT_MODE);
				byte[] byteArray = new byte[1024];
				char[]charArray=new char[1024];
				int r = 0;
				
				if(flag){
					//以加密流写入文件
					CipherInputStream cipherInputStream = new CipherInputStream(in,cipher);
					//BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out,"UTF-8"));
					while ((r = cipherInputStream.read(byteArray)) != -1) {
						out.write(byteArray, 0, r);
						out.flush();
						//bw.write(charArray, 0, r);
						//bw.flush();
					}
					cipherInputStream.close();
				}else {
					CipherOutputStream cipherOutputStream = new CipherOutputStream(out, cipher);
					while ((r = in.read(byteArray)) >= 0) {
						cipherOutputStream.write(byteArray, 0, r);
					}
					cipherOutputStream.close();
				}
				
				if(in!=null)in.close();
				if(out!=null)out.close();
				
				if(override) {
					sourceFile.delete();//删除原来
					FileUtils.renameFile(destFile,sourceFilePath,false);//新的重命名为原来
				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace(); // To change body of catch statement use File |
			// Settings | File Templates.
		} catch (IOException e) {
			e.printStackTrace(); // To change body of catch statement use File |
			// Settings | File Templates.
		} finally {
			try {
				if(out!=null)out.close();
			} catch (IOException e) {
				e.printStackTrace(); // To change body of catch statement use
				// File | Settings | File Templates.
			}
			try {
				if(in!=null)in.close();
			} catch (IOException e) {
				e.printStackTrace(); // To change body of catch statement use
				// File | Settings | File Templates.
			}
		}
		return destFile;
	}
	
	/**
	 * 加密文件
	 * */
	public static File aesEnFile(String key, String sourceFilePath,String destFilePath,boolean override){
		return aesFile(key, sourceFilePath,destFilePath,override,true);
	}

	/**
	 * 解密文件
	 * */
	public static File aesDeFile(String key, String sourceFilePath,String destFilePath,boolean override) {
		return aesFile(key, sourceFilePath,destFilePath,override,false);
	}
	
	public static File aesDeFile(File file) {
		String key = getRandomKey();
		String destFilePath = file.getAbsolutePath() + "-" + key;
		return aesEnFile(key, file.getAbsolutePath(), destFilePath,false);
	}

	/**
	 * 文件加密
	 * @param fileRuller
	 * @param filePath
	 * @param encryType
	 * @return
	 */
	public static File fileEncrypt(String fileRuller,String filePath,String encryType){
		File file=null;
		if(StringUtils.isNotBlank(encryType)){
			switch(encryType.toUpperCase()) {
				case "AES":
					file = Encrypt.aesEnFile(fileRuller,filePath,null,true);//加密
					break;
				case "DES":
					String str = FileUtils.readFromFile(filePath);//获取数据
					str = Encrypt.encrypt(str);//数据加密
					String destFilePath=filePath.substring(0,filePath.lastIndexOf("."))
							+"-EN"+filePath.substring(filePath.lastIndexOf("."));//获取新文件名
					FileUtils.writeFile(str,destFilePath,"UTF-8");//数据加密后存入新文件中
					FileUtils.renameFile(new File(destFilePath),filePath,true);//新文件重命名为原文件
					break;
				case "SHA1":
					
					break;
				case "":
					break;
				default:
					break;
			}
		}
		return file;
	}
	
	/**
	 * 文件解密
	 * @param fileRuller
	 * @param filePath
	 * @param encryType
	 * @return
	 */
	public static File fileDecrypt(String fileRuller,String filePath,String encryType){
		File file=null;
		String destFilePath="";
		if(StringUtils.isNotBlank(encryType)){
			switch(encryType.toUpperCase()) {
				case "AES":
					//File file = AesUtils.encryptFile(fileRuller,filePath,filePathM);
					int p=filePath.lastIndexOf(".");
					destFilePath=filePath.substring(0,p)+"-DE"+filePath.substring(p);
					//destFilePath=filePath.replaceFirst("-EN\\.","-DE.");
					file = Encrypt.aesDeFile(fileRuller,filePath,destFilePath,false);//解密
					//file = Encrypt.aesDeFile(fileRuller,filePath,filePath.replaceFirst("-EN\\.","."),false);//解密
					break;
				case "DES":
					String str = FileUtils.readFromFile(filePath);//获取数据
					str = Encrypt.decrypt(str);//数据加密
					destFilePath=filePath.substring(0,filePath.lastIndexOf("."))
							+"-DE"+filePath.substring(filePath.lastIndexOf("."));//获取新文件名
					FileUtils.writeFile(str,destFilePath,"UTF-8");//数据加密后存入新文件中
					FileUtils.renameFile(new File(destFilePath),filePath,true);//新文件重命名为原文件
					break;
				case "SHA1":
					
					break;
				case "":
					break;
				default:
					break;
			}
		}
		return file;
	}
	
	public static void main(String[] args){
		//0
		try{
			/*
			//String a = "9660105586945244";
			String a = AesUtils.getRandomKey();
			System.out.println(a);
			//String a = "3744897966898045";
			//File fnew = AesUtils.encryptFile(a, "e:\\aaa.txt", "e:\\aaaa.txt");
			//AesUtils.decryptFile(a, "E:\\testfile\\0532110004\\10\\9660105586945244-数据库迁移步骤文档.txt", "e:\\aaaa1.txt");
			File fnew = AesUtils.encryptFile(a, "d:\\123.txt", "d:\\123.txt");
			//AesUtils.decryptFile(a, "d:\\1231.txt", "d:\\aaaa1.txt");
			*/
			
			
			
			
			//Encrypt en=(Encrypt)Encrypt.getInstance();

			/*
			String userid="password";//要加密的用户工号
			String e_userid=en.encrypt(userid);//用户工号加密后的值
			String eAES_userid=en.enCodeAES(userid);
			System.out.println("encrypt-->" + e_userid);
			System.out.println("enCodeAES-->" + eAES_userid);
			System.out.println(en.decrypt(e_userid).equals(userid));//对加密的用户工号进行解密
			System.out.println(en.deCodeAES(eAES_userid).equals(userid));//对加密的用户工号进行解密
			*/

			/*
			//System.out.println(en.deCodeAES("password"));
			String str="root";
			System.out.println("encrypt加密后为:" + en.encrypt(str));
			System.out.println("decrypt解密后为:" + en.decrypt(en.encrypt(str)));
			System.out.println("enCodeAES加密后为:" + en.enCodeAES(str));
			System.out.println("deCodeAES解密后为:" + en.deCodeAES(en.enCodeAES(str)));
			System.out.println("deCodeAES解密后为:" + en.deCodeAES("294ff8020298a1bede18cd2af6d5045f"));//holytax
			*/

			//System.out.println(en.encrypt("wftax"));//
			//System.out.println(en.enCodeAES("wftax"));
			//System.out.println(en.enCodeAES("riskManage"));//
			//System.out.println(en.deCodeAES("c2e23587c75a622b91bd456e0ccca2c3"));//riskManage
			
			//System.out.println(en.enCodeAES("fahon"));
			//System.out.println(en.enCodeAES("123456"));
			//System.out.println(en.enCodeAES("root"));
			
			
			String str="fahon";
			System.out.println("encrypt加密后为:" + encrypt(str));
			System.out.println("decrypt解密后为:" + decrypt(encrypt(str)));
			
			/*
			FileUtils.renameFile("d://111.xlsx","D://222.xlsx",true);//新的重命名为原来
			aesFile("3744897966898045","C:\\fahonEAP\\doc\\excelExp\\fahon-eap_20200715150446-EN.xlsx","C:\\fahonEAP\\doc\\excelExp\\11.xlsx",false,false);
			System.out.println(11);
			*/
			
			String s = "aaaaa-EN.txt";
			s=s.replaceFirst("-EN\\.",".");
			System.out.println(s);
		}catch(Exception e){
			e.printStackTrace();
		}

		//1
		/*
		System.out.println(md5("123456"));
		System.out.println(sha("123456"));
		*/
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值