SM4算法大文件加密与字符串加密
引入包
<!-- 一个开源的加解密算法包 --><dependency><groupId>org.bouncycastle</groupId><artifactId>bcmail-jdk15on</artifactId><version>1.66</version></dependency><!-- 测试包 --><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency>
工具类
import org.bouncycastle.jce.provider.BouncyCastleProvider;import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.Security;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.util.Base64;/*** @author zkk*/
public class Sm4Helper3 {private static final String PADDING_MODE = "SM4/ECB/PKCS5Padding";private static final String FILE_MODE_READ = "r";private static final String FILE_MODE_READ_WRITE = "rw";private static final String PBK_SHA1 = "PBKDF2WithHmacSHA1";private static final String ALGORITHM_SM4 = "SM4";private static final int KEY_DEFAULT_SIZE = 128;private static final int ENCRYPT_BUFFER_SIZE = 1024;private static final int DECRYPT_BUFFER_SIZE = 1040;static{try{Security.addProvider(new BouncyCastleProvider());}catch(Exception e){e.printStackTrace();}}/*** 文件加密* @param sourceFilePath 源文件文件路径* @param encryptFilePath 加密后文件路径* @param seed 种子* @throws Exception 异常*/public static void encryptFile(String sourceFilePath, String encryptFilePath, String seed) throws Exception {sm4Cipher(Cipher.ENCRYPT_MODE, sourceFilePath, encryptFilePath, seed);}/*** 文件解密* @param encryptFilePath 加密文件路径* @param targetFilePath 解密后文件路径* @param seed 种子* @throws Exception 异常*/public static void decryptFile(String encryptFilePath, String targetFilePath, String seed) throws Exception {sm4Cipher(Cipher.DECRYPT_MODE, encryptFilePath, targetFilePath, seed);}/*** 文件加解密过程* @param cipherMode 加解密选项* @param sourceFilePath 源文件地址* @param targetFilePath 目标文件地址* @param seed 密钥种子* @throws Exception 出现异常*/private static void sm4Cipher(int cipherMode, String sourceFilePath,String targetFilePath, String seed) throws Exception {FileChannel sourcefc = null;FileChannel targetfc = null;try {byte[] rawKey = getRawKey(seed);Cipher mCipher = generateEcbCipher(cipherMode, rawKey);File sourceFile = new File(sourceFilePath);File targetFile = new File(targetFilePath);sourcefc = new RandomAccessFile(sourceFile, FILE_MODE_READ).getChannel();targetfc = new RandomAccessFile(targetFile, FILE_MODE_READ_WRITE).getChannel();int bufferSize = Cipher.ENCRYPT_MODE == cipherMode ? ENCRYPT_BUFFER_SIZE : DECRYPT_BUFFER_SIZE;ByteBuffer byteData = ByteBuffer.allocate(bufferSize);while (sourcefc.read(byteData) != -1) {// 通过通道读写交叉进行。// 将缓冲区准备为数据传出状态byteData.flip();byte[] byteList = new byte[byteData.remaining()];byteData.get(byteList, 0, byteList.length);//此处,若不使用数组加密解密会失败,因为当byteData达不到1024个时,加密方式不同对空白字节的处理也不相同,从而导致成功与失败。byte[] bytes = mCipher.doFinal(byteList);targetfc.write(ByteBuffer.wrap(bytes));byteData.clear();}} finally {try {if (sourcefc != null) {sourcefc.close();}if (targetfc != null) {targetfc.close();}} catch (IOException e) {e.printStackTrace();}}}/*** 大字符串分段加密* @param content 需要加密的内容* @param seed 种子* @return 加密后内容* @throws Exception 异常*/public static String sm4EncryptLarge(String content, String seed) throws Exception {byte[] data = content.getBytes(StandardCharsets.UTF_8);byte[] rawKey = getRawKey(seed);Cipher mCipher = generateEcbCipher(Cipher.ENCRYPT_MODE, rawKey);int inputLen = data.length;ByteArrayOutputStream out = new ByteArrayOutputStream();int offSet = 0;byte[] cache;int i = 0;// 对数据分段解密while (inputLen - offSet > 0) {if (inputLen - offSet > ENCRYPT_BUFFER_SIZE) {cache = mCipher.doFinal(data, offSet, ENCRYPT_BUFFER_SIZE);} else {cache = mCipher.doFinal(data, offSet, inputLen - offSet);}out.write(cache, 0, cache.length);i++;offSet = i * ENCRYPT_BUFFER_SIZE;}byte[] decryptedData = out.toByteArray();out.close();return Base64.getEncoder().encodeToString(decryptedData);}/*** 大字符串分段解密* @param content 密文* @param seed 种子* @return 解密后内容* @throws Exception 异常*/public static String sm4DecryptLarge(String content, String seed) throws Exception {byte[] data = Base64.getDecoder().decode(content);byte[] rawKey = getRawKey(seed);Cipher mCipher = generateEcbCipher(Cipher.DECRYPT_MODE, rawKey);int inputLen = data.length;ByteArrayOutputStream out = new ByteArrayOutputStream();int offSet = 0;byte[] cache;int i = 0;// 对数据分段解密while (inputLen - offSet > 0) {if (inputLen - offSet > DECRYPT_BUFFER_SIZE) {cache = mCipher.doFinal(data, offSet, DECRYPT_BUFFER_SIZE);} else {cache = mCipher.doFinal(data, offSet, inputLen - offSet);}out.write(cache, 0, cache.length);i++;offSet = i * DECRYPT_BUFFER_SIZE;}byte[] decryptedData = out.toByteArray();out.close();return new String(decryptedData, StandardCharsets.UTF_8);}/*** 字符串加密* @param data 字符串* @param seed 种子* @return 加密后内容* @throws Exception 异常*/public static String sm4Encrypt(String data, String seed) throws Exception {byte[] rawKey = getRawKey(seed);Cipher mCipher = generateEcbCipher(Cipher.ENCRYPT_MODE, rawKey);byte[] bytes = mCipher.doFinal(data.getBytes(StandardCharsets.UTF_8));return Base64.getEncoder().encodeToString(bytes);}/*** 字符串解密* @param data 加密字符串* @param seed 种子* @return 解密后内容* @throws Exception 异常*/public static String sm4Decrypt(String data, String seed) throws Exception {byte[] rawKey = getRawKey(seed);Cipher mCipher = generateEcbCipher(Cipher.DECRYPT_MODE, rawKey);byte[] bytes = mCipher.doFinal(Base64.getDecoder().decode(data));return new String(bytes, StandardCharsets.UTF_8);}/*** 使用一个安全的随机数来产生一个密匙,密匙加密使用的* @param seed 种子* @return 随机数组* @throws NoSuchAlgorithmException 模式错误*/public static byte[] getRawKey(String seed) throws NoSuchAlgorithmException, InvalidKeySpecException {int count = 1000;int keyLen = KEY_DEFAULT_SIZE;int saltLen = keyLen / 8;SecureRandom random = new SecureRandom();byte[] salt = new byte[saltLen];random.setSeed(seed.getBytes());random.nextBytes(salt);KeySpec keySpec = new PBEKeySpec(seed.toCharArray(), salt, count, keyLen);SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(PBK_SHA1);return secretKeyFactory.generateSecret(keySpec).getEncoded();}/*** 生成ecb模式密码工具* @param mode 模式* @param key 密钥* @return 密码工具* @throws Exception 异常*/private static Cipher generateEcbCipher(int mode, byte[] key) throws Exception{Cipher cipher = Cipher.getInstance(PADDING_MODE, BouncyCastleProvider.PROVIDER_NAME);Key sm4Key = new SecretKeySpec(key, ALGORITHM_SM4);cipher.init(mode, sm4Key);return cipher;}
}
测试类
import java.time.Clock;/*** @author zkk*/
public class Sm4Test3 {private static final String SEED = "afeawredafe";@org.junit.Testpublic void test1() throws Exception {long time1 = Clock.systemUTC().millis() / 1000;String sourceFile = "E:\\test\\djbx\\file.docx";String targetFile = "E:\\test\\djbx\\file.encrypt";Sm4Helper3.encryptFile(sourceFile, targetFile, SEED);long time2 = Clock.systemUTC().millis() / 1000;System.out.println("加密时间 = " + (time2 - time1));}@org.junit.Testpublic void test2() throws Exception {long time1 = Clock.systemUTC().millis() / 1000;String targetFile = "E:\\test\\djbx\\file.encrypt";String sourceFile2 = "E:\\test\\djbx\\fileDecrypt.docx";Sm4Helper3.decryptFile(targetFile, sourceFile2, SEED);long time2 = Clock.systemUTC().millis() / 1000;System.out.println("解密时间 = " + (time2 - time1));}@org.junit.Testpublic void test3() throws Exception {String content = getLargeContent(1024000);System.out.println("content 长度 = " + content.length());long time1 = Clock.systemUTC().millis() / 1000;String en = Sm4Helper3.sm4Encrypt(content, SEED);
// System.out.println("en = " + en);long time2 = Clock.systemUTC().millis() / 1000;content = Sm4Helper3.sm4Decrypt(en, SEED);
// System.out.println("content = " + content);long time3 = Clock.systemUTC().millis() / 1000;System.out.println("加密时间 = " + (time2 - time1));System.out.println("解密时间 = " + (time3 - time2));}@org.junit.Testpublic void test4() throws Exception {String content = getLargeContent(1024000);System.out.println("content 长度 = " + content.length());long time1 = Clock.systemUTC().millis() / 1000;String en = Sm4Helper3.sm4EncryptLarge(content, SEED);
// System.out.println("en = " + en);long time2 = Clock.systemUTC().millis() / 1000;content = Sm4Helper3.sm4DecryptLarge(en, SEED);
// System.out.println("content = " + content);long time3 = Clock.systemUTC().millis() / 1000;System.out.println("加密时间 = " + (time2 - time1));System.out.println("解密时间 = " + (time3 - time2));}private static String getLargeContent(int count){StringBuilder sb = new StringBuilder();for (int i = 0; i < count; i++) {sb.append(getContent(i));}return sb.toString();}private static String getContent(int number){return "这是一段测试数据,结尾行号为"+ number+ "。";}
}
SM4算法大文件加密与字符串加密相关推荐
- java string 加密_java字符串加密解密
java字符串加密解密 try { String test = "123456789@fdj.com"; EncryptionDecryption des = new Encryp ...
- Java基于SM4算法实现文件加密 SM4FileUtils
SM4Utils 相关连接:https://blog.csdn.net/Jimmy12581/article/details/106468148 public class SM4FileUtils { ...
- Android常用加密手段之MD5加密(字符串加密和文件加密)
前言 安全问题一直伴随着互联网的成长,如何有效地保护应用程序的数据是每一个开发者都应该考虑和努力的事情.这篇文章介绍Android平台上常用的加密方式之MD5加密. MD5 MD5即Message-D ...
- 用java实现字符串的加密_JAVA 字符串加密、密码加密实现方法
在我们的程序设计中,我们经常要加密一些特殊的内容,今天总结了几个简单的加密方法,分享给大家! 如何用java实现字符串简单加密解密?为保证用户信息安全,系统在保存用户信息的时候,务必要将其密码加密保存 ...
- linux下打开大文件且搜索字符串的方法
使用more命令 一.more file.name 二.ctr f ctr b上下翻页 三.查找字符串的方法 输入 v 键即可: 此时会进入上下水平分割的两个窗口 四.退出快捷键:q 使用less命 ...
- 大文件MD5计算 C语言 (从OpenSSL库中分离算法:三)
从OpenSSL库中分离算法-MD5算法-大文件MD5计算 续上述博客 小文件计算MD5时,可以把文件数据一次性都读到内存中计算,但当文件很大时,将文件一次性读到内存中是不可行的,此时,需要对文件数据 ...
- 【Kotlin学习之旅】使用Kotlin实现常见的对称加密、非对称加密、消息摘要、数字签名的demo
文章目录 Demo 介绍 一.对称加密 二.非对称加密 三.消息摘要 四.数字签名 五.Demo地址 Demo 介绍 使用Kotlin实现常见的对称加密.非对称加密.消息摘要.数字签名的demo 一. ...
- 密码学03.5(SM4算法)
SM4算法 基本概念 SM4算法 基本变换规则 轮函数F 加密 密钥扩展运算 基本概念 明文分组.密钥.生成的密文长度都为128位. 采用非对称的Feistal结构.迭代32轮 对合运算,加解密算法一 ...
- 为什么都说Dubbo不适合传输大文件?Dubbo支持的协议
背景 之前公司有一个 Dubbo 服务,内部封装了腾讯云的对象存储服务 SDK,是为了统一管理这种三方服务的SDK,其他系统直接调用这个对象存储的 Dubbo 服务.用来避免因平台 SDK 出现不兼容 ...
最新文章
- 地区省份城市sql信息
- 前台开发之HTML定义语义化
- 微信平台全面封杀UBER的24小时里,优步做了什么
- 37、Power Query-不使用IF嵌套进行匹配
- python做圆柱绕流_圆柱绕流
- 最近面试遇到的技术问题
- 页面加载速度-合并资源文件
- Node JS Buffer使用理解
- android studio for android learning (二十一 )异步任务AsyncTask加载美女图片攻略及AsyncTask源码详解
- 库存收藏-各种设备默认用户名和密码
- NetLogo的下载安装过程
- 【庖丁解牛】configure: error: Please reinstall the libzip distribution
- Android制作.9图
- 微信小程序分页功能(上拉触底事件)
- dht11传感器c语言程序,数字温湿度传感器DHT11 操作C语言源代码
- Matplotlib-散点图详解
- mysql数据完整性实验报告,数据库原理实验报告(Mysql)
- 报错(root) Additional property redis is not allowed
- word2013打开后一直未响应完美解决方案
- 数独_软件工程基础个人项目
热门文章
- 解决在Filter中读取Request中的流后,后续controller或restful接口中无法获取流的问题
- 在马克思手稿中有一道趣味的数学问题:一共有30个人,可能包括男人,女人和小孩。他们在一家饭馆吃饭共花了50先令,其中每个男人花3先令,每个女人花2先令,每个小孩花1先令。请问男人、女人和小孩各几人?
- JAVA软件海豚_海豚调度系统Apache DolphinScheduler单机部署官方文档(Standalone)
- Android ExceptionThrowable 常见异常和解决方法 奔溃日志上报 monkey异常修改
- Angular primeng tree 组件数据解析(适用于Angular2+)
- 嵌入式linux kermit,嵌入式开发常用串口工具kermit使用笔记
- PyQt(Python+Qt)学习随笔:QTreeWidgetItem项列图标的访问方法
- S2FGAN论文阅读
- textfield观察UIControlEventEditingChanged时键盘快捷输入验证码会执行两次
- android 7 评测,iQOO 7 评测:性能出众,操控全面升级的横屏旗舰