首页 > 其他分享 >rdf-file:SM2加解密

rdf-file:SM2加解密

时间:2023-12-18 12:02:16浏览次数:30  
标签:SM2Toolkit String 加解密 SM2 rdf static new byte keyPath


一:SM2简介

SM2是中国密码学算法标准中的一种非对称加密算法(包括公钥和私钥)。SM2主要用于数字签名密钥交换加密解密等密码学。

  • 生成秘钥:用于生成一对公钥和私钥。公钥:用于加密数据和验证数字签名。私钥:用于解密数据和生成数字签名。
  • 数字签名:用于生成和验证数字签名,可以独立使用。数字签名可以确保数据的完整性和身份认证,防止数据被篡改或冒充。发送方可以使用自己的私钥生成数字签名,并将签名附加在数据上发送给接收方。接收方使用发送方的公钥来验证数字签名的有效性,从而确保数据的完整性和身份认证。
  • 密钥交换:双方可以使用各自的私钥和对方的公钥来生成一个共享密钥,用于后续的对称加密通信。
  • 加密解密:发送方使用接收方的公钥进行加密,接收方使用自己的私钥进行解密。

CFCA

二:Java

<dependency>
	<groupId>org.apache.commons</groupId>
	<artifactId>commons-lang3</artifactId>
	<version>3.9</version>
</dependency>

<dependency>
	<groupId>com.cfca</groupId>
	<artifactId>SADK</artifactId>
	<version>3.2.1.3</version>
</dependency>
public class SM2Util {

    private static final String PVK_FILE = ".pvk";
    private static final String PUB_FILE = ".puk";


    /**
     * 加密数据
     * @param publicKey
     * @param data
     */
    public static byte[] encrypt(PublicKey publicKey, byte[] data) throws Exception {
        byte[] result = null;
        SM2Toolkit sm2Toolkit = new SM2Toolkit();
        SM2PublicKey sm2PublicKey = (SM2PublicKey)publicKey;
        result = sm2Toolkit.SM2EncryptData(sm2PublicKey, data);
        return result;
    }

    public static byte[] decryptString(PrivateKey privateKey, String base64Text) throws Exception {
        SM2Toolkit sm2Toolkit = new SM2Toolkit();
        SM2PrivateKey sm2PrivateKey = (SM2PrivateKey)privateKey;
        return sm2Toolkit.SM2DecryptData(sm2PrivateKey, BASE64Toolkit.decode(base64Text));
    }

    public static void sm4EncryptFile(String key, String inFile, String outFile) throws Exception{
        SM4Toolkit toolkit = new SM4Toolkit();
        toolkit.SM4Init(key.getBytes(), key.getBytes());
        toolkit.SM4EncryptFile(inFile, outFile);
    }

    public static boolean sM4DecryptFile(String key, String inFile, String outFile) throws Exception {
        SM4Toolkit toolkit = new SM4Toolkit();
        toolkit.SM4Init(key.getBytes(), key.getBytes());
        return toolkit.SM4DecryptFile(inFile, outFile);
    }

    /**
     * 签名
     * @param privateKey
     */
    public static String singnString(PrivateKey privateKey, byte[] srcBytes) throws Exception {
        SM2Toolkit sm2Toolkit = new SM2Toolkit();
        SM2PrivateKey sm2PrivateKey = (SM2PrivateKey)privateKey;
        String result = BASE64Toolkit.encode(sm2Toolkit.SM2Sign(sm2PrivateKey, srcBytes));
        return result;
    }

    public static String sm2SignFile(String filePath, String privateKeyPath) throws Exception {
        SM2Toolkit sm2Toolkit = new SM2Toolkit();
        byte[] privateBytes = readKey(privateKeyPath);

        SM2PrivateKey sm2PrivateKey = (SM2PrivateKey)sm2Toolkit.SM2BuildPrivateKey(BASE64Toolkit.encode(privateBytes));
        byte[] hash = SM3Toolkit.SM3HashFile(sm2PrivateKey.getSM2PublicKey(), filePath);
        String result = BASE64Toolkit.encode(BCSoftSM2.sign(hash, sm2PrivateKey.dBigInteger(), true));
        return result;
    }


    /**
     * 文件验签
     * @param outfilePath
     * @param keyPath
     * @param singStr
     * @return
     */
    public static boolean verify(String outfilePath, String keyPath, String singStr) {
        boolean result = false;

        try {
            SM2Toolkit toolkit = new SM2Toolkit();
            SM2PublicKey sm2PublicKey = (SM2PublicKey)toolkit.SM2BuildPublicKey(BASE64Toolkit.encode(readKey(keyPath)));
            byte[] hash = SM3Toolkit.SM3HashFile(sm2PublicKey, outfilePath);
            result = toolkit.SM2VerifyHash(sm2PublicKey, hash, BASE64Toolkit.decode(singStr));
        } catch (Exception e) {
            throw new RuntimeException("文件验签失败");
        }

        return result;
    }


    /**
     * 读取私钥
     * @param keyPath
     * @return
     */
    public static SM2PrivateKey buildPrivateKey(String keyPath) throws Exception {
        if (!keyPath.endsWith(PVK_FILE)) {
            keyPath += PVK_FILE;
        }

        byte[] privateKeyByte = readKey(keyPath);
        SM2Toolkit sm2Toolkit = new SM2Toolkit();
        SM2PrivateKey sm2PrivateKey = (SM2PrivateKey)sm2Toolkit.SM2BuildPrivateKey(BASE64Toolkit.encode(privateKeyByte));
        return sm2PrivateKey;
    }

    /**
     * 读取公钥
     * @param keyPath
     * @return
     */
    public static SM2PublicKey buildPublicKey(String keyPath) throws Exception {
        if (!keyPath.endsWith(PUB_FILE)) {
            keyPath += PUB_FILE;
        }

        byte[] privateKeyByte = readKey(keyPath);
        SM2Toolkit sm2Toolkit = new SM2Toolkit();
        SM2PublicKey sm2PublicKey = (SM2PublicKey)sm2Toolkit.SM2BuildPublicKey(BASE64Toolkit.encode(privateKeyByte));
        return sm2PublicKey;
    }

    /**
     * 读取秘钥
     * @param filePath
     */
    public static byte[] readKey(String filePath) throws Exception {
        try(FileInputStream is = new FileInputStream(filePath)) {
            byte[] out = new byte[is.available()];
            byte[] buffer = new byte[1024];
            int len;
            for (int offset = 0; (len = is.read(buffer, 0, buffer.length)) != -1; offset += len) {
                System.arraycopy(buffer, 0, out, offset, len);
            }
            return out;
        }
    }


    public static void main(String[] args) throws Exception {
        SM2Toolkit toolkit = new SM2Toolkit();
        KeyPair keyPair = toolkit.SM2GenerateKeyPair();
        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();


        // 1. 对源文件进行签名(最终会作为签名文件和数据zip一起放到新的.zip中去)
        String zipPath = "/Temp/data.zip";
        String tempZipPath = "/Temp/Activiti/data.zip";
        String signguare = sm2SignFile(zipPath, "xxx.pvk");

        // 2. 对秘钥加密(最终将将加密的秘钥作为压缩包文件中的一部分)
        String verifyChars = "1234567890abcdefghijkmnopqrstuvwxyz";
        String encryptKey = RandomStringUtils.random(16, verifyChars).toUpperCase();
        
        byte[] encrypt = encrypt(buildPublicKey("/Temp/xxx.puk"), random16.getBytes());
        byte[] encryptKeyBytes = BASE64Toolkit.encode(encrypt).getBytes();

        // 3. 加密源文件
        sm4EncryptFile(encryptKey, zipPath, tempZipPath);
        
        // 4. 新的zip = (sign文件、秘钥文件、加密源文件)
    }
}

rdf-file:SM2加解密_rdf-file


标签:SM2Toolkit,String,加解密,SM2,rdf,static,new,byte,keyPath
From: https://blog.51cto.com/u_16114318/8871041

相关文章

  • Java加解密【回车换行】坑与解决
    在Java中进行加解密时,经常会遇到回车换行的问题,这可能导致加解密结果不符合预期,引发一系列的错误。本文将探讨在Java加解密中常见的回车换行问题,并提供解决方案,以确保数据的准确性和一致性。一、问题背景在文本数据进行加密时,回车换行字符可能会在不同的操作系统上表示方式不同。例......
  • 【APP小程序】微信小程序包解密+加解密算法JS逆向
    简介现如今大部分微信小程序抓包看到的数据均是加密的,无法通过常规的业务抓包进行测试,现通过对微信小程序包进行解密,获取到微信小程序源码对加解密算法进行分析。微信小程序解密小程序包默认路径:C:\Users\Administrator\Documents\WeChatFiles\Applet如不知道哪个是需要测试......
  • C# 使用AES实现简单的加解密
    加密://使用SHA-256哈希函数处理秘钥varhashedKey=GetSHA256Hash(publicKey);//加密varencryptString=EncryptStringToBytes_Aes(strs,hashedKey);staticstringGetSHA256Hash(stringinput){using(SHA256sha256=SHA256.Create()){byte......
  • .net中加解密用BouncyCastle就够了,支持常用的各种加密解密算法
    BouncyCastle是一个流行的Java加解密库,也支持在.NET平台上使用。下面是BouncyCastle在.NET下使用的一些常见功能,包括AES、RSA、MD5、SHA1、DES、SHA256、SHA384、SHA512等。在开始之前,请确保你已经将BouncyCastle的NuGet包安装到你的项目中。你可以通过NuGet......
  • vue+spirngboot前后端数据加解密(基于AES+RSA实现)
    案例说明案例只针对post请求这里使用’Content-Type’:‘application/x-www-form-urlencoded;charset=UTF-8’;为键值对的形式(非json)AES加密数据,RAS加密AES的key实现思路前台首先请求非加密接口获取后台的公钥前台在请求前生成自己的公钥和私钥,以及AES对称加密的key使用前台......
  • C++ CryptoPP使用AES加解密
    Crypto++(CryptoPP)是一个用于密码学和加密的C++库。它是一个开源项目,提供了大量的密码学算法和功能,包括对称加密、非对称加密、哈希函数、消息认证码(MAC)、数字签名等。Crypto++的目标是提供高性能和可靠的密码学工具,以满足软件开发中对安全性的需求。高级加密标准(Advanc......
  • netty服务端加解密
    参考链接:https://www.cnblogs.com/silyvin/articles/11827030.html一、解密1、自定义解密类importio.netty.buffer.ByteBuf;importio.netty.buffer.Unpooled;importio.netty.channel.ChannelHandlerContext;importio.netty.handler.codec.ByteToMessageDecoder;impor......
  • PHP 国密SM2 私钥公钥计算公式
      在线测试地址1.私钥可查询出公钥;公钥无法计算私钥,注意保护私钥安全;2.分割字符串:PHP函数substr($str,36|76);3.HEX转base64:PHP函数base64_encode(hex2bin());4.base64转HEX:PHP函数bin2hex(base64_decode());5.公钥HEX转PEM证书:字符串'3059301306072a8648ce3d02......
  • 关于 Angular 构建之后生成的 dist 目录和 esm2020, fesm2015 等等
    在Angular应用中,dist目录是构建应用后的输出目录,其中包含了已编译、打包和优化的应用文件。assets文件夹通常用于存放应用所需的静态资源,如图片、字体、配置文件等。esm2020、fesm2015和fesm2020是Angular构建过程中生成的文件夹,它们主要与Angular的模块加载系统和代码优化有关。......
  • SM2加密(公钥私钥模式)
    importcn.hutool.core.util.CharsetUtil;importcn.hutool.core.util.StrUtil;importcn.hutool.crypto.SecureUtil;importcn.hutool.crypto.SmUtil;importcn.hutool.crypto.asymmetric.KeyType;importcn.hutool.crypto.asymmetric.SM2;importlombok.extern.slf4j.......