```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;
public class Encrypt{
private static final String password="e_f_codd";
private static final String encoding="GBK";
private static final String[]hexDigits={"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"};
private static final byte[]keyByte={0x11,0x22,0x4F,0x58,(byte)0x88,0x10,0x40,0x38,0x28,0x25,0x79,0x51,(byte)0xCB,(byte)0xDD,0x55,0x66};
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];
}
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();
}
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;
}
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;
}
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;
}
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();
}
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);
}
public static String enCodeAES(String text){
try{
byte[]OriByte=text.getBytes(encoding);
SecretKey key=new SecretKeySpec(keyByte,"AES");
Cipher cipher=Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE,key);
byte[]OriCipherText=cipher.doFinal(OriByte);
String b=byteArrayToHexString(OriCipherText);
return b;
}catch(Exception e){
e.printStackTrace();
return "";
}
}
public static String deCodeAES(String encryptText){
try{
SecretKey key=new SecretKeySpec(keyByte,"AES");
Cipher cipher=Cipher.getInstance("AES/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 "";
}
}
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 "";
}
}
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 "";
}
}
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();
return hex(s);
}catch(NoSuchAlgorithmException e){
e.printStackTrace();
}catch(UnsupportedEncodingException e){
e.printStackTrace();
}
return encryptText;
}
public static String md5(String inputText){
return encrypt(inputText,"md5");
}
public static String sha(String inputText){
return encrypt(inputText,"sha-1");
}
public static String md5AndSha(String inputText){
return sha(md5(inputText));
}
public static Cipher initAESCipher(String sKey, int cipherMode) {
KeyGenerator keyGenerator = null;
Cipher cipher = null;
try{
String VIPARA = "0102030405060708";
IvParameterSpec zeroIv = new IvParameterSpec(VIPARA.getBytes());
keyGenerator = KeyGenerator.getInstance("AES");
SecretKeySpec key = new SecretKeySpec(sKey.getBytes(), "AES");
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(cipherMode, key, zeroIv);
}catch(Exception e){
e.printStackTrace();
}
return cipher;
}
public static File aesFile(String key, String sourceFilePath,String destFilePath,boolean override,boolean flag){
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);
while ((r = cipherInputStream.read(byteArray)) != -1) {
out.write(byteArray, 0, r);
out.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();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(out!=null)out.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(in!=null)in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
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);
}
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;
}
public static File fileDecrypt(String fileRuller,String filePath,String encryType){
File file=null;
String destFilePath="";
if(StringUtils.isNotBlank(encryType)){
switch(encryType.toUpperCase()) {
case "AES":
int p=filePath.lastIndexOf(".");
destFilePath=filePath.substring(0,p)+"-DE"+filePath.substring(p);
file = Encrypt.aesDeFile(fileRuller,filePath,destFilePath,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){
try{
String str="fahon";
System.out.println("encrypt加密后为:" + encrypt(str));
System.out.println("decrypt解密后为:" + decrypt(encrypt(str)));
String s = "aaaaa-EN.txt";
s=s.replaceFirst("-EN\\.",".");
System.out.println(s);
}catch(Exception e){
e.printStackTrace();
}
}
}