管道基础大数据平台系统开发-【后端】-Server
1
sws
2022-11-26 ab849f796bdc17236a95ea5fe5c166fb8f24a75c
src/main/java/com/lf/server/helper/RsaHelper.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,200 @@
package com.lf.server.helper;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.core.io.ClassPathResource;
import javax.crypto.Cipher;
import java.io.*;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
/**
 * RSA工具类 é»˜è®¤é•¿åº¦ä¸º2048位
 * @author LinTao
 * @date 2022/2/13
 */
public class RsaHelper {
    /**
     * ç§é’¥
     */
    private static String privateKey;
    /**
     * å…¬é’¥
     */
    private static String publicKey;
    private static final String KEY_ALGORITHM = "RSA";
    /**
     * RSA密钥长度:1024 æˆ– 2048
     */
    private static final int DEFAULT_RSA_KEY_SIZE = 1024;
    /**
     * ç”Ÿæˆå…¬ç§é’¥
     */
    public static void generate() {
        Map<String, String> result = generateRsaKey(DEFAULT_RSA_KEY_SIZE);
        System.out.println("公钥为:" + result.get("publicKey"));
        System.out.println("私钥为:" + result.get("privateKey"));
    }
    /**
     * èŽ·å–RSA加密私钥
     *
     * @return
     * @throws IOException
     */
    public static String getPrivateKey() throws IOException {
        if (privateKey == null) {
            InputStream inPrivate = new ClassPathResource("config" + File.separator + "rsa_private_key.txt").getInputStream();
            privateKey = inputStream2String(inPrivate);
            inPrivate.close();
        }
        return privateKey;
    }
    /**
     * èŽ·å–RSA加密公钥
     *
     * @return
     * @throws IOException
     */
    public static String getPublicKey() throws IOException {
        if (publicKey == null) {
            InputStream inPrivate = new ClassPathResource("config" + File.separator + "rsa_public_key.txt").getInputStream();
            publicKey = inputStream2String(inPrivate);
            inPrivate.close();
        }
        return publicKey;
    }
    /**
     * è¯»å–文本文件
     *
     * @param fileName æ–‡ä»¶è·¯å¾„
     * @return
     * @throws IOException
     */
    public static String readFile(String fileName) throws IOException {
        File file = new File(fileName);
        BufferedReader br = new BufferedReader(new FileReader(file));
        StringBuilder result = new StringBuilder();
        String line = null;
        while ((line = br.readLine()) != null) {
            result.append(System.lineSeparator() + line);
        }
        br.close();
        return result.toString();
    }
    /**
     * æŠŠinputStream转成String
     *
     * @param is
     * @return
     * @throws IOException
     */
    private static String inputStream2String(InputStream is) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int i = -1;
        while ((i = is.read()) != -1) {
            baos.write(i);
        }
        String str = baos.toString();
        baos.close();
        return str;
    }
    /**
     * ç”ŸæˆRSA的公私钥
     *
     * @param keySize 1025 æˆ– 2048
     * @return
     */
    public static Map<String, String> generateRsaKey(int keySize) {
        Map<String, String> result = new HashMap<>(2);
        try {
            KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
            // åˆå§‹åŒ–密钥对生成器,密钥大小为1024 2048位
            keyPairGen.initialize(keySize, new SecureRandom());
            // ç”Ÿæˆä¸€ä¸ªå¯†é’¥å¯¹ï¼Œä¿å­˜åœ¨keyPair中
            KeyPair keyPair = keyPairGen.generateKeyPair();
            // å¾—到公钥字符串
            String pub = new String(Base64.encodeBase64(keyPair.getPublic().getEncoded()));
            result.put("publicKey", pub);
            // å¾—到私钥字符串
            String pri = new String(Base64.encodeBase64(keyPair.getPrivate().getEncoded()));
            result.put("privateKey", pri);
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        }
        return result;
    }
    /**
     * RSA私钥解密
     *
     * @param str åŠ å¯†çš„å­—ç¬¦ä¸²
     * @return è§£å¯†å­—符串
     * @throws Exception åŠ å¯†è¿‡ç¨‹ä¸­çš„å¼‚å¸¸ä¿¡æ¯
     */
    public static String decrypt(String str) throws Exception {
        // 64位解码加密后的字符串
        byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
        // Base64编码的私钥
        byte[] decoded = Base64.decodeBase64(getPrivateKey());
        RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
        // RSA解密:RSA/ECB/NoPadding
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, priKey);
        String outStr = new String(cipher.doFinal(inputByte));
        return outStr;
    }
    /**
     * RSA公钥加密
     *
     * @param str éœ€è¦åŠ å¯†çš„å­—ç¬¦ä¸²
     * @return å¯†æ–‡
     * @throws Exception åŠ å¯†è¿‡ç¨‹ä¸­çš„å¼‚å¸¸ä¿¡æ¯
     */
    public static String encrypt(String str) throws Exception {
        // Base64编码的公钥
        byte[] decoded = Base64.decodeBase64(getPublicKey());
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
        // RSA加密:RSA/ECB/NoPadding
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        String outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));
        return outStr;
    }
}