Java实现文件加密与解密的SM4国密算法应用

  <dependency>
            <groupId>com.hutool</groupId>
            <artifactId>all</artifactId>
            <version>4.6.17</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/src/main/webapp/lib/sm4/hutool-all-4.6.17.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>com.bcprov</groupId>
            <artifactId>jdk15on</artifactId>
            <version>1.59</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/src/main/webapp/lib/sm4/bcprov-jdk15on-1.59.jar</systemPath>
        </dependency>

首先我们在idae开发工具导入导入pom.xml的两个必要依赖

 jar包下载地址:百度网盘 请输入提取码   npn8

 图上systemPath为jar包的文件路径,我们需要使用以下的路径存储jar包。(也可以自己设置)

java包的文件路径如图所示

然后创建所需要加密的文件 ,需要加密的文件内容,并保存文件加密的地址。

以下是代码实现:

使用密钥"0123456789abcdeffedcba9876543210"对文件加解密

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import org.bouncycastle.jcajce.io.CipherInputStream;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;

public class SM4Tools {
    public static void main(String[] args) throws Exception {

        String sp = "D:\\sm4jiami\\tt\\tt.txt";//原始文件
        String dp = "D:\\sm4jiami\\tt\\tt.txt加密文件";//加密后文件
        String dp2 = "D:\\sm4jiami\\tt\\tt.txt解密文件";//解密后文件

        // String key = "05d986b1141227cb20d46d0b56202024";
        // byte[] keyData = ByteUtils.fromHexString(key);
        //加密文件
        encryptFile(sp,dp);
        System.out.println("加密成功");
        //解密文件
        decryptFile(dp,dp2);
        System.out.println("解密成功");
    }
    private static String key = "0123456789abcdeffedcba9876543210";  //使用到的密钥对文件加密
    private static byte[] keyData = ByteUtils.fromHexString(key);

    static{
        if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null){
            //No such provider: BC
            Security.addProvider(new BouncyCastleProvider());
        }
    }

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


    //加密文件
    public static void encryptFile(String sourcePath,String targetPath){
        //加密文件
        try {
            Cipher cipher = generateCipher(Cipher.ENCRYPT_MODE,keyData);
            CipherInputStream cipherInputStream = new CipherInputStream(new FileInputStream(sourcePath), cipher);
            FileUtil.writeFromStream(cipherInputStream, targetPath);
            IoUtil.close(cipherInputStream);
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }


    /**
     * 解密文件
     * @param sourcePath 待解密的文件路径
     * @param targetPath 解密后的文件路径
     */
    public static void decryptFile(String sourcePath, String targetPath) {
        FileInputStream in =null;
        ByteArrayInputStream byteArrayInputStream =null;
        OutputStream out = null;
        CipherOutputStream cipherOutputStream=null;
        try {
            in = new FileInputStream(sourcePath);
            byte[] bytes = IoUtil.readBytes(in);
            byteArrayInputStream = IoUtil.toStream(bytes);

            Cipher cipher = generateCipher(Cipher.DECRYPT_MODE,keyData);

            out = new FileOutputStream(targetPath);
            cipherOutputStream = new CipherOutputStream(out, cipher);
            IoUtil.copy(byteArrayInputStream, cipherOutputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        }finally {
            IoUtil.close(cipherOutputStream);
            IoUtil.close(out);
            IoUtil.close(byteArrayInputStream);
            IoUtil.close(in);
        }
    }
}

运行代码

代码运行成功

我们可以看到文件路径上多了两个文件,分别是加解密后的文件

我们用右键选择打开方式,用文本的方式打开可以看到加密后的信息如下

ok我们加密成功了!同理解密的文件也能解密成功

以上就是java对sm4国密算法的加密解密方式。

物联沃分享整理
物联沃-IOTWORD物联网 » Java实现文件加密与解密的SM4国密算法应用

发表评论