java aes 解密 文件_Java AES文件加解密

转自:http://www.webtag123.com/java/4049.html

AESUtils.java

package demo.security;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.InputStream;

import java.io.OutputStream;

import java.security.Key;

import java.security.SecureRandom;

import javax.crypto.Cipher;

import javax.crypto.CipherInputStream;

import javax.crypto.CipherOutputStream;

import javax.crypto.KeyGenerator;

import javax.crypto.SecretKey;

import javax.crypto.spec.SecretKeySpec;

/**

*

* AES加密解密工具包

*

*

* @author IceWee

* @date 2012-5-18

* @version 1.0

*/

public class AESUtils {

private static final String ALGORITHM = "AES";

private static final int KEY_SIZE = 128;

private static final int CACHE_SIZE = 1024;

/**

*

* 生成随机密钥

*

*

* @return

* @throws Exception

*/

public static String getSecretKey() throws Exception {

return getSecretKey(null);

}

/**

*

* 生成密钥

*

*

* @param seed 密钥种子

* @return

* @throws Exception

*/

public static String getSecretKey(String seed) throws Exception {

KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);

SecureRandom secureRandom;

if (seed != null && !"".equals(seed)) {

secureRandom = new SecureRandom(seed.getBytes());

} else {

secureRandom = new SecureRandom();

}

keyGenerator.init(KEY_SIZE, secureRandom);

SecretKey secretKey = keyGenerator.generateKey();

return Base64Utils.encode(secretKey.getEncoded());

}

/**

*

* 加密

*

*

* @param data

* @param key

* @return

* @throws Exception

*/

public static byte[] encrypt(byte[] data, String key) throws Exception {

Key k = toKey(Base64Utils.decode(key));

byte[] raw = k.getEncoded();

SecretKeySpec secretKeySpec = new SecretKeySpec(raw, ALGORITHM);

Cipher cipher = Cipher.getInstance(ALGORITHM);

cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);

return cipher.doFinal(data);

}

/**

*

* 文件加密

*

*

* @param key

* @param sourceFilePath

* @param destFilePath

* @throws Exception

*/

public static void encryptFile(String key, String sourceFilePath, String destFilePath) throws Exception {

File sourceFile = new File(sourceFilePath);

File destFile = new File(destFilePath);

if (sourceFile.exists() && sourceFile.isFile()) {

if (!destFile.getParentFile().exists()) {

destFile.getParentFile().mkdirs();

}

destFile.createNewFile();

InputStream in = new FileInputStream(sourceFile);

OutputStream out = new FileOutputStream(destFile);

Key k = toKey(Base64Utils.decode(key));

byte[] raw = k.getEncoded();

SecretKeySpec secretKeySpec = new SecretKeySpec(raw, ALGORITHM);

Cipher cipher = Cipher.getInstance(ALGORITHM);

cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);

CipherInputStream cin = new CipherInputStream(in, cipher);

byte[] cache = new byte[CACHE_SIZE];

int nRead = 0;

while ((nRead = cin.read(cache)) != -1) {

out.write(cache, 0, nRead);

out.flush();

}

out.close();

cin.close();

in.close();

}

}

/**

*

* 解密

*

*

* @param data

* @param key

* @return

* @throws Exception

*/

public static byte[] decrypt(byte[] data, String key) throws Exception {

Key k = toKey(Base64Utils.decode(key));

byte[] raw = k.getEncoded();

SecretKeySpec secretKeySpec = new SecretKeySpec(raw, ALGORITHM);

Cipher cipher = Cipher.getInstance(ALGORITHM);

cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);

return cipher.doFinal(data);

}

/**

*

* 文件解密

*

*

* @param key

* @param sourceFilePath

* @param destFilePath

* @throws Exception

*/

public static void decryptFile(String key, String sourceFilePath, String destFilePath) throws Exception {

File sourceFile = new File(sourceFilePath);

File destFile = new File(destFilePath);

if (sourceFile.exists() && sourceFile.isFile()) {

if (!destFile.getParentFile().exists()) {

destFile.getParentFile().mkdirs();

}

destFile.createNewFile();

FileInputStream in = new FileInputStream(sourceFile);

FileOutputStream out = new FileOutputStream(destFile);

Key k = toKey(Base64Utils.decode(key));

byte[] raw = k.getEncoded();

SecretKeySpec secretKeySpec = new SecretKeySpec(raw, ALGORITHM);

Cipher cipher = Cipher.getInstance(ALGORITHM);

cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);

CipherOutputStream cout = new CipherOutputStream(out, cipher);

byte[] cache = new byte[CACHE_SIZE];

int nRead = 0;

while ((nRead = in.read(cache)) != -1) {

cout.write(cache, 0, nRead);

cout.flush();

}

cout.close();

out.close();

in.close();

}

}

/**

*

* 转换密钥

*

*

* @param key

* @return

* @throws Exception

*/

private static Key toKey(byte[] key) throws Exception {

SecretKey secretKey = new SecretKeySpec(key, ALGORITHM);

return secretKey;

}

}

Base64Utils.java(依赖javabase64-1.3.1.jar)

package demo.security;

import java.io.ByteArrayInputStream;

import java.io.ByteArrayOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.InputStream;

import java.io.OutputStream;

import it.sauronsoftware.base64.Base64;

/**

*

* BASE64编码解码工具包

*

*

* 依赖javabase64-1.3.1.jar

*

*

* @author IceWee

* @date 2012-5-19

* @version 1.0

*/

public class Base64Utils {

/**

* 文件读取缓冲区大小

*/

private static final int CACHE_SIZE = 1024;

/**

*

* BASE64字符串解码为二进制数据

*

*

* @param base64

* @return

* @throws Exception

*/

public static byte[] decode(String base64) throws Exception {

return Base64.decode(base64.getBytes());

}

/**

*

* 二进制数据编码为BASE64字符串

*

*

* @param bytes

* @return

* @throws Exception

*/

public static String encode(byte[] bytes) throws Exception {

return new String(Base64.encode(bytes));

}

/**

*

* 将文件编码为BASE64字符串

*

*

* 大文件慎用,可能会导致内存溢出

*

*

* @param filePath 文件绝对路径

* @return

* @throws Exception

*/

public static String encodeFile(String filePath) throws Exception {

byte[] bytes = fileToByte(filePath);

return encode(bytes);

}

/**

*

* BASE64字符串转回文件

*

*

* @param filePath 文件绝对路径

* @param base64 编码字符串

* @throws Exception

*/

public static void decodeToFile(String filePath, String base64) throws Exception {

byte[] bytes = decode(base64);

byteArrayToFile(bytes, filePath);

}

/**

*

* 文件转换为二进制数组

*

*

* @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;

}

/**

*

* 二进制数据写文件

*

*

* @param bytes 二进制数据

* @param filePath 文件生成目录

*/

public static void byteArrayToFile(byte[] bytes, String filePath) throws Exception {

InputStream in = new ByteArrayInputStream(bytes);

File destFile = new File(filePath);

if (!destFile.getParentFile().exists()) {

destFile.getParentFile().mkdirs();

}

destFile.createNewFile();

OutputStream out = new FileOutputStream(destFile);

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();

}

}

AESTester.java

package demo.security;

public class AESTester {

static String key;

static {

try {

key = AESUtils.getSecretKey();

} catch (Exception e) {

e.printStackTrace();

}

}

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

long begin = System.currentTimeMillis();

encryptFile();

decryptFile();

test();

long end = System.currentTimeMillis();

System.err.println("耗时:" + (end-begin)/1000 + "秒");

}

static void encryptFile() throws Exception {

String sourceFilePath = "D:/demo.mp4";

String destFilePath = "D:/demo_encrypted.mp4";

AESUtils.encryptFile(key, sourceFilePath, destFilePath);

}

static void decryptFile() throws Exception {

String sourceFilePath = "D:/demo_encrypted.mp4";

String destFilePath = "D:/demo_decrypted.mp4";

AESUtils.decryptFile(key, sourceFilePath, destFilePath);

}

static void test() throws Exception {

String source = "这是一行测试DES加密/解密的文字,你看完也等于没看,是不是啊?!";

System.err.println("原文:\t" + source);

byte[] inputData = source.getBytes();

inputData = AESUtils.encrypt(inputData, key);

System.err.println("加密后:\t" + Base64Utils.encode(inputData));

byte[] outputData = AESUtils.decrypt(inputData, key);

String outputStr = new String(outputData);

System.err.println("解密后:\t" + outputStr);

}

}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/332774.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

JavaScript(JS)的习惯写法总结

//取整 parseInt(a,10); //Before Math.floor(a); //Before a>>0; //Before ~~a; //After a|0; //After//四舍五入 Math.round(a); //Before a.5|0; //After//内置值 undefined; //Before void 0; //After, 快 0[0]; //After, 略慢//内置值 Infinity; 1/0;//布尔值短写法…

java模拟连接超时_Java:使用Toxiproxy模拟各种连接问题

java模拟连接超时用Toxiproxy和Java的HttpURLConnection模拟各种连接问题,以查看产生了什么样的错误:连接超时vs.读取超时vs.连接被拒绝…。 结果: 系统:openjdk 11.0.1 2018-10-16 (.setConnectTimeout 1) > java.net.Socke…

java中的僵死进程_Java中线程间怎么通讯?什么叫僵死线程?

《尸家保镖》 《猛鬼出千》 《不死心灵》 《大家发财》 《灵幻少女》 《九天玄女》 《僵尸至尊》 《湘西尸王》 《尸前想后》 《魔高一丈》 《一世好命》 《妖兽尸王》 《人蝎大战》 《星际钝胎》 《艳女还魂》 《邪完再邪》 《艳鬼山坟》 《尸破今天阳光很好,坐在窗…

正则表达式中的分组的匹配次数的理解

正则表达式:/((\d){1,6})/ 这个正则表达式可以匹配任意数量的数字。 限定符 指的是前面的子表达式 (\d){1,6} 可以出现 1 次或者多次,所以如果是贪婪匹配,每次迭代匹配的数字个数可以超过 6 个(即 ≥1);如…

aws使用技巧_AWS:避免那些“神圣的法案”时刻的一些技巧

aws使用技巧云非常棒:几乎100%的可用性,接近零的维护,按需付费,最重要的是,它具有无限的可扩展性。 但是最后两个很容易把你咬回去,把那令人敬畏的事情变成一场噩梦。 偶尔您会看到类似的故事…

JAVA类和对象访问_Java类和对象

一、类类是封装对象的属性和行为的载体,在Java语言中对象的属性以成员变量的形式存在,而对象的方法以成员方法的形式存在。1. 类的构造方法构造方法是一个与类同名的方法,对象的创建就是通过构造方法完成的,构造方法分为有参构造方…

扩展方法 枚举值_扩展枚举功能的两种方法

扩展方法 枚举值前言 在上一篇文章中,我解释了如何以及为什么在Java代码中使用enums而不是switch/case控制结构。 在这里,我将展示如何扩展现有enums功能。 介绍 Java enum是一种编译器魔术。 在字节码中,任何enum都表示为扩展抽象类java.la…

正则表达式中关于字符集的问题

/[abc]/,匹配1或者多个方括号中的任意字符,方括号中的字符是“或者”的关系,等价于 /(a|b|c)/ /(abc)/,匹配1个或者多个 abc,abc 是一个整体,如下图所示: /[0-9|_|-]/,匹配由数字…

spring 构造函数注入_Spring依赖注入–字段vs设置器vs构造函数注入

spring 构造函数注入欢迎使用Spring Dependency Injection –字段,设置器,构造函数注入教程。 了解场注入 , 二传手注入和构造函数注入之间的区别。 借助代码示例,我们将看到使用每个示例的好处以及为什么选择一个而不是另一个。 …

java 快速io_Java编程在ICPC快速IO实现源码

本文将介绍Java在ICPC快速IO实现方法,下面看看具体代码。不处理EOF:import java.io.OutputStream;import java.io.IOException;import java.io.InputStream;import java.io.PrintWriter;import java.util.Arrays;import java.util.Random;import java.io…

adf开发_如何在ADF中将参数传递给ActionListener

adf开发在某些情况下,需要将值传递给ADF Button的ActionListener。 可以由actionListeners调用的方法只有一个ActionEvent类型的参数。 因此,我将解释如何将参数传递给该bean方法,但是它在方法签名中仅包含一个参数ActionEvent。 我在页面…

JavaScript/JS的学习

文章目录JavaScript 简介JavaScript 发展史ECMAScript基本语法与 HTML 结合方式数据类型类型转换非 number 转成 number非 boolean 转成 boolean特殊语法变量运算符双等号()全等号()流程控制语句switch...casewhilefor 循环对象Fu…

java soap协议头_自己调用webservice方法总结(带请求头SoapHeader)

调用webservice总结:1.加入第三方的jar包 Ksoap2-android-XXX2.访问响应的webservice的网站,查看响应的信息,得到nameSpace,methodName,url,soapAction3.如果request信息还有带有SoapHander的。那么就要封装…

注册界面演示代码(前端开发)

<!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><title>注册</title><style>* {margin: 0px;padding: 0px;/*这样的设置会阻止元素大小的改变&#xff0c;因为设置内边距时元素大小会发生改变*/b…

apache ignite_使用Apache Ignite瘦客户端– Apache Ignite内部博客

apache ignite从2.4.0版本开始&#xff0c;Apache Ignite引入了一种连接到Ignite群集的新方法&#xff0c;该方法允许与Ignite群集进行通信而无需启动Ignite客户端节点。 从历史上看&#xff0c;Apache Ignite提供了客户端和服务器节点两个概念。 点燃旨在用作轻量级模式的客户…

java 网络编程 方式_JAVA网络编程

概念BIO 阻塞io&#xff0c;1.4之前NIO no-blocking io 非阻塞io&#xff0c;jdk1.4AIO 异步io&#xff0c;jdk1.7浏览器输入网址&#xff0c;敲下回车之后发生了什么&#xff1f;1.URL解析2.DNS解析概念&#xff1a;Domain Name System&#xff0c;域名系统&#xff0c;本质…

如何设置背景图(前端开发)

<!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><title>模糊化背景图</title><style>body {background-image: url("image/bjt03.jpg");background-repeat: no-repeat;background-atta…

java字符串底层实现_「JAVA」细述合理创建字符串,分析字符串的底层存储,你不该错过...

Java基础之字符串操作——String字符串什么是字符串&#xff1f;如果直接按照字面意思来理解就是多个字符连接起来组合成的字符序列。为了更好的理解以上的理论&#xff0c;我们先来解释下字符序列&#xff0c;字符序列&#xff1a;把多个字符按照一定的顺序排列起来&#xff1…

查看oracle会话和进程_带有Oracle Digital Assistant和Fn Project的会话式UI。 第三部分,迁移到云...

查看oracle会话和进程在这篇文章中&#xff0c;我将继续在Oracle Digital Assistant和Oracle Digital Assistant之上为FlexDeploy实现对话式UI的故事。 Fn项目 。 今天&#xff0c;我将围绕聊天机器人工作的无服务器API迁移到云中&#xff0c;因此整个解决方案都在云中工作&am…