sm4国密4加解密文件

package com.baian.common.fileftp.core.utils;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Hex;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.security.*;

/**
 * maven:
 * <dependency>
 * <groupId>commons-io</groupId>
 * <artifactId>commons-io</artifactId>
 * </dependency>
 * <dependency>
 * <groupId>org.bouncycastle</groupId>
 * <artifactId>bcpkix-jdk18on</artifactId>
 * </dependency>
 * 国密算法加密文件存储,引用依赖,jdk8+
 * 使用方式:
 * //1、 创建 key
 * String key = SM4FileEncryptUtils.getKey();
 * System.out.println("key: " + key);
 * //2、 创建SM4FileEncryptUtils
 * SM4FileEncryptUtils sm4FileEncryptUtils = new SM4FileEncryptUtils(key);
 * //3、 加密文件
 * sm4FileEncryptUtils.encryptFile("sourcePath", "targetPath");
 * //4、 解密文件
 * sm4FileEncryptUtils.decryptFile("targetPath", "sourcePath");
 *
 * @author: <航迹者-694204477@qq.com>
 * @create: 2024-07-24 09:19
 */
public class SM4FileEncryptUtils {

    private static final int KEY_SIZE = 128;

    private final String FILE_SM4_KEY;
//    private static String FILE_SM4_KEY = "BAE19A54EEAD4C7D9664C292EEB9D0F8";

    static {
        if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
            Security.addProvider(new BouncyCastleProvider());
        }
    }

    public SM4FileEncryptUtils(String fileSm4Key) {
        this.FILE_SM4_KEY = fileSm4Key;
    }

    public static void main(String[] args) {
        // 创建 key
        String key = SM4FileEncryptUtils.getKey();
        System.out.println("key: " + key);
        // 创建SM4FileEncryptUtils
        SM4FileEncryptUtils sm4FileEncryptUtils = new SM4FileEncryptUtils(key);
        // 加密文件
//        sm4FileEncryptUtils.encryptFile("sourcePath", "targetPath");
        // 解密文件
//        sm4FileEncryptUtils.decryptFile("targetPath", "sourcePath");
        String filePathPrefix = "/Users/linfahe/baian/project-workspace/fileflow-parent/file-ferry-core/src/test/java/com/fagejiang/";
        sm4FileEncryptUtils.encryptFile(filePathPrefix + "test.txt", filePathPrefix + "jiamitest.txt");
        sm4FileEncryptUtils.decryptFile(filePathPrefix + "jiamitest.txt", filePathPrefix + "jiemitest.txt");
    }

    //生成 Cipher
    private Cipher generateCipher(int mode, String key) throws InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException, NoSuchProviderException {
        Cipher cipher = Cipher.getInstance("SM4/ECB/PKCS5Padding", BouncyCastleProvider.PROVIDER_NAME);
        byte[] keyData = Hex.decode(key);
        Key sm4Key = new SecretKeySpec(keyData, "SM4");
        cipher.init(mode, sm4Key);
        return cipher;
    }

    /**
     * 利用系统内置密钥加密文件
     *
     * @param sourcePath 源文件路径
     * @param targetPath 目标文件路径
     */
    public void encryptFile(String sourcePath, String targetPath) {
        encryptFile(FILE_SM4_KEY, sourcePath, targetPath);
    }


    /**
     * 加密文件
     *
     * @param key        密钥字节数组
     * @param sourcePath 源文件路径
     * @param targetPath 目标文件路径
     */
    private void encryptFile(String key, String sourcePath, String targetPath) {
        //加密文件
        try {
            Cipher cipher = generateCipher(Cipher.ENCRYPT_MODE, key);
            CipherInputStream cipherInputStream = new CipherInputStream(new FileInputStream(sourcePath), cipher);
            FileUtils.copyInputStreamToFile(cipherInputStream, new File(targetPath));
            IOUtils.close(cipherInputStream);
        } catch (InvalidKeyException | NoSuchPaddingException | NoSuchAlgorithmException | NoSuchProviderException |
                 IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 解密文件
     *
     * @param sourcePath 待解密的文件路径
     * @param targetPath 解密后的文件路径
     */
    public void decryptFile(String sourcePath, String targetPath) {
        decryptFile(FILE_SM4_KEY, sourcePath, targetPath);
    }

    /**
     * 解密文件
     *
     * @param sourcePath 待解密的文件路径
     * @param targetPath 解密后的文件路径
     */
    private void decryptFile(String key, String sourcePath, String targetPath) {
        try (FileInputStream in = new FileInputStream(sourcePath);
             OutputStream out = new FileOutputStream(targetPath)) {
            try (InputStream bufferedInputStream = IOUtils.toBufferedInputStream(in);) {
                Cipher cipher = generateCipher(Cipher.DECRYPT_MODE, key);
                try (CipherOutputStream cipherOutputStream = new CipherOutputStream(out, cipher)) {
                    IOUtils.copy(bufferedInputStream, cipherOutputStream);
                }
            }
        } catch (IOException | InvalidKeyException | NoSuchPaddingException | NoSuchAlgorithmException |
                 NoSuchProviderException e) {
            e.printStackTrace();
        }
    }

    /**
     * 随机生成秘钥
     */
    public static String getKey() {
        try {
            KeyGenerator kg = KeyGenerator.getInstance("SM4");
            kg.init(KEY_SIZE);
            //要生成多少位,只需要修改这里即可128, 192或256
            SecretKey sk = kg.generateKey();
            byte[] b = sk.getEncoded();
            // byte数组转化为16进制字符串
            return Hex.toHexString(b);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            System.out.println("没有此算法。");
        }
        return null;
    }


}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

航迹者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值