公钥私钥Util

package com.prophesy.util;

import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.util.CollectionUtils;
import sun.applet.Main;

import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class RSAUtils {
    private String secret;
    /**
     * 签名算法: MD5withRSA
     */
    public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
    private final static String CIPHER_ALGORITHM = "RSA/ECB/PKCS1Padding";
    private final static String PUBLIC_KEY = "PUBLIC_KEY";
    private final static String PRIVATE_KEY = "PRIVATE_KEY";

    /**
     * 根据base64生成RSA公钥
     *
     * @param base64Str
     * @return
     */
    public static PublicKey generatePublicKey(String base64Str) {
        try {
            byte[] publicKeyBytes = Base64.decodeBase64(base64Str);
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            return keyFactory.generatePublic(keySpec);
        } catch (Throwable t) {
            throw new RuntimeException("generate public key error", t);
        }
    }

    /**
     * 根据base64生成RSA私钥
     *
     * @param base64Str
     * @return
     */
    public static PrivateKey generatePrivateKey(String base64Str) {
        try {
            byte[] privateKeyBytes = Base64.decodeBase64(base64Str);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            return keyFactory.generatePrivate(keySpec);
        } catch (Throwable t) {
            throw new RuntimeException("generate private key error", t);
        }
    }

    /**
     * 生成公私钥对
     *
     * @return
     */
    public static Map<String, Key> generateKeyPair() {
        try {
            SecureRandom secureRandom = new SecureRandom();
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            keyPairGenerator.initialize(2048, secureRandom);
            KeyPair keyPair = keyPairGenerator.generateKeyPair();
            Map<String, Key> keyPairMap = new HashMap<>(2);
            keyPairMap.put(PUBLIC_KEY, keyPair.getPublic());
            keyPairMap.put(PRIVATE_KEY, keyPair.getPrivate());
            return keyPairMap;
        } catch (Throwable t) {
            throw new RuntimeException("generate key pair error", t);
        }
    }

    /**
     * 根据公私钥对获取公钥base64
     *
     * @param keyPair
     * @return
     */
    public static String getPublicKeyBase64(Map<String, Key> keyPair) {
        if (!CollectionUtils.isEmpty(keyPair)) {
            Key key = keyPair.get(PUBLIC_KEY);
            if (key != null) {
                return Base64.encodeBase64String(key.getEncoded());
            }
        }
        return null;
    }

    /**
     * 根据公私钥对获取私钥base64
     *
     * @param keyPair
     * @return
     */
    public static String getPrivateKeyBase64(Map<String, Key> keyPair) {
        if (!CollectionUtils.isEmpty(keyPair)) {
            Key key = keyPair.get(PRIVATE_KEY);
            if (key != null) {
                return Base64.encodeBase64String(key.getEncoded());
            }
        }
        return null;
    }

    /**
     * 加密
     * @param data
     * @param key
     * @return
     */
    public static byte[] encrypt(byte[] data, Key key) {
        try {
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            return cipher.doFinal(data);
        } catch (Exception e) {
            throw new RuntimeException("encrypt fail!", e);
        }
    }

    /**
     * 加密
     * @param data
     * @param key
     * @return
     */
    public static String encryptToBase64(String data, Key key) {
        try {
            return Base64.encodeBase64String(encrypt(data.getBytes(StandardCharsets.UTF_8), key));
        } catch (Exception e) {
            throw new RuntimeException("encrypt fail!", e);
        }
    }

    /**
     * 解密
     * @param data
     * @param key
     * @return
     */
    public static byte[] decrypt(byte[] data, Key key) {
        try {
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, key);
            return cipher.doFinal(data);
        } catch (Exception e) {
            throw new RuntimeException("decrypt fail!", e);
        }
    }

    /**
     * 解密
     * @param data
     * @param key
     * @return
     */
    public static String decryptFromBase64(String data, Key key) {
        try {
            return new String(decrypt(Base64.decodeBase64(data), key), StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new RuntimeException("decrypt fail!", e);
        }
    }

    /**
     * 签名
     * @param data
     * @param privateKeyStr
     * @return
     * @throws Exception
     */
    public static String sign(String data, String privateKeyStr) throws Exception {
        byte[] sign =sign(Base64.decodeBase64(data),privateKeyStr);
        return Base64.encodeBase64String(sign);
    }

    /**
     * 签名
     * @param data
     * @param privateKeyStr
     * @return
     * @throws Exception
     */
    public static byte[] sign(byte[] data, String privateKeyStr) throws Exception {
        PrivateKey priK = RSAUtils.generatePrivateKey(privateKeyStr);
        Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM);
        sig.initSign(priK);
        sig.update(data);
        return sig.sign();
    }

    /**
     * 验证签名
     * @param dataStr
     * @param signStr
     * @param publicKeyStr
     * @return
     * @throws Exception
     */
    public static boolean verify(String dataStr, String signStr, String publicKeyStr) throws Exception {
        byte[] data =Base64.decodeBase64(dataStr);
        byte[] sign =Base64.decodeBase64(signStr);
        return verify(data,sign,publicKeyStr);
    }

    /**
     * 验证签名
     * @param data
     * @param sign
     * @param publicKeyStr
     * @return
     * @throws Exception
     */
    public static boolean verify(byte[] data, byte[] sign, String publicKeyStr) throws Exception {
        PublicKey pubK = RSAUtils.generatePublicKey(publicKeyStr);
        Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM);
        sig.initVerify(pubK);
        sig.update(data);
        return sig.verify(sign);
    }


    public static void main(String[] args) throws Exception {
        String data="dsssssssssssssssss";
        //生成公私钥
        Map<String, Key> keymap=RSAUtils.generateKeyPair();
        //获取公钥
        String publicKey=RSAUtils.getPublicKeyBase64(keymap);
        System.err.println("公钥"+publicKey);
        //私钥
        String privateKey=RSAUtils.getPrivateKeyBase64(keymap);
        System.err.println("私钥"+privateKey);
        //加密
        String ss=RSAUtils.encryptToBase64(data,RSAUtils.generatePublicKey(publicKey));
        System.err.println("加密后:"+ss);
        //解密
        String s2=RSAUtils.decryptFromBase64(ss,RSAUtils.generatePrivateKey(privateKey));
        System.err.println("解密后:"+s2);
        String data2 ="3444rff";
        String s3 =RSAUtils.sign(data2, privateKey);
        System.err.println("签名:"+s3);
        Boolean s4 =RSAUtils.verify(data2,s3,publicKey);
        System.err.println("验签:"+s4);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值