SM2加密(公钥私钥模式)

发布时间 2023-11-17 14:30:35作者: show-code
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.SM2;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.security.KeyPair;

@Slf4j
@Component("SM2Util")
public class SM2Util {
    private static SM2 sm2;
    /**私钥*/
    final private static String privateKey = "调用下面的getSM2Key生成";//自己调用下面的getSM2Key生成
    /**公钥*/
    final private static String publicKey = "调用下面的getSM2Key生成";//自己调用下面的getSM2Key生成

    private static synchronized SM2 getSm2() {
        if (sm2 == null) {
//            Environment environment = SpringBeanUtil.getApplicationContext().getEnvironment();
//            String privateKey = environment.getProperty("encrypt.sm2.privateKey");
//            String publicKey = environment.getProperty("encrypt.sm2.publicKey");
            sm2 = SmUtil.sm2(Base64.decodeBase64(privateKey), Base64.decodeBase64(publicKey));
        }
        return sm2;
    }

    /**
     * 公钥加密
     *
     * @param cipherTxt
     * @return
     */
    public static String encrypt(String cipherTxt) {
        if (!StringUtils.hasText(cipherTxt)) {
            return cipherTxt;
        }
        String encryptStr = getSm2().encryptBcd(cipherTxt, KeyType.PublicKey);
        return encryptStr;
    }

    /**
     * 私钥解密
     *
     * @param plainTxt
     * @return
     */
    public static String decrypt(String plainTxt) {

        if (!StringUtils.hasText(plainTxt)) {
            return plainTxt;
        }
        String decryptStr = StrUtil.utf8Str(getSm2().decryptFromBcd(plainTxt, KeyType.PrivateKey));
        return decryptStr;
    }

    /**
     * 生成一对 C1C2C3 格式的SM2密钥
     *
     * @return 处理结果
     */
    public static void getSM2Key() {
        KeyPair pair = SecureUtil.generateKeyPair("SM2");
        byte[] privateKey = pair.getPrivate().getEncoded();
        byte[] publicKey = pair.getPublic().getEncoded();
        try {
            System.out.println("私钥" + new String(Base64.encodeBase64(privateKey), CharsetUtil.UTF_8));
            System.out.println("公钥" + new String(Base64.encodeBase64(publicKey), CharsetUtil.UTF_8));
        } catch (UnsupportedEncodingException e) {
            log.error(e.getMessage());
        }
    }

    public static void main(String[] args) {
//        getSM2Key();
        String name = "张三";
        String mi = encrypt(name);
        System.out.println(mi);
        System.out.println(decrypt(mi));
    }
}