哈希数据库密码 [Hibernate]

Hashed Database Password [Hibernate]

由于安全要求,我需要将数据库密码作为 md5 哈希存储在我的 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;
    }
}

有没有办法为休眠使用哈希数据库密码?

休眠使用 hibernate.connection.password 中提供的密码连接到数据库,因此它需要实际密码而不是散列密码。

只有在需要验证用户身份时才存储散列密码,因为任何文本一旦经过散列处理,就不可逆转

这是一个单向过程: 您可以从密码中获取散列文本,但无法从生成的散列文本中取回密码。

如果您在 hibernate.connection.password 中存储散列密码,那么您的休眠将无法连接到数据库,因为无法从 MD5 散列中获取密码。所以不可能。

另请参阅:Fundamental difference between Hashing and Encryption algorithms

但是,您可以在 hibernate.cfg.xml 中加密密码,请参阅 this question

您最好将密码外部化,即将其从 hibernate.cfg.xml 中完全删除。然后您可以通过系统 属性 将其传入,例如将以下内容添加到服务器的启动命令中 -Dhibernate.connection.password=password.

更好的方法是在您的应用程序服务器中定义一个 JNDI 数据源,然后让 hibernate 获取对此的引用。然后从应用程序配置中删除所有数据库凭据,然后您可以将应用程序部署到不同的环境而无需更改配置(假设 JNDI 数据源名称保持一致)。

参见:

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