引入jar包:bcprov-jdk15to18-1.72.jar
package com.hidy.hdoa6.util.SM4;
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.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
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.ArrayList;
import java.util.Base64;
import java.util.List;
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;
private static final String SEED = "afeawredafe";
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) 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) 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;
File sourceFile = new File(sourceFilePath);
File targetFile = new File(targetFilePath);
try {
byte[] rawKey = getRawKey(seed);
Cipher mCipher = generateEcbCipher(cipherMode, rawKey);
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);
byte[] encrypt=new byte[0];
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));
encrypt=unitByteArray(encrypt,bytes);
byteData.clear();
}
sourcefc.close();
if(!targetFile.getParentFile().exists()) {
targetFile.getParentFile().mkdirs();
}
if (targetFile.exists()) {
targetFile.delete();
}
InputStream in = new ByteArrayInputStream(encrypt);
OutputStream out = new FileOutputStream(targetFilePath);
int numRead = 0;
byte[] buf = new byte[1024];
while ((numRead = in.read(buf)) >= 0) {
out.write(buf, 0, numRead);
}
buf = null;
out.close();
in.close();
} finally {
try {
if (sourcefc != null) {
sourcefc.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;
}
/**
* 文件加密返回流
* @param sourceFilePath 源文件文件路径
* @param encryptFilePath 加密后文件路径
* @param seed 种子
* @throws Exception 异常
*/
public static InputStream encryptFile(String sourceFilePath){
return sm4Cipher(Cipher.ENCRYPT_MODE, sourceFilePath,SEED);
}
/**
* 文件解密返回流
* @param encryptFilePath 加密文件路径
* @param seed 种子
* @throws Exception 异常
*/
public static InputStream decryptFile(String encryptFilePath) {
return sm4Cipher(Cipher.DECRYPT_MODE, encryptFilePath,SEED);
}
private static InputStream sm4Cipher(int cipherMode, String sourceFilePath, String seed) {
FileChannel sourcefc = null;
//FileChannel targetfc = null;
InputStream in=null;
try {
byte[] rawKey = getRawKey(seed);
Cipher mCipher = generateEcbCipher(cipherMode, rawKey);
File sourceFile = new File(sourceFilePath);
sourcefc = new RandomAccessFile(sourceFile, FILE_MODE_READ).getChannel();
int bufferSize = Cipher.ENCRYPT_MODE == cipherMode ? ENCRYPT_BUFFER_SIZE : DECRYPT_BUFFER_SIZE;
ByteBuffer byteData = ByteBuffer.allocate(bufferSize);
byte[] decrypted=new byte[0];
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);
decrypted=unitByteArray(decrypted,bytes);
byteData.clear();
}
return new ByteArrayInputStream(decrypted);
}catch(Exception e) {
e.printStackTrace();
return null;
} finally {
try {
if (sourcefc != null) {
sourcefc.close();
}
if (in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static byte[] unitByteArray(byte[] byte1,byte[] byte2){
byte[] unitByte = new byte[byte1.length + byte2.length];
System.arraycopy(byte1, 0, unitByte, 0, byte1.length);
System.arraycopy(byte2, 0, unitByte, byte1.length, byte2.length);
return unitByte;
}
}
package com.hidy.hdoa6.util.SM4;
import java.time.Clock;
public class Sm4Test3 {
private static final String SEED = "afeawredafe";
@org.junit.Test
public void test1() throws Exception {
long time1 = Clock.systemUTC().millis() / 1000;
String sourceFile = "F:\\1.docx";
// String targetFile = "F:\\1.encrypt";
Sm4Helper3.encryptFile(sourceFile);
long time2 = Clock.systemUTC().millis() / 1000;
System.out.println("加密时间 = " + (time2 - time1));
}
@org.junit.Test
public void test2() throws Exception {
long time1 = Clock.systemUTC().millis() / 1000;
String targetFile = "F:\\1.encrypt";
// String sourceFile2 = "F:\\2.docx";
Sm4Helper3.decryptFile(targetFile);
long time2 = Clock.systemUTC().millis() / 1000;
System.out.println("解密时间 = " + (time2 - time1));
}
}