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; } }
相关文章推荐
- Sed简介
- powerdesigner逆向工程,从数据库导出PDM
- 使用 PHP 7 给 Web 应用加速
- Zeal与velocity: Windows与Linux下与Mac中Dash类似的API离线查询工具
- Android Https请求详细demo
- iOS应用程序内购/内付费(一)
- 解析 dex 文件结构 - DexHeader
- 欢迎使用CSDN-markdown编辑器
- 如何在android中用代码修改unity模型界面
- mysql常用数学函数
- 虚拟化和云计算
- [Criteria]not in子查询,查询不在中间表的数据
- Android开发-将Android studio的Gradle升级到最新版本
- UITableViewDelete 删除
- windows下安装redis
- 笑点变低可能是痴呆先兆
- js的eval函数
- Hibernate——自动建表
- matlab 复制图片到另一个文件夹 并且重命名
- 动态加载Animator和AnimatorController