2016-08-19 113 views
0

由於安全要求,我需要將數據庫密碼作爲md5-hash存儲在我的hibernate.cfg.xml中,但據我所知,Hibernate不支持哈希密碼。我正在使用休眠5.1.0。哈希數據庫密碼[休眠]

我的hibernate.cfg.xml是這樣的:

<?xml version='1.0' encoding='UTF-8'?> 
<!DOCTYPE hibernate-configuration PUBLIC 
"-//Hibernate/Hibernate Configuration DTD//EN" 
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> 
<hibernate-configuration> 
<session-factory> 
    <property name="hibernate.connection.driver_class">org.h2.Driver </property> 
    <property name="hibernate.connection.url">jdbc:h2:tcp://localhost/~/test</property> 
    <property name="hibernate.connection.username">sa</property> 
    <property name="hibernate.connection.password"></property> 
     <property name="show_sql">true</property> 
    <property name="hibernate.c3p0.min_size">5</property> 
    <property name="hibernate.c3p0.max_size">20</property> 
    <property name="hibernate.c3p0.timeout">300</property> 
    <property name="hibernate.c3p0.max_statements">50</property> 
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property> 
    <property name="hibernate.hbm2ddl.auto">update</property> 

</session-factory> 
</hibernate-configuration> 

這是我如何創建一個SessionFactory:

import org.hibernate.SessionFactory; 
import org.hibernate.cfg.Configuration; 

public class HibernateUtility { 
    private static final SessionFactory sessionFactory = buildSessionFactory(); 

    private static SessionFactory buildSessionFactory() { 
     try { 
      // Create the SessionFactory from hibernate.cfg.xml 
      return new Configuration() 
        .configure() 
        .buildSessionFactory().; 
     } catch (Throwable ex) { 
      System.err.println("Initial SessionFactory creation failed." + ex); 
      throw new ExceptionInInitializerError(ex); 
     } 
    } 

    public static SessionFactory getSessionFactory() { 
     return sessionFactory; 
    } 
} 

是否有使用哈希數據庫密碼休眠的方式?

+2

請注意,MD5是一個非常弱(和碎)加密哈希算法。要麼使用帶有x次迭代的鹽漬SHA256 +,要麼更好地切換到像BCrypt這樣的密碼哈希算法。 –

+0

另請注意,哈希值不能顛倒,這就是爲什麼你不能使用它們登錄到任何系統。 –

+0

絕對與JPA API無關。刪除TAG –

回答

3

休眠時使用hibernate.connection.password內提供的密碼連接到數據庫,因此它需要實際的密碼而不是哈希密碼。

只有當您需要驗證用戶的身份時才存儲散列密碼,因爲一旦散列了文本,就不可逆

這是一個單向的過程:從您的密碼 可以得到散列文本,但你不能從密碼哈希生成文本回來。

如果您在hibernate.connection.password存儲哈希密碼,然後你的Hibernate將無法連接到數據庫,因爲沒有辦法從MD5哈希值獲取口令。所以這是不可能的。

還看到:Fundamental difference between Hashing and Encryption algorithms

然而,在hibernate.cfg.xml看到this question您可以加密密碼。

0

你應該更好地外化密碼,即從hibernate.cfg.xml中完全刪除它。然後您可以通過系統屬性將其傳入,例如將以下內容添加到您的服務器的啓動命令-Dhibernate.connection.password = password。

甚至更​​好的方法是在你的應用服務器中定義一個JNDI數據源,然後讓hibernate獲得對此的引用。然後,所有數據庫憑證將從應用程序配置中刪除,然後您可以將您的應用程序部署到不同的環境,而無需更改配置(假設JNDI數據源名稱保持一致)。

參見:

https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/session-configuration.html