JAVA AES字符串解密算法可读取文件,也可以保存解密后的文件
package jm;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
public class EncryptUti
{//将File转换成Byte
public static byte[] getBytesFromFile(File f)
{
if (f == null)
{
return null;
}
try
{
FileInputStream stream = new FileInputStream(f);
ByteArrayOutputStream out = new ByteArrayOutputStream(5*1024*1024);
byte[] b = new byte[1000];
int n;
while ((n = stream.read(b)) != -1)
out.write(b, 0, n);
stream.close();
out.close();
return out.toByteArray();
}
catch (IOException e)
{ e.printStackTrace();
}
return null;
}
//AES解密
public static byte[] aesDecrypt(byte[] datas, String key) throws Exception
{
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes("utf-8"), "AES"));
byte[] bytes = cipher.doFinal(datas);
return bytes;
}
//将Byte转换成File
public static File getFileFromBytes(byte[] b, String outputFile)
{
BufferedOutputStream stream = null;
File file = null;
try
{
file = new File(outputFile);
FileOutputStream fstream = new FileOutputStream(file);
stream = new BufferedOutputStream(fstream);
stream.write(b);
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (stream != null)
{
try
{
stream.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
}
return file;
}
public static void main(String[] args) throws Exception
{
long lStart = System.currentTimeMillis();
File f=new File("D:\\加密的文件.gz");
byte[] datas1=EncryptUti.getBytesFromFile(f);
byte[] output=EncryptUti.aesDecrypt(datas1, "geoway12geoway12");
String outputFile="D:\\解密的文件1.gz";
EncryptUti.getFileFromBytes(output, outputFile);
long lUseTime1 = System.currentTimeMillis() - lStart;
System.out.println("AES解密耗时:" + lUseTime1/1000.00 + "秒");
}
}