1
13693261870
2024-08-25 f6ad52119ce752858edda6d5bf95f8e89a3e3e39
1
已添加2个文件
342 ■■■■■ 文件已修改
se-common/se-common-core/src/main/java/com/se/common/core/utils/AesUtils.java 130 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
se-common/se-common-core/src/main/java/com/se/common/core/utils/RsaUtils.java 212 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
se-common/se-common-core/src/main/java/com/se/common/core/utils/AesUtils.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,130 @@
package com.se.common.core.utils;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
/**
 * AES加密工具
 *
 * @author WWW
 * @date 2024-08-25
 */
@SuppressWarnings("ALL")
public class AesUtils {
    /**
     * å¯†é’¥é•¿åº¦å¿…须是16
     */
    private static final String DEFAULT_KEY = "A#s_zZ_sErve_k.y";
    private static final String KEY_ALGORITHM = "AES";
    /**
     * ç®—法
     */
    private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";
    /**
     * aes解密
     *
     * @param encrypt å†…容
     * @return
     * @throws Exception
     */
    public static String decrypt(String encrypt) throws Exception {
        return decrypt(encrypt, DEFAULT_KEY);
    }
    /**
     * aes加密
     *
     * @param content å†…容
     * @return
     * @throws Exception
     */
    public static String encrypt(String content) throws Exception {
        return encrypt(content, DEFAULT_KEY);
    }
    /**
     * base 64 encode
     *
     * @param bytes å¾…编码的byte[]
     * @return ç¼–码后的base64 code
     */
    private static String base64Encode(byte[] bytes) {
        return Base64.getEncoder().encodeToString(bytes);
    }
    /**
     * base 64 decode
     *
     * @param base64Code å¾…解码的base64 code
     * @return è§£ç åŽçš„byte[]
     * @throws Exception
     */
    private static byte[] base64Decode(String base64Code) {
        return StringUtils.isEmpty(base64Code) ? null : Base64.getDecoder().decode(base64Code);
    }
    /**
     * AES加密
     *
     * @param content    å¾…加密的内容
     * @param encryptKey åР坆坆钥
     * @return åŠ å¯†åŽçš„byte[]
     * @throws Exception
     */
    private static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception {
        // KeyGenerator kGen = KeyGenerator.getInstance(KEY_ALGORITHM)
        // kGen.init(128)
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), KEY_ALGORITHM));
        return cipher.doFinal(content.getBytes("utf-8"));
    }
    /**
     * AES加密为base 64 code
     *
     * @param content    å¾…加密的内容
     * @param encryptKey åР坆坆钥
     * @return åŠ å¯†åŽçš„base 64 code
     * @throws Exception
     */
    public static String encrypt(String content, String encryptKey) throws Exception {
        return base64Encode(aesEncryptToBytes(content, encryptKey));
    }
    /**
     * å°†base 64 code AES解密
     *
     * @param encryptStr å¾…解密的base 64 code
     * @param decryptKey è§£å¯†å¯†é’¥
     * @return è§£å¯†åŽçš„string
     * @throws Exception
     */
    public static String decrypt(String encryptStr, String decryptKey) throws Exception {
        return StringUtils.isEmpty(encryptStr) ? null : aesDecryptByBytes(base64Decode(encryptStr), decryptKey);
    }
    /**
     * AES解密
     *
     * @param encryptBytes å¾…解密的byte[]
     * @param decryptKey   è§£å¯†å¯†é’¥
     * @return è§£å¯†åŽçš„String
     * @throws Exception
     */
    private static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception {
        // KeyGenerator kGen = KeyGenerator.getInstance(KEY_ALGORITHM)
        // kGen.init(128)
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), KEY_ALGORITHM));
        byte[] decryptBytes = cipher.doFinal(encryptBytes);
        return new String(decryptBytes);
    }
}
se-common/se-common-core/src/main/java/com/se/common/core/utils/RsaUtils.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,212 @@
package com.se.common.core.utils;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import javax.crypto.Cipher;
import java.io.*;
import java.nio.charset.StandardCharsets;
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工具类
 *
 * @author WWW
 * @date 2024-08-25
 */
public class RsaUtils {
    /**
     * ç§é’¥
     */
    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;
    /**
     * æ—¥å¿—
     */
    private static final Logger log = LoggerFactory.getLogger(RsaUtils.class);
    /**
     * ç”Ÿæˆå…¬ç§é’¥
     */
    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 (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
        return result;
    }
    /**
     * RSA私钥解密
     *
     * @param str åŠ å¯†çš„å­—ç¬¦ä¸²
     * @return è§£å¯†å­—符串
     * @throws Exception åŠ å¯†è¿‡ç¨‹ä¸­çš„å¼‚å¸¸ä¿¡æ¯
     */
    public static String decrypt(String str) throws Exception {
        // 64位解码加密后的字符串
        byte[] inputByte = Base64.decodeBase64(str.getBytes(StandardCharsets.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(StandardCharsets.UTF_8)));
        return outStr;
    }
}