天天看點

Druid資料庫加密

RSA加密工具類:

package cn.com.yns;

import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.codec.binary.Base64;

/**
 * @description: RSA加解密工具類
 * @author: Zhiwei Wang
 * @create: 2020/12/01
 */
public class RSAUtil {
    /**
     * 數字簽名,密鑰算法
     */
    private static final String RSA_KEY_ALGORITHM = "RSA";

    /**
     * 數字簽名簽名/驗證算法
     */
    private static final String SIGNATURE_ALGORITHM = "MD5withRSA";

    /**
     * RSA密鑰長度,RSA算法的預設密鑰長度是1024密鑰長度必須是64的倍數,在512到65536位之間
     */
    private static final int KEY_SIZE = 1024;

    /**
     * 生成密鑰對
     */
    public static Map<String, String> initKey() throws Exception {
        KeyPairGenerator keygen = KeyPairGenerator.getInstance(RSA_KEY_ALGORITHM);
        SecureRandom secrand = new SecureRandom();
        /**
         * 初始化随機産生器
         */
        secrand.setSeed("initSeed".getBytes());
        /**
         * 初始化密鑰生成器
         */
        keygen.initialize(KEY_SIZE, secrand);
        KeyPair keys = keygen.genKeyPair();

        byte[] pub_key = keys.getPublic().getEncoded();
        String publicKeyString = Base64.encodeBase64String(pub_key);

        byte[] pri_key = keys.getPrivate().getEncoded();
        String privateKeyString = Base64.encodeBase64String(pri_key);

        Map<String, String> keyPairMap = new HashMap<String, String>();
        keyPairMap.put("publicKeyString", publicKeyString);
        keyPairMap.put("privateKeyString", privateKeyString);

        return keyPairMap;
    }

    /**
     * 密鑰轉成字元串
     *
     * @param key
     * @return
     */
    public static String encodeBase64String(byte[] key) {
        return Base64.encodeBase64String(key);
    }

    /**
     * 密鑰轉成byte[]
     *
     * @param key
     * @return
     */
    public static byte[] decodeBase64(String key) {
        return Base64.decodeBase64(key);
    }

    /**
     * 公鑰加密
     *
     * @param data      加密前的字元串
     * @param publicKey 公鑰
     * @return 加密後的字元串
     * @throws Exception
     */
    public static String encryptByPubKey(String data, String publicKey) throws Exception {
        byte[] pubKey = RSAUtil.decodeBase64(publicKey);
        byte[] enSign = encryptByPubKey(data.getBytes(), pubKey);
        return Base64.encodeBase64String(enSign);
    }

    /**
     * 公鑰加密
     *
     * @param data   待加密資料
     * @param pubKey 公鑰
     * @return
     * @throws Exception
     */
    public static byte[] encryptByPubKey(byte[] data, byte[] pubKey) throws Exception {
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(pubKey);
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM);
        PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        return cipher.doFinal(data);
    }

    /**
     * 私鑰加密
     *
     * @param data       加密前的字元串
     * @param privateKey 私鑰
     * @return 加密後的字元串
     * @throws Exception
     */
    public static String encryptByPriKey(String data, String privateKey) throws Exception {
        byte[] priKey = RSAUtil.decodeBase64(privateKey);
        byte[] enSign = encryptByPriKey(data.getBytes(), priKey);
        return Base64.encodeBase64String(enSign);
    }

    /**
     * 私鑰加密
     *
     * @param data   待加密的資料
     * @param priKey 私鑰
     * @return 加密後的資料
     * @throws Exception
     */
    public static byte[] encryptByPriKey(byte[] data, byte[] priKey) throws Exception {
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(priKey);
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM);
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
        return cipher.doFinal(data);
    }

    /**
     * 公鑰解密
     *
     * @param data   待解密的資料
     * @param pubKey 公鑰
     * @return 解密後的資料
     * @throws Exception
     */
    public static byte[] decryptByPubKey(byte[] data, byte[] pubKey) throws Exception {
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(pubKey);
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM);
        PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, publicKey);
        return cipher.doFinal(data);
    }

    /**
     * 公鑰解密
     *
     * @param data      解密前的字元串
     * @param publicKey 公鑰
     * @return 解密後的字元串
     * @throws Exception
     */
    public static String decryptByPubKey(String data, String publicKey) throws Exception {
        byte[] pubKey = RSAUtil.decodeBase64(publicKey);
        byte[] design = decryptByPubKey(Base64.decodeBase64(data), pubKey);
        return new String(design);
    }

    /**
     * 私鑰解密
     *
     * @param data   待解密的資料
     * @param priKey 私鑰
     * @return
     * @throws Exception
     */
    public static byte[] decryptByPriKey(byte[] data, byte[] priKey) throws Exception {
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(priKey);
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM);
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return cipher.doFinal(data);
    }

    /**
     * 私鑰解密
     *
     * @param data       解密前的字元串
     * @param privateKey 私鑰
     * @return 解密後的字元串
     * @throws Exception
     */
    public static String decryptByPriKey(String data, String privateKey) throws Exception {
        byte[] priKey = RSAUtil.decodeBase64(privateKey);
        byte[] design = decryptByPriKey(Base64.decodeBase64(data), priKey);
        return new String(design);
    }

    /**
     * RSA簽名
     *
     * @param data   待簽名資料
     * @param priKey 私鑰
     * @return 簽名
     * @throws Exception
     */
    public static String sign(byte[] data, byte[] priKey) throws Exception {
        // 取得私鑰
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(priKey);
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM);
        // 生成私鑰
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
        // 執行個體化Signature
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        // 初始化Signature
        signature.initSign(privateKey);
        // 更新
        signature.update(data);
        return Base64.encodeBase64String(signature.sign());
    }

    /**
     * RSA校驗數字簽名
     *
     * @param data   待校驗資料
     * @param sign   數字簽名
     * @param pubKey 公鑰
     * @return boolean 校驗成功傳回true,失敗傳回false
     */
    public boolean verify(byte[] data, byte[] sign, byte[] pubKey) throws Exception {
        // 執行個體化密鑰工廠
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM);
        // 初始化公鑰
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(pubKey);
        // 産生公鑰
        PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);
        // 執行個體化Signature
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        // 初始化Signature
        signature.initVerify(publicKey);
        // 更新
        signature.update(data);
        // 驗證
        return signature.verify(sign);
    }

    public static void main(String[] args) {
        try {
            Map<String, String> keyMap = initKey();
            String publicKeyString = keyMap.get("publicKeyString");
            String privateKeyString = keyMap.get("privateKeyString");
            System.out.println("公鑰:" + publicKeyString);
            System.out.println("私鑰:" + privateKeyString);

            // 待加密資料
            String data = "admin123";
            // 公鑰加密
            String encrypt = RSAUtil.encryptByPubKey(data, publicKeyString);
            // 私鑰解密
            String decrypt = RSAUtil.decryptByPriKey(encrypt, privateKeyString);

            System.out.println("加密前:" + data);
            System.out.println("加密後:" + encrypt);
            System.out.println("解密後:" + decrypt);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

           

加密

package cn.com.yns;

import java.io.FileWriter;
import java.util.Map;

/**
 * @description: 渝農商資料庫連接配接加密工具--RSA
 * @author: Zhiwei Wang
 * @create: 2020/12/01
 */
public class encryptUtil {
    private static final String ENCODE = "UTF-8";
    private static final String PRIVATE_KEY = "privateKeyString";
    private static final String PUBLIC_KEY = "publicKeyString";

    public static void main(String[] args) {

        if (args.length == 0) {
            System.out.println("沒有指定任何參數!");
            return;
        } else if (args.length < 4) {
            System.out.println("指定參數不足!");
        } else {
            System.out.println("====加密開始====");
            StringBuffer sb = new StringBuffer();
            sb.append("輸入參數:")
                    .append("\n")
                    .append("url:")
                    .append(args[0])
                    .append("\n")
                    .append("username:")
                    .append(args[1])
                    .append("\n")
                    .append("password:")
                    .append(args[2]);

            try {
                //生成密鑰對
                Map keyPair = RSAUtil.initKey();
                //擷取私鑰
                String privateKey = keyPair.get(PRIVATE_KEY).toString();
                //擷取公鑰
                String publicKey = keyPair.get(PUBLIC_KEY).toString();
                sb.append("\n").append("公鑰:").append("\n").append(publicKey);
                sb.append("\n").append("私鑰:").append("\n").append(privateKey);

                //使用私鑰加密url
                String cipUrl = RSAUtil.encryptByPriKey(args[0], privateKey);
                sb.append("\n").append("url密文:").append(cipUrl);

                //使用私鑰加密username
                String cipUsername = RSAUtil.encryptByPriKey(args[1], privateKey);
                sb.append("\n").append("username密文:").append(cipUsername);

                //使用私鑰加密password
                String cipPassword = RSAUtil.encryptByPriKey(args[2], privateKey);
                sb.append("\n").append("password密文:").append(cipPassword);

                System.out.println(sb.toString());

                FileWriter fileWriter = new FileWriter(args[3] + "//加密結果.txt");
                fileWriter.write(sb.toString());
                fileWriter.flush();
                fileWriter.close();
                System.out.println("====加密完成====");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

           

Datasource

package cn.com.dhcc.credit.platform.datasource;

import cn.com.dhcc.credit.platform.util.PropertiesUtil;
import cn.com.dhcc.credit.platform.util.datasource.RSAUtil;
import com.alibaba.druid.pool.DruidDataSource;
import lombok.SneakyThrows;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.io.IOException;

/**
 * @description: 渝農商資料庫連接配接--加密
 * @author: Zhiwei Wang
 * @create: 2020/12/01
 */
public class YnsDataSource extends DruidDataSource {
    String publicKeyString = PropertiesLoaderUtils.loadAllProperties("db.properties").getProperty("publicKeyString");
    String encryptFlag = PropertiesLoaderUtils.loadAllProperties("db.properties").getProperty("encryptFlag");

    public YnsDataSource() throws IOException {
    }

    @SneakyThrows
    @Override
    public void setUrl(String jdbcUrl) {
        if("true".equals(encryptFlag)){
            this.jdbcUrl= RSAUtil.decryptByPubKey(jdbcUrl,publicKeyString);
        }
    }
    @SneakyThrows
    @Override
    public void setUsername(String username){
        if("true".equals(encryptFlag)){
            this.username= RSAUtil.decryptByPubKey(username,publicKeyString);
        }
    }
    @SneakyThrows
    @Override
    public void setPassword(String password){
        if("true".equals(encryptFlag)){
            this.password= RSAUtil.decryptByPubKey(password,publicKeyString);
        }
    }
}

           

配置檔案:

jdbc.driverType=cn.com.dhcc.credit.platform.datasource.YnsDataSource
#dbcp settings
jdbc.driver=oracle.jdbc.driver.OracleDriver
jdbc.url=oSizdCczsDmX7+ftg4OiYM/ftT9TkT4ejReUZzWU2Zo6o89SeoKCWVsAtiX/gmzDQzZGlAepWMxkbC3H33BRxx1YK+zL62YY1+9mlpdh57JPD6HXvqvqn27LBPkhjGa93722cO7B7bi2PJ4WQ1QS0Ri8CLYbB0InS1wA3Si1CLA=
jdbc.username=eAIRIOgbDtNTeEXsLJUSEQEpyzT+ugR6z6dhBL8svmBQRLN/3GFtI8/qN7vLIQ+eiRSefzRycI0TwjfKebUz4MfQPNxFJxNchICoScrfVUJ7bAlvtbJAwsM7mMH7SpSokvFi4fFb2QLOmiPkJj8MZfkK/Vt3d0DXUcRmBTiJi+8=
jdbc.password=eAIRIOgbDtNTeEXsLJUSEQEpyzT+ugR6z6dhBL8svmBQRLN/3GFtI8/qN7vLIQ+eiRSefzRycI0TwjfKebUz4MfQPNxFJxNchICoScrfVUJ7bAlvtbJAwsM7mMH7SpSokvFi4fFb2QLOmiPkJj8MZfkK/Vt3d0DXUcRmBTiJi+8=
databasePlatform=oracle.jdbc.driver.OracleDriver

publicKeyString=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDSUmOXyQmYYSnZacp0btvAZCOvCNPtzixAp7eJmzmAG4mgy/VgrY/s1BDLh9qTNHIRWXepUtwMrf1kYul/A45qE/2oxIbeeq4238YDWQ7ModOVXR9ytEHsT0jpCFvoYfYXYZnnoWRrLIBylQeXzqxbLDxxBxGCs4AjoRKh5S7nNQIDAQAB
encryptFlag=true

dbcp.maxIdle=5
dbcp.maxActive=150