您的位置:首页 > 其它

AES加密解密简单实例

2015-11-18 11:03 387 查看
package cn.com.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

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.spec.SecretKeySpec;

/**
* 加密压缩文件,解密压缩文件工具类
* @author max
*
*/
public class AESlockUtil {
/**
* 文件读取缓冲区大小
*/
private static final int CACHE_SIZE = 1024;

public static void main(String[] args) throws Exception {
jiami();
jiemi();

}
/**
* 加密
* @param content 需要加密的内容
* @param password  加密密码
* @return
*/
public static byte[] encrypt(byte[] content, String password) {
try {
//long startTime=System.currentTimeMillis();
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom(password.getBytes()));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");// 创建密码器
cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
byte[] result = cipher.doFinal(content);
//long endTime=System.currentTimeMillis();
//System.out.println("加密时间: "+(endTime-startTime)+"ms");
return result;
} 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();
}
return null;
}

/**解密
* @param content  待解密内容
* @param password 解密密钥
* @return
*/
public static byte[] decrypt(byte[] content, String password) {
try {
//long startTime=System.currentTimeMillis();
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom(password.getBytes()));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");// 创建密码器
cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
byte[] result = cipher.doFinal(content);
//long endTime=System.currentTimeMillis();
// System.out.println("解密时间: "+(endTime-startTime)+"ms");
return result;
} 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();
}
return null;
}

/**
* 加密测试方法
* 加密后的文件放在源文件同一目录下
*/
public static void jiami() throws Exception{
//压缩包文件转byte
byte[] zipByte = fileToByte("D:/aaa/4028cb2450fa422a0150ff63da6b004f.rar");
//加密
String password = "123qwe!@#";//加密密码
//加密后的byte数组
byte[] encryptResult = encrypt(zipByte, password);
//如果加密成功形成了加密后的数组,就删除原有的压缩文件
if(encryptResult.length!=0){
//压缩包文件路径
File folder = new File("D:/aaa");
File[] files =folder.listFiles();
//遍历整个文件夹
for(File file:files){
//如果是加密之前的文件就删除
if(file.getName().equals("4028cb2450fa422a0150ff63da6b004f.rar")){
file.delete();
}
}
}
//读取加密后的文件
ByteArrayInputStream arrin =new ByteArrayInputStream(encryptResult);
//文件输出流
FileOutputStream out = new FileOutputStream("D:/aaa/4028cb2450fa422a0150ff63da6b004f.rar");
byte[] bytes = new byte[1024];
int len = 0;
while((len=arrin.read(bytes))!=-1){
//写入加密后的内容
out.write(bytes,0,len);
}
out.close();
arrin.close();
}
/**
* 解密测试方法
* 解密后的文件存放在解密前统一路径下
*/
public static void jiemi() throws Exception{
//文件转byte数组
byte[] content = fileToByte("D:/aaa/4028cb2450fa422a0150ff63da6b004f.rar");
//解密密码
String password = "123qwe!@#";
//解密后的byte数组
byte[] decryptResult = decrypt(content,password);
//如果解密成功形成了解密后的数组,就删除原有的压缩文件
if(decryptResult.length!=0){
//压缩包文件路径
File folder = new File("D:/aaa");
File[] files =folder.listFiles();
//遍历整个文件夹
for(File file:files){
//如果是解密之前的文件就删除
if(file.getName().equals("4028cb2450fa422a0150ff63da6b004f.rar")){
file.delete();
}
}
}
//读取解密后的文件
ByteArrayInputStream arrin =new ByteArrayInputStream(decryptResult);
//输出文件流
FileOutputStream output = new FileOutputStream("D:/aaa/4028cb2450fa422a0150ff63da6b004f.rar");
byte[] bytes = new byte[1024];
int len = 0;
while((len=arrin.read(bytes))!=-1){
//写入解密后的文件内容
output.write(bytes,0,len);
}
output.close();
arrin.close();
}
/**
* 文件转换为二进制数组
* @param filePath
* @return
* @throws Exception
*/
public static byte[] fileToByte(String filePath) throws Exception {
byte[] data = new byte[0];
File file = new File(filePath);
if (file.exists()) {
FileInputStream in = new FileInputStream(file);
ByteArrayOutputStream out = new ByteArrayOutputStream(2048);
byte[] cache = new byte[CACHE_SIZE];
int nRead = 0;
while ((nRead = in.read(cache)) != -1) {
out.write(cache, 0, nRead);
out.flush();
}
out.close();
in.close();
data = out.toByteArray();
}
return data;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: