最近接到任务(文件的安全性)需要在文件上传到服务器上时将文件加密保存, 用户下载时将文件解密后返回给用户。翻了下方法最后决定用java中的Cipher类来完成(里面的实现方式挺全的)。

上手实现。pom.xml文件引入依赖包

org.bouncycastlebcprov-jdk15on1.56commons-codeccommons-codec1.10 

生成秘钥(static代码块必须否则会报错)

static {Security.addProvider(new BouncyCastleProvider());}public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException {KeyGenerator kg = KeyGenerator.getInstance("AES", BouncyCastleProvider.PROVIDER_NAME);kg.init(128, new SecureRandom());byte[] result = kg.generateKey().getEncoded();System.out.println(new String(Hex.encodeHex(result, false)));}

初始化Cipher加解密的公用方法

/**   *    * @param mode_type 加解密类型   * @param keyData key的字节数组   * @param cipher_algorith 算法/工作模式/填充模式   * @param algorith_name 算法   * @return   * @throws InvalidKeyException   * @throws NoSuchPaddingException   * @throws NoSuchAlgorithmException   * @throws NoSuchProviderException   */  public static Cipher generateCipher(int mode_type, byte[] keyData,String cipher_algorith,String algorith_name)    throws InvalidKeyException,    NoSuchPaddingException,    NoSuchAlgorithmException,    NoSuchProviderException  {    Cipher cipher = Cipher.getInstance(cipher_algorith, BouncyCastleProvider.PROVIDER_NAME);    SecretKeySpec key = new SecretKeySpec(keyData, algorith_name);    cipher.init(mode_type, key);    return cipher;  }

加密方法调用

 /**   *    * @param key  秘钥   * @param inStream 源文件流   * @param targetPath 加密后文件   * @param cipher_algorith 算法/工作模式/填充模式   * @param algorith_name 算法   * @throws InvalidKeyException   * @throws NoSuchPaddingException   * @throws NoSuchAlgorithmException   * @throws NoSuchProviderException   * @throws IOException   */  public static void encryptStream(String key, InputStream inStream, String targetPath,String cipher_algorith,String algorith_name) throws InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException, NoSuchProviderException, IOException  {    CipherInputStream cipherInputStream = null;    try    {      byte[] keyData = ByteUtils.fromHexString(key);      Cipher cipher = generateCipher(Cipher.ENCRYPT_MODE, keyData, cipher_algorith, algorith_name);      cipherInputStream = new CipherInputStream(inStream, cipher);      Util.copy(cipherInputStream, targetPath);    }    finally    {      Util.close(cipherInputStream,inStream);    }  }

解密方法调用

/**   *    * @param key 秘钥   * @param sourcePath 加密文件   * @param out 输入的文件流   * @param cipher_algorith 算法/工作模式/填充模式   * @param algorith_name 算法   * @throws InvalidKeyException   * @throws NoSuchPaddingException   * @throws NoSuchAlgorithmException   * @throws NoSuchProviderException   * @throws IOException   */  public static void decryptFile(String key,String sourcePath, OutputStream out,String cipher_algorith,String algorith_name) throws InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException, NoSuchProviderException, IOException  {    CipherOutputStream cipherOutputStream = null;    try    {      byte[] keyData = ByteUtils.fromHexString(key);      Cipher cipher = generateCipher(Cipher.DECRYPT_MODE, keyData, cipher_algorith, algorith_name);      cipherOutputStream = new CipherOutputStream(out, cipher);      Files.copy(Paths.get(sourcePath), cipherOutputStream);    }    finally    {    Util.close(cipherOutputStream, out);    }  }

写个工具类用于文件转移和关流

public class Util {/** * 文件转移 当上级目录不存在时创建 *  * @param in * @param targetPath * @throws IOException */public static void copy(InputStream in, String targetPath) throws IOException {Path target = Paths.get(targetPath);Files.createDirectories(target.getParent());Files.copy(in, target, StandardCopyOption.REPLACE_EXISTING);}/** * 关流 * @param cb */public static void close(Closeable... cb) {for (Closeable cbd : cb) {if (cbd != null) {try {cbd.close();} catch (IOException e) {e.printStackTrace();}}}}}

找到Cipher中支持的加解密算法,从bcprov-jdk15on1.56.jar包中翻出目前支持的算法有

从bcprov-jdk15on1.56.jar包中BouncyCastleProvider类截取

找几个常用的加解密方式来验收下成果

package com.more.fw.core.common.method;import java.io.FileInputStream;import java.io.FileOutputStream;import java.security.SecureRandom;import java.security.Security;import javax.crypto.KeyGenerator;import org.apache.commons.codec.binary.Hex;import org.bouncycastle.jce.provider.BouncyCastleProvider;public class Test {  public static final String ALGORITHM_NAME_3DES = "DESede";//Blowfish算法    public static final String CIPHER_ALGORITHM_3DES_ECB = "DESede/ECB/PKCS5Padding";//格式是"算法/工作模式/填充模式"    public static final String ALGORITHM_NAME_BLOWFISH = "Blowfish";//Blowfish算法    public static final String CIPHER_ALGORITHM_BLOWFISH = "Blowfish/ECB/PKCS5Padding";//格式是"算法/工作模式/填充模式"    public static final String ALGORITHM_NAME_SM4 = "SM4";//SM4算法    public static final String CIPHER_ALGORITHM_SM4 = "SM4/ECB/PKCS5Padding";//格式是"算法/工作模式/填充模式"    public static final String ALGORITHM_NAME_AES = "AES";//AES算法  public static final String CIPHER_ALGORITHM_AES = "AES/ECB/PKCS5Padding";//格式是"算法/工作模式/填充模式"    public static final String ALGORITHM_NAME_RC2 = "RC2";//RC2算法  public static final String CIPHER_ALGORITHM_RC2 = "RC2/ECB/PKCS5Padding";//格式是"算法/工作模式/填充模式"static {Security.addProvider(new BouncyCastleProvider());}public static final int DEFAULT_KEY_SIZE = 128;public static void main(String[] args) throws Exception {String key = generateKey(ALGORITHM_NAME_AES);FileInputStream in = new FileInputStream("F:logsmc_info.log.14");//源文件String targer = "D:logsmc_info.log.15";//加密后文件long star = System.currentTimeMillis();encryptStream(key,in,targer,CIPHER_ALGORITHM_AES,ALGORITHM_NAME_AES);System.out.println("AES加密時間:"+(System.currentTimeMillis()-star));FileOutputStream out = new FileOutputStream("D:logsmc_info.log.16");star = System.currentTimeMillis();decryptFile(key, targer, out, CIPHER_ALGORITHM_AES,ALGORITHM_NAME_AES);System.out.println("AES解密時間:"+(System.currentTimeMillis()-star));in = new FileInputStream("F:logsmc_info.log.14");//源文件targer = "D:logsmc_info.log.17";//加密后文件star = System.currentTimeMillis();encryptStream(key,in,targer,CIPHER_ALGORITHM_SM4,ALGORITHM_NAME_SM4);System.out.println("SM4加密時間:"+(System.currentTimeMillis()-star));out = new FileOutputStream("D:logsmc_info.log.18");star = System.currentTimeMillis();decryptFile(key, targer, out, CIPHER_ALGORITHM_SM4,ALGORITHM_NAME_SM4);System.out.println("SM4解密時間:"+(System.currentTimeMillis()-star));in = new FileInputStream("F:logsmc_info.log.14");//源文件targer = "D:logsmc_info.log.19";//加密后文件star = System.currentTimeMillis();encryptStream(key,in,targer,CIPHER_ALGORITHM_BLOWFISH,ALGORITHM_NAME_BLOWFISH);System.out.println("BLOWFISH加密時間:"+(System.currentTimeMillis()-star));out = new FileOutputStream("D:logsmc_info.log.20");star = System.currentTimeMillis();decryptFile(key, targer, out, CIPHER_ALGORITHM_BLOWFISH,ALGORITHM_NAME_BLOWFISH);System.out.println("BLOWFISH解密時間:"+(System.currentTimeMillis()-star));in = new FileInputStream("F:logsmc_info.log.14");//源文件targer = "D:logsmc_info.log.21";//加密后文件star = System.currentTimeMillis();encryptStream(key,in,targer,CIPHER_ALGORITHM_3DES_ECB,ALGORITHM_NAME_3DES);System.out.println("3DES加密時間:"+(System.currentTimeMillis()-star));out = new FileOutputStream("D:logsmc_info.log.22");star = System.currentTimeMillis();decryptFile(key, targer, out, CIPHER_ALGORITHM_3DES_ECB,ALGORITHM_NAME_3DES);System.out.println("3DES解密時間:"+(System.currentTimeMillis()-star));in = new FileInputStream("F:logsmc_info.log.14");//源文件targer = "D:logsmc_info.log.22";//加密后文件star = System.currentTimeMillis();encryptStream(key,in,targer,CIPHER_ALGORITHM_RC2,ALGORITHM_NAME_RC2);System.out.println("RC2加密時間:"+(System.currentTimeMillis()-star));out = new FileOutputStream("D:logsmc_info.log.23");star = System.currentTimeMillis();decryptFile(key, targer, out, CIPHER_ALGORITHM_RC2,ALGORITHM_NAME_RC2);System.out.println("RC2解密時間:"+(System.currentTimeMillis()-star));}public static String generateKey(String algorithmName) throws Exception {KeyGenerator kg = KeyGenerator.getInstance(algorithmName, BouncyCastleProvider.PROVIDER_NAME);kg.init(DEFAULT_KEY_SIZE, new SecureRandom());byte[] result = kg.generateKey().getEncoded();return new String(Hex.encodeHex(result, false));}}

跑出的结果如下

AES加密時間:6845AES解密時間:2880SM4加密時間:8328SM4解密時間:4255BLOWFISH加密時間:7648BLOWFISH解密時間:39353DES加密時間:183513DES解密時間:14710RC2加密時間:12116RC2解密時間:4151

java加密解密代码_java加解密文件公用方法整合(多看一本书,少写三行代码)相关推荐

  1. rsa java代码_java加解密RSA使用方法代码示例

    最近为了分析一段请求流,不得不去研究一下RSA加密. 首先,强调一点:密钥的"钥"读"yue",不是"yao",额... 网上关于RSA的原 ...

  2. java sha加解密算法_java加解密

    SHA256 ------------------java自带实现方式--------------- package com.xiayu.demo; import java.io.Unsupporte ...

  3. java加密工作模式None_java加解密算法--对称加密工作模式

    对称加密又分为分组加密和序列密码. 分组密码,也叫块加密(block cyphers),一次加密明文中的一个块.是将明文按一定的位长分组,明文组经过加密运算得到密文组,密文组经过解密运算(加密运算的逆 ...

  4. Java md5加解密汉字_Java加解密_MD5

    在Java中使用MD5摘要还是很方便的,直接上代码. 1 packagecom.cxc.nothing;2 3 importjava.nio.charset.Charset;4 importjava. ...

  5. java pkcs#11读取证书加解密(初学-分享)

    java pkcs#11读取证书加解密(初学-分享) http://www.cnblogs.com/sunfb/archive/2013/02/28/2937227.html 插入USB-KEY, 想 ...

  6. java 多个类共用属性_java中读写Properties属性文件公用方法详解

    前言 大家都知道Java中有个比较重要的类Properties(Java.util.Properties),主要用于读取Java的配置文件,各种语言都有自己所支持的配置文件,配置文件中很多变量是经常改 ...

  7. Java之相对路径找不到文件问题解决方法

    Java之相对路径找不到文件问题解决方法 参考文章: (1)Java之相对路径找不到文件问题解决方法 (2)https://www.cnblogs.com/gongxr/p/8862155.html ...

  8. 微服务应用大行其道,我提供一个dto和entity转换工具类,方便大家做转换,少写机械代码,多陪陪家人

    微服务应用大行其道,我提供一个dto和entity转换工具类,方便大家做转换,少写机械代码,多陪陪家人. 该工具类主要是对dozer进行了封装,使用过程代码量极少,废话少说,贴代码了 import j ...

  9. 微服务应用大行其道,我提供一个dto和entity转换工具类,方便大家做转换,少写机械代码,多陪陪家人...

    微服务应用大行其道,我提供一个dto和entity转换工具类,方便大家做转换,少写机械代码,多陪陪家人. 该工具类主要是对dozer进行了封装,使用过程代码量极少,废话少说,贴代码了 import j ...

最新文章

  1. 创建和存储 cookie
  2. hql懒加载后判断对象是否存在_hibernate延迟加载(懒加载)详解
  3. RA维持期达标式减停生物制剂(DRESS研究)的18个月数据
  4. Python统计共同参演电影最多的演员组合
  5. 多程序集版本冲突问题
  6. BZOJ2728 HNOI2012与非(并查集+数位dp)
  7. Overpass Turbo下载OSM数据
  8. QQ游戏连连看的脚本
  9. 七年级上册数学用计算机进行计算,数学北师大版七年级上册用计算器进行运算.doc...
  10. python文本处理
  11. capslock键英语怎么读_capslock怎么读
  12. 智汇上海:微软在中国的AI人工智能布局
  13. Unity导出exe时遇到的两个问题
  14. 04735数据库系统原理(笔记)(更新中)
  15. Python模块——标准库\开源模块\自定义模块
  16. 《机器学习实战》——第3章 决策树
  17. android5.1 rom互刷,一加2 代通刷 5.1.1 ROM刷机包 个人适配 附加高级设置 稳定
  18. IC设计数字工程师技能必备
  19. 用dom4j解析xml错误-Content is not allowed in prolog前言中不允许有内容
  20. matlab中找矩阵最小值,matlab寻找矩阵最小值

热门文章

  1. gentoo 安装php7,在Gentoo安装Wifidog Portal
  2. 新款苹果电脑_“Mac历史性的一天”!别了,英特尔!苹果电脑将采用自研芯片,公司股价又创新高...
  3. 自学python考哪些证书-自学Python半年的姑娘告诉我,她这半年只值8元
  4. python是什么类型的编程语言-Python是个什么语言?
  5. python在线学习直播-Python在线学习最有效马哥开启全网独家全程直播课
  6. 如何自学python知乎-马哥教育官网-专业Linux培训班,Python培训机构
  7. ICRoute 语音识别芯片/声控芯片 用声音去沟通 LD332X系列语音识别芯片
  8. 成都高新税务推出智能电话语音咨询服务 24小时在线答复
  9. 并行DA实验c语言程序,求助怎么把两个单片机c语言程序结合在一起?大一期末实验...
  10. android usb软件自动安装监控,Android中监控USB的插拔