百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程字典 > 正文

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

toyiye 2024-08-10 21:26 7 浏览 0 评论

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

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

<dependencies>
		<dependency>
			<groupId>org.bouncycastle</groupId>
			<artifactId>bcprov-jdk15on</artifactId>
			<version>1.56</version>
		</dependency>
		<dependency>
			<groupId>commons-codec</groupId>
			<artifactId>commons-codec</artifactId>
			<version>1.10</version>
		</dependency>
	</dependencies> 

生成秘钥(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包中翻出目前支持的算法有



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

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:\\logs\\mc_info.log.14");//源文件
		String targer = "D:\\logs\\mc_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:\\logs\\mc_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:\\logs\\mc_info.log.14");//源文件
		targer = "D:\\logs\\mc_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:\\logs\\mc_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:\\logs\\mc_info.log.14");//源文件
		targer = "D:\\logs\\mc_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:\\logs\\mc_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:\\logs\\mc_info.log.14");//源文件
		targer = "D:\\logs\\mc_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:\\logs\\mc_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:\\logs\\mc_info.log.14");//源文件
		targer = "D:\\logs\\mc_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:\\logs\\mc_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加密時間:6845
AES解密時間:2880
SM4加密時間:8328
SM4解密時間:4255
BLOWFISH加密時間:7648
BLOWFISH解密時間:3935
3DES加密時間:18351
3DES解密時間:14710
RC2加密時間:12116
RC2解密時間:4151

相关推荐

为何越来越多的编程语言使用JSON(为什么编程)

JSON是JavascriptObjectNotation的缩写,意思是Javascript对象表示法,是一种易于人类阅读和对编程友好的文本数据传递方法,是JavaScript语言规范定义的一个子...

何时在数据库中使用 JSON(数据库用json格式存储)

在本文中,您将了解何时应考虑将JSON数据类型添加到表中以及何时应避免使用它们。每天?分享?最新?软件?开发?,Devops,敏捷?,测试?以及?项目?管理?最新?,最热门?的?文章?,每天?花?...

MySQL 从零开始:05 数据类型(mysql数据类型有哪些,并举例)

前面的讲解中已经接触到了表的创建,表的创建是对字段的声明,比如:上述语句声明了字段的名称、类型、所占空间、默认值和是否可以为空等信息。其中的int、varchar、char和decimal都...

JSON对象花样进阶(json格式对象)

一、引言在现代Web开发中,JSON(JavaScriptObjectNotation)已经成为数据交换的标准格式。无论是从前端向后端发送数据,还是从后端接收数据,JSON都是不可或缺的一部分。...

深入理解 JSON 和 Form-data(json和formdata提交区别)

在讨论现代网络开发与API设计的语境下,理解客户端和服务器间如何有效且可靠地交换数据变得尤为关键。这里,特别值得关注的是两种主流数据格式:...

JSON 语法(json 语法 priority)

JSON语法是JavaScript语法的子集。JSON语法规则JSON语法是JavaScript对象表示法语法的子集。数据在名称/值对中数据由逗号分隔花括号保存对象方括号保存数组JS...

JSON语法详解(json的语法规则)

JSON语法规则JSON语法是JavaScript对象表示法语法的子集。数据在名称/值对中数据由逗号分隔大括号保存对象中括号保存数组注意:json的key是字符串,且必须是双引号,不能是单引号...

MySQL JSON数据类型操作(mysql的json)

概述mysql自5.7.8版本开始,就支持了json结构的数据存储和查询,这表明了mysql也在不断的学习和增加nosql数据库的有点。但mysql毕竟是关系型数据库,在处理json这种非结构化的数据...

JSON的数据模式(json数据格式示例)

像XML模式一样,JSON数据格式也有Schema,这是一个基于JSON格式的规范。JSON模式也以JSON格式编写。它用于验证JSON数据。JSON模式示例以下代码显示了基本的JSON模式。{"...

前端学习——JSON格式详解(后端json格式)

JSON(JavaScriptObjectNotation)是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。它基于JavaScriptProgrammingLa...

什么是 JSON:详解 JSON 及其优势(什么叫json)

现在程序员还有谁不知道JSON吗?无论对于前端还是后端,JSON都是一种常见的数据格式。那么JSON到底是什么呢?JSON的定义...

PostgreSQL JSON 类型:处理结构化数据

PostgreSQL提供JSON类型,以存储结构化数据。JSON是一种开放的数据格式,可用于存储各种类型的值。什么是JSON类型?JSON类型表示JSON(JavaScriptO...

JavaScript:JSON、三种包装类(javascript 包)

JOSN:我们希望可以将一个对象在不同的语言中进行传递,以达到通信的目的,最佳方式就是将一个对象转换为字符串的形式JSON(JavaScriptObjectNotation)-JS的对象表示法...

Python数据分析 只要1分钟 教你玩转JSON 全程干货

Json简介:Json,全名JavaScriptObjectNotation,JSON(JavaScriptObjectNotation(记号、标记))是一种轻量级的数据交换格式。它基于J...

比较一下JSON与XML两种数据格式?(json和xml哪个好)

JSON(JavaScriptObjectNotation)和XML(eXtensibleMarkupLanguage)是在日常开发中比较常用的两种数据格式,它们主要的作用就是用来进行数据的传...

取消回复欢迎 发表评论:

请填写验证码