前言

最近公司需要对本公司的一些下载文件进行加密解密需求,也就尝试去实现下,其实需要借助第三方的jar包:bcprov-jdk15on-155.jar,下载这个可以到网上搜或者下载本人的demo即可,注意:需要加密和解密的key是一致的才可以解密,不然就会解密失败。不多说,直接上代码。
效果图
代码:
实现加密解密逻辑代码
package com.vsoontech.p2p.sample;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.InvalidKeyException;
import java.security.Key;
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.ShortBufferException;
/**
* @author zhou
* @since 2016/9/26
*/
public enum AES {
INSTANCE;
private Key key;
/**
* 生成AES对称秘钥
*/
public String generateKey() throws NoSuchAlgorithmException {
KeyGenerator keygen = KeyGenerator.getInstance("AES");
SecureRandom random = new SecureRandom();
keygen.init(random);
this.key = keygen.generateKey();
return "Algorithm Format Encoded:" + key.getAlgorithm() + " - " + key.getFormat() + " - " + new String(key.getEncoded());
}
/**
* 加密
*/
public void encrypt(InputStream in) throws InvalidKeyException, ShortBufferException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, IOException {
this.crypt(in, null, Cipher.ENCRYPT_MODE);
}
/**
* 解密
*/
public String decrypt(InputStream in) throws InvalidKeyException, ShortBufferException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, IOException {
return this.crypt(in, Cipher.DECRYPT_MODE);
}
/**
* 加密
*/
public void encrypt(InputStream in, OutputStream out) throws InvalidKeyException, ShortBufferException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, IOException {
this.crypt(in, out, Cipher.ENCRYPT_MODE);
}
/**
* 解密
*/
public void decrypt(InputStream in, OutputStream out) throws InvalidKeyException, ShortBufferException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, IOException {
this.crypt(in, out, Cipher.DECRYPT_MODE);
}
/**
* 实际的加密解密过程
*/
public void crypt(InputStream in, OutputStream out, int mode) throws IOException, ShortBufferException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(mode, this.key);
int blockSize = cipher.getBlockSize();
int outputSize = cipher.getOutputSize(blockSize);
byte[] inBytes = new byte[blockSize];
byte[] outBytes = new byte[outputSize];
int inLength = 0;
boolean more = true;
while (more) {
inLength = in.read(inBytes);
if (inLength == blockSize) { //只要输入数据块具有全长度(长度可被8整除),调用update方法
int outLength = cipher.update(inBytes, 0, blockSize, outBytes);
if (out != null) out.write(outBytes, 0, outLength);
} else {
more = false;
}
}
if (inLength > 0) //不具有全长度,调用doFinal方法
outBytes = cipher.doFinal(inBytes, 0, inLength);
else
outBytes = cipher.doFinal();
if (out != null) {
out.write(outBytes);
out.flush();
}
}
/**
* 实际的加密解密过程
*/
public String crypt(InputStream in, int mode) throws IOException, ShortBufferException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(mode, this.key);
int blockSize = cipher.getBlockSize();
int outputSize = cipher.getOutputSize(blockSize);
byte[] inBytes = new byte[blockSize];
byte[] outBytes = new byte[outputSize];
int inLength = 0;
boolean more = true;
StringBuilder sb = new StringBuilder();
while (more) {
inLength = in.read(inBytes);
if (inLength == blockSize) { //只要输入数据块具有全长度(长度可被8整除),调用update方法
int outLength = cipher.update(inBytes, 0, blockSize, outBytes);
} else {
more = false;
}
}
if (inLength > 0) //不具有全长度,调用doFinal方法
outBytes = cipher.doFinal(inBytes, 0, inLength);
else
outBytes = cipher.doFinal();
sb.append(new String(outBytes));
return sb.toString();
}
public void setKey(Key key) {
this.key = key;
}
public Key getKey() {
return key;
}
}
生成秘钥代码
package com.vsoontech.p2p.sample;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
/**
* @author zhou
* @since 2016/9/26
*/
public class AESKeyModel {
public static final String KEY_ALGORITHM = "AES";
private static final String DEFAULT_CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
private String srcFile = "", destionFile = "";
/**
* 初始化密钥
*
* @return byte[] 密钥
* @throws Exception
*/
public byte[] initSecretKey() {
//返回生成指定算法的秘密密钥的 KeyGenerator 对象
KeyGenerator kg = null;
try {
kg = KeyGenerator.getInstance(KEY_ALGORITHM);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return new byte[0];
}
//初始化此密钥生成器,使其具有确定的密钥大小
//AES 要求密钥长度为 128
kg.init(128);
//生成一个密钥
SecretKey secretKey = kg.generateKey();
return secretKey.getEncoded();
}
public void setDestionFile(String destionFile) {
this.destionFile = destionFile;
}
public void setSrcFile(String srcFile) {
this.srcFile = srcFile;
}
/**
* 转换密钥
*
* @param key 二进制密钥
* @return 密钥
*/
private static Key toKey(byte[] key) {
//生成密钥
return new SecretKeySpec(key, KEY_ALGORITHM);
}
/**
* 加密
*
* @param data 待加密数据
* @param key 密钥
* @return byte[] 加密数据
* @throws Exception
*/
public static byte[] encrypt(byte[] data, Key key) throws Exception {
return encrypt(data, key, DEFAULT_CIPHER_ALGORITHM);
}
/**
* 加密
*
* @param data 待加密数据
* @param key 二进制密钥
* @return byte[] 加密数据
* @throws Exception
*/
public static byte[] encrypt(byte[] data, byte[] key) throws Exception {
return encrypt(data, key, DEFAULT_CIPHER_ALGORITHM);
}
/**
* 加密
*
* @param data 待加密数据
* @param key 二进制密钥
* @param cipherAlgorithm 加密算法/工作模式/填充方式
* @return byte[] 加密数据
* @throws Exception
*/
public static byte[] encrypt(byte[] data, byte[] key, String cipherAlgorithm) throws Exception {
//还原密钥
Key k = toKey(key);
return encrypt(data, k, cipherAlgorithm);
}
/**
* 加密
*
* @param data 待加密数据
* @param key 密钥
* @param cipherAlgorithm 加密算法/工作模式/填充方式
* @return byte[] 加密数据
* @throws Exception
*/
public static byte[] encrypt(byte[] data, Key key, String cipherAlgorithm) throws Exception {
//实例化
Cipher cipher = Cipher.getInstance(cipherAlgorithm);
//使用密钥初始化,设置为加密模式
cipher.init(Cipher.ENCRYPT_MODE, key);
//执行操作
return cipher.doFinal(data);
}
/**
* 解密
*
* @param data 待解密数据
* @param key 二进制密钥
* @return byte[] 解密数据
* @throws Exception
*/
public static byte[] decrypt(byte[] data, byte[] key) throws Exception {
return decrypt(data, key, DEFAULT_CIPHER_ALGORITHM);
}
/**
* 解密
*
* @param data 待解密数据
* @param key 密钥
* @return byte[] 解密数据
* @throws Exception
*/
public static byte[] decrypt(byte[] data, Key key) throws Exception {
return decrypt(data, key, DEFAULT_CIPHER_ALGORITHM);
}
/**
* 解密
*
* @param data 待解密数据
* @param key 二进制密钥
* @param cipherAlgorithm 加密算法/工作模式/填充方式
* @return byte[] 解密数据
* @throws Exception
*/
public static byte[] decrypt(byte[] data, byte[] key, String cipherAlgorithm) throws Exception {
//还原密钥
Key k = toKey(key);
return decrypt(data, k, cipherAlgorithm);
}
/**
* 解密
*
* @param data 待解密数据
* @param key 密钥
* @param cipherAlgorithm 加密算法/工作模式/填充方式
* @return byte[] 解密数据
* @throws Exception
*/
public static byte[] decrypt(byte[] data, Key key, String cipherAlgorithm) throws Exception {
//实例化
Cipher cipher = Cipher.getInstance(cipherAlgorithm);
//使用密钥初始化,设置为解密模式
cipher.init(Cipher.DECRYPT_MODE, key);
//执行操作
return cipher.doFinal(data);
}
public void encryptionFile(Key sessionKey) throws Exception {
int len = 0;
byte[] buffer = new byte[1024];
byte[] cipherbuffer = null;
// 使用会话密钥对文件加密。
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM, new BouncyCastleProvider());
IvParameterSpec iv = new IvParameterSpec("0000000000123456".getBytes());
cipher.init(Cipher.ENCRYPT_MODE, sessionKey, iv);
FileInputStream fis = new FileInputStream(new File(srcFile));
FileOutputStream fos = new FileOutputStream(new File(destionFile));
// 读取原文,加密并写密文到输出文件。
while ((len = fis.read(buffer)) != -1) {
cipherbuffer = cipher.update(buffer, 0, len);
fos.write(cipherbuffer);
fos.flush();
}
cipherbuffer = cipher.doFinal();
fos.write(cipherbuffer);
fos.flush();
if (fis != null)
fis.close();
if (fos != null)
fos.close();
}
public void descryptionFile(Key sessionKey) throws Exception {
int len = 0;
byte[] buffer = new byte[5 * 1024];
byte[] plainbuffer = null;
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM, new BouncyCastleProvider());
IvParameterSpec iv = new IvParameterSpec("0000000000123456".getBytes());
cipher.init(Cipher.DECRYPT_MODE, sessionKey, iv);
FileInputStream fis = new FileInputStream(new File(srcFile));
FileOutputStream fos = new FileOutputStream(new File(destionFile));
while ((len = fis.read(buffer)) != -1) {
plainbuffer = cipher.update(buffer, 0, len);
fos.write(plainbuffer);
fos.flush();
}
plainbuffer = cipher.doFinal();
fos.write(plainbuffer);
fos.flush();
if (fis != null)
fis.close();
if (fos != null)
fos.close();
}
}
加密逻辑示例代码
/**
* 加密
*
* @param path
* @param destionFile
*/
private void aes(String path, String destionFile) {
try {
Log.d(TAG, "aes Key: " + AES.INSTANCE.generateKey());
FileInputStream fis = new FileInputStream(new File(path));
FileOutputStream fos = new FileOutputStream(new File(destionFile));
AES.INSTANCE.encrypt(fis, fos);
} catch (Exception e) {
Log.d(TAG, "Exception: " + e.toString());
e.printStackTrace();
}
}
解密逻辑示例代码:
/**
* AES解密文件
*
* @param path 需要解密的文件目录
*/
private void aesJieMi(String path) {
File f = new File(path);
if (!f.exists() || f.isDirectory())
Toast.makeText(getApplicationContext(), "该文件不合法!", Toast.LENGTH_SHORT).show();
else {
String prefix = f.getName().substring(0, f.getName().indexOf('.'));
String suffix = f.getName().substring(f.getName().indexOf('.'));
String outjiemiFile = Environment.getExternalStorageDirectory() + File.separator + prefix + "AES_jieMi" + suffix;
AESKeyModel model_aes = new AESKeyModel();
model_aes.setSrcFile(path);
model_aes.setDestionFile(outjiemiFile);
try {
// model_aes.descryptionFile(key_AES);
model_aes.descryptionFile(key_aes);
// TODO: 加密后的文件
RandomAccessFile raf = new RandomAccessFile(path, "rw");
Log.d(TAG, "解密后 file length: " + raf.length());
Log.d(TAG, "解密后 file content: " + raf.readLine());
} catch (Exception e) {
e.printStackTrace();
}
}
}
总结:
注意秘钥需要一致。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
# android
# aes加密解密
# 文件加密解密
# aes文件加密
# Android加密之全盘加密详解
# Android常用的数据加密方式代码详解
# Android数据传输中的参数加密代码示例
# 详解Android端与JavaWeb传输加密(DES+RSA)
# Android使用RSA加密和解密的示例代码
# Android 客户端RSA加密的实现方法
# android实现视频的加密和解密(使用AES)
# Android md5加密与php md5加密一致详解
# 详解Android安全防护之加密算法
# 加密解密
# 设置为
# 只要输入
# 就会
# 也就
# 才可以
# 使其
# 多说
# 第三方
# 该文件
# 大家多多
# 不合法
# 文件加密
# 长度为
# 网上
# getAlgorithm
# private
# getFormat
# Encoded
# void
相关文章:
制作网站的模板软件,网站怎么建设?
企业网站制作费用多少,企业网站空间一般需要多大,费用是多少?
如何在Golang中使用replace替换模块_指定本地或远程路径
整蛊网站制作软件,手机不停的收到各种网站的验证码短信,是手机病毒还是人为恶搞?有这种手机病毒吗?
网站制作和推广的区别,想自己建立一个网站做推广,有什么快捷方法马上做好一个网站?
广东专业制作网站有哪些,广东省能源集团有限公司官网?
电商网站制作多少钱一个,电子商务公司的网站制作费用计入什么科目?
如何注册花生壳免费域名并搭建个人网站?
建站之星伪静态规则如何正确配置?
如何选择高效响应式自助建站源码系统?
商务网站制作工程师,从哪几个方面把握电子商务网站主页和页面的特色设计?
网站建设制作需要多少钱费用,自己做一个网站要多少钱,模板一般多少钱?
网站海报制作教学视频教程,有什么免费的高清可商用图片网站,用于海报设计?
如何设置并定期更换建站之星安全管理员密码?
想学网站制作怎么学,建立一个网站要花费多少?
如何高效配置香港服务器实现快速建站?
标准网站视频模板制作软件,现在有哪个网站的视频编辑素材最齐全的,背景音乐、音效等?
专业网站制作企业网站,如何制作一个企业网站,建设网站的基本步骤有哪些?
南宁网站建设制作定制,南宁网站建设可以定制吗?
怎么制作网站设计模板图片,有电商商品详情页面的免费模板素材网站推荐吗?
再谈Python中的字符串与字符编码(推荐)
广东企业建站网站优化与SEO营销核心策略指南
如何在搬瓦工VPS快速搭建网站?
宝塔面板如何快速创建新站点?
c# F# 的 MailboxProcessor 和 C# 的 Actor 模型
建站之星后台搭建步骤解析:模板选择与产品管理实操指南
高端网站建设与定制开发一站式解决方案 中企动力
杭州银行网站设计制作流程,杭州银行怎么开通认证方式?
IOS倒计时设置UIButton标题title的抖动问题
Avalonia如何实现跨窗口通信 Avalonia窗口间数据传递
如何通过VPS建站无需域名直接访问?
建站之星客服服务时间及联系方式如何?
网页制作模板网站推荐,网页设计海报之类的素材哪里好?
宝塔新建站点为何无法访问?如何排查?
如何自己制作一个网站链接,如何制作一个企业网站,建设网站的基本步骤有哪些?
零基础网站服务器架设实战:轻量应用与域名解析配置指南
广州美橙建站如何快速搭建多端合一网站?
盘锦网站制作公司,盘锦大洼有多少5G网站?
已有域名和空间,如何快速搭建网站?
宿州网站制作公司兴策,安徽省低保查询网站?
建站主机与虚拟主机有何区别?如何选择最优方案?
网站制作公司哪里好做,成都网站制作公司哪家做得比较好,更正规?
黑客入侵网站服务器的常见手法有哪些?
如何在阿里云购买域名并搭建网站?
制作证书网站有哪些,全国城建培训中心证书查询官网?
佛山网站制作系统,佛山企业变更地址网上办理步骤?
php能控制zigbee模块吗_php通过串口与cc2530 zigbee通信【介绍】
如何在七牛云存储上搭建网站并设置自定义域名?
如何用PHP快速搭建CMS系统?
兔展官网 在线制作,怎样制作微信请帖?
*请认真填写需求信息,我们会在24小时内与您取得联系。