hibernate配置用户名密码加密

1 我使用的数据库连接池是c3p0,

即hibernate的配置为:

hibernate.connection.provider_class org.hibernate.connection.C3P0ConnectionProvider

2 hibernate配置文件中添加两个配置:代表密文

hibernate.connection.passwordSec RhxglVY1jAk
hibernate.connection.usernameSec RhxglVY1jAk

自定义一个类,继承 C3P0ConnectionProvider,覆写方法 configure,将账户名,密码的密文解密后,重新设置账户名,密码的明文即可。

4 hibernate配置修改,

hibernate.connection.provider_class com.ctc.ema.db.CustomDriverManagerConnectionProvider

5 CustomDriverManagerConnectionProvider中的main方法中是加密解密的部分

 

如下:

package com.ctc.ema.db;

import java.io.IOException;
import java.util.Properties;
import java.util.Scanner;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.cfg.Environment;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import com.ctc.ema.encry.Coder;
import com.ctc.ema.encry.des3.Encry_DES3;

public class CustomDriverManagerConnectionProvider extends org.hibernate.connection.C3P0ConnectionProvider {
    private static Logger log = Logger.getLogger(CustomDriverManagerConnectionProvider.class);

    public static byte[] key = null;
    static {
        try {
            key = new BASE64Decoder().decodeBuffer("DSLKFJSDLKLDKSJFSKDLsdkjdsfdslkssdkl");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            log.error("密钥生成失败", e);
        }
    }

    public CustomDriverManagerConnectionProvider() {
        super();

    }

   
    @Override
    public void configure(Properties props) throws HibernateException {
        String users = props.getProperty("hibernate.connection.usernameSec");
        String passwords = props.getProperty("hibernate.connection.passwordSec");
        try {
            if (StringUtils.isNotBlank(users)) {
                byte[] userByte = Encry_DES3.des3DecodeECB(key, Coder.decryptBASE64(users));
                props.setProperty(Environment.USER, new String(userByte, "UTF-8"));
            }
            if (StringUtils.isNotBlank(passwords)) {
                byte[] passByte = Encry_DES3.des3DecodeECB(key, Coder.decryptBASE64(passwords));
                props.setProperty(Environment.PASS, new String(passByte, "UTF-8"));
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            log.error("密文解密失败:", e);
        }
        super.configure(props);
    }

    public static void main(String[] args) {
        try {
            while (true) {
                dealSec();
            }
        } catch (Throwable e) {
            e.printStackTrace();
            log.error("运行异常,退出.....", e);
            exit();
        }
        exit();

    }

    private static void dealSec() throws Throwable {
        System.out.println("");
        System.out.println("--------------------------");
        System.out.println("---------- 0:加密 ----------");

//解密不要开放,否则直接拿密文就可以还原成明文
//      System.out.println("---------- 1:解密 ----------");
        System.out.println("---------- 2:退出 ----------");
        System.out.println("--------------------------");
        System.out.println("");
        System.out.print("请选择:");
        Scanner input = new Scanner(System.in);
        String s = input.next();
        if (StringUtils.isNotBlank(s)) {
            if ("2".equals(s)) {
                System.out.println("退出......");
                exit();
            } else if ("0".equals(s)) {
                System.out.print("请输入需要加密的明文:");
                input = new Scanner(System.in);
                s = input.next();
                if (StringUtils.isNotBlank(s)) {
                    byte[] data = s.getBytes("UTF-8");
                    byte[] str3 = Encry_DES3.des3EncodeECB(key, data);
                    System.out.println(s + "加密后的密文为:" + new BASE64Encoder().encode(str3));
                }
            } else if ("1".equals(s)) {
                System.out.print("请输入需要解密的密文:");
                input = new Scanner(System.in);
                s = input.next();
                if (StringUtils.isNotBlank(s)) {
                    byte[] str4 = Encry_DES3.des3DecodeECB(key, Coder.decryptBASE64(s));;
                    System.out.println(s + "解密后的明文为:" + new String(str4, "UTF-8"));
                }
            }
        }
    }

    private static void exit() {
        System.exit(1);
    }
}

Coder.java 代码:

package com.ctc.ema.encry;

import java.security.MessageDigest;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;


public class Coder {
 public static final String KEY_SHA = "SHA";
 public static final String KEY_MD5 = "MD5";

 
 public static final String KEY_MAC = "HmacMD5";

 
 public static byte[] decryptBASE64(String key) throws Exception {
  return (new BASE64Decoder()).decodeBuffer(key);
 }

 
 public static String encryptBASE64(byte[] key) throws Exception {
  return (new BASE64Encoder()).encodeBuffer(key);
 }

 
 public static byte[] encryptMD5(byte[] data) throws Exception {
  MessageDigest md5 = MessageDigest.getInstance(KEY_MD5);
  md5.update(data);
  return md5.digest();

 }

 
 public static byte[] encryptSHA(byte[] data) throws Exception {

  MessageDigest sha = MessageDigest.getInstance(KEY_SHA);
  sha.update(data);

  return sha.digest();

 }

 
 public static String initMacKey() throws Exception {
  KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_MAC);

  SecretKey secretKey = keyGenerator.generateKey();
  return encryptBASE64(secretKey.getEncoded());
 }

 
 public static byte[] encryptHMAC(byte[] data, String key) throws Exception {

  SecretKey secretKey = new SecretKeySpec(decryptBASE64(key), KEY_MAC);
  Mac mac = Mac.getInstance(secretKey.getAlgorithm());
  mac.init(secretKey);

  return mac.doFinal(data);

 }
}

 

Encry_DES3.java 代码:

 

package com.ctc.ema.encry.des3;

import java.security.Key;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;

import sun.misc.BASE64Decoder;

import com.ctc.ema.encry.Coder;


public class Encry_DES3 {


   
    public byte[] initKey(String license) {
        try {
            KeyGenerator _generator = KeyGenerator.getInstance("DESede");
            _generator.init(112, new SecureRandom(license.getBytes()));
            return _generator.generateKey().getEncoded();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

   
    public String getDesString(String strMi, String eaKey) {

        String strMing = "";
        try {
            byte[] strMiby = Coder.decryptBASE64(strMi);
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] keyArray = decoder.decodeBuffer(eaKey);
            byte[] byteMing = des3DecodeECB(keyArray, strMiby);
            strMing = new String(byteMing, "UTF8");

            return strMing;
        } catch (Exception e) {

            e.printStackTrace();
        }
        return null;
    }

   
    public String getEncString(String strMing, String eaKey) {
        byte[] byteMi = null;
        byte[] byteMing = null;
        String strMi = "";
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] keyArray = decoder.decodeBuffer(eaKey);
            byteMing = strMing.getBytes("UTF8");
            byteMi = des3EncodeECB(keyArray, byteMing);
            strMi = Coder.encryptBASE64(byteMi);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            byteMing = null;
            byteMi = null;
        }
        return strMi;
    }

   
    public static byte[] des3EncodeECB(byte[] key, byte[] data) throws Exception {

        Key deskey = null;
        DESedeKeySpec spec = new DESedeKeySpec(key);
        SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
        deskey = keyfactory.generateSecret(spec);

        Cipher cipher = Cipher.getInstance("desede" + "/ECB/PKCS5Padding");

        cipher.init(Cipher.ENCRYPT_MODE, deskey);
        byte[] bOut = cipher.doFinal(data);

        return bOut;
    }

   
    public static byte[] des3DecodeECB(byte[] key, byte[] data) throws Exception {

        Key deskey = null;
        DESedeKeySpec spec = new DESedeKeySpec(key);
        SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
        deskey = keyfactory.generateSecret(spec);

        Cipher cipher = Cipher.getInstance("desede" + "/ECB/PKCS5Padding");

        cipher.init(Cipher.DECRYPT_MODE, deskey);

        byte[] bOut = cipher.doFinal(data);

        return bOut;

    }

}

收藏  | 打印  | 字体:  -缩小  放大+    
[ x ] 请正确填写下面信息


是否保存此网页快照 是否公开此收藏

查看全部评论(0)我来说两句