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.Test
    public 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.Test
    public 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.Test
    public 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.Test
    public 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
                + "。";
    }
}

 

  • 6
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值