java - 在属性文件中保护密码

标签 java security

我有一个连接到数据库的 java 应用程序。
数据库的用户名和密码存储在属性文件中。
避免在属性文件中以明文形式存储密码同时仍保留让用户更改密码的选项的常见做法是什么?
这里的主要动机是防止有人在管理员编辑属性文件时越过管理员的肩膀看到密码。
我读了here在 C# 中有一个内置的方法来做到这一点。
了解java,我不希望找到一个内置的解决方案,但我想听听其他人在做什么。
如果我没有找到任何好的选择,那么我可能会使用将保存在代码中的恒定密码对其进行加密。但我不想这样做,因为感觉不对。

2012 年 12 月 12 日编辑 看起来没有魔法,我必须将密码存储在代码或类似的东西中。 最后,我们实现了与答案之一中提到的 Jasypt 非常相似的东西。 所以我接受 Jasypt 的答案,因为它最接近明确的答案。

最佳答案

enter image description here

Jasypt 提供 org.jasypt.properties.EncryptableProperties用于加载、管理和透明解密 .properties 文件中的加密值的类,允许在同一文件中混合加密和未加密的值。

http://www.jasypt.org/encrypting-configuration.html

By using an org.jasypt.properties.EncryptableProperties object, an application would be able to correctly read and use a .properties file like this:

datasource.driver=com.mysql.jdbc.Driver 
datasource.url=jdbc:mysql://localhost/reportsdb 
datasource.username=reportsUser 
datasource.password=ENC(G6N718UuyPE5bHyWKyuLQSm02auQPUtm) 

Note that the database password is encrypted (in fact, any other property could also be encrypted, be it related with database configuration or not).

How do we read this value? like this:

/*
* First, create (or ask some other component for) the adequate encryptor for   
* decrypting the values in our .properties file.   
*/  
StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();     
encryptor.setPassword("jasypt"); // could be got from web, env variable...    
/*   
* Create our EncryptableProperties object and load it the usual way.   
*/  
Properties props = new EncryptableProperties(encryptor);  
props.load(new FileInputStream("/path/to/my/configuration.properties"));

/*   
* To get a non-encrypted value, we just get it with getProperty...   
*/  
String datasourceUsername = props.getProperty("datasource.username");

/*   
* ...and to get an encrypted value, we do exactly the same. Decryption will   
* be transparently performed behind the scenes.   
*/ 
String datasourcePassword = props.getProperty("datasource.password");

 // From now on, datasourcePassword equals "reports_passwd"...

关于java - 在属性文件中保护密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10306673/

相关文章:

java - 如何使用 JPA 分页应用基于 java 的过滤器?

java - 仅使用外部存储器比较两个带有 Java URL 的文本大文件?

java - Java 销售点系统的多级密码加密

security - 如何防止tomcat被黑客攻击?

security - nServiceBus 和安全 : what is best practise?

java - Travis-ci 无法构建其他 github 存储库贡献者所做的 github 提交

java - weblogic中的类转换异常

java - 断言失败后如何不停止执行?

asp.net - X-Frame-Options 允许来自多个域

java - JAX-RS 中的横切关注点