原文链接:https://blog.csdn.net/A_Lonely_Smile/article/details/118366945
对文档进行加密操作,只有经过系统解密后才能进行查看文档内容
这里使用hutool工具类提供的SM2方法,首先引入pom.xml依赖
hutool文档地址 https://www.hutool.cn/
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.6.5</version>
</dependency>
生成SM2密钥对
SM2 sm2 = new SM2();
String privateKeyBase64 = sm2.getPrivateKeyBase64();
String publicKeyBase64 = sm2.getPublicKeyBase64();
FileUtils工具类,进行byte数组和文件的转换
package com.smile.common.utils.file;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import java.io.*;
/**
* 文件处理工具类
*
* @author wujie
*/
@Slf4j
public class FileUtils {
/**
* 获得指定文件的byte数组
*
* @param filePath 文件路径
* @return 字节数组
*/
public static byte[] fileToByte(String filePath) {
byte[] buffer = null;
try {
File file = new File(filePath);
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
byte[] b = new byte[1024];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
bos.close();
buffer = bos.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return buffer;
}
/**
* 根据byte数组,生成文件
* @param bfile 字节数组
* @param filePath 文件路径
* @param fileName 文件名
*/
public static void byteToFile(byte[] bfile, String filePath, String fileName) {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
try {
File dir = new File(filePath);
if (!dir.exists() && dir.isDirectory()) {
dir.mkdirs();
}
file = new File(filePath + "\\" + fileName);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bfile);
} catch (Exception e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(bos);
IOUtils.closeQuietly(fos);
}
}
}
EncryptionTools 加解密工具类,这里用的静态代码块,加载已存在的密钥对,不用每次都生成新的密钥
package com.smile.project.openinterface.tools.ofd;
import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.SM2;
import com.smile.common.utils.file.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
/**
* 加解密工具类
*
* @author: WuJie
* @version: 1.0
**/
@Slf4j
public class EncryptionTools {
private static SM2 SM_2 = null;
static {
try {
BouncyCastleProvider BC = new BouncyCastleProvider();
String publicKeyStr = "MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAE6/ZmNaBRnZnisjtfxxh2r5F7MXjr2Rjf6wi5++WkUqU0APNadWN+jcZZeupwrkpOaS" +
"+epBpYFwaHhlMGIbUzKw==";
String privateKeyStr = "MIGTAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBHkwdwIBAQQgsTwYNqhtSjlpYDQnaKaEQbn9kVdSW3RJnFejbKTYa5KgCgYIKoEcz1UBgi2hRANCAATr9mY1oFGdmeKyO1/HGHavkXsxeOvZGN/rCLn75aRSpTQA81p1Y36Nxll66nCuSk5pL56kGlgXBoeGUwYhtTMr";
KeyFactory keyFactory = KeyFactory.getInstance("EC", BC);
PublicKey publicKey = keyFactory.generatePublic(new X509EncodedKeySpec(Base64.decode(publicKeyStr)));
PrivateKey privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(Base64.decode(privateKeyStr)));
SM_2 = SmUtil.sm2(privateKey, publicKey);
} catch (Exception e) {
log.info("SM2密钥初始化错误", e);
}
}
/**
* 文件加/解密
*
* @param source 原始文件路径
* @param out 输出路径
* @param fileName 输出文件名
* @param action 行为(true为加密,false为解密)
*/
public static void encryptionOrDecryption(String source, String out, String fileName, boolean action) {
byte[] bytes = FileUtils.fileToByte(source);
byte[] data;
if (action) {
data = SM_2.encrypt(bytes, KeyType.PublicKey);
} else {
data = SM_2.decrypt(bytes, KeyType.PrivateKey);
}
FileUtils.byteToFile(data, out, fileName);
}
/**
* 测试方法
*/
public static void main(String[] args) {
// 加密
encryptionOrDecryption("D:\\test\\test.pdf","D:\\test","encrypt.pdf",true);
// 解密
encryptionOrDecryption("D:\\test\\encrypt.pdf","D:\\test","decrypt.pdf",false);
}
}