用Java存储数据库密码(在JDBC连接字符串中需要)的最佳方法是什么? [英] What's the best way to store a Database Password (required in a JDBC connection string) in Java?
问题描述
我目前正在研究Java应用程序,以使用JDBC连接到Azure数据库.这就是我当前的代码-
I'm currently working on a Java Application to connect to an Azure DB using JDBC. This is what my current code looks like -
File file = new File("filename.txt");
Scanner scanner = new Scanner(file);
String pwd = scanner.nextLine();
String connectionUrl =
"jdbc:sqlserver:{A link here};" +
"database={DBName}; +
"user={UserName};" +
"password=" + pwd + ";"
"encrypt=true;" +
"trustServerCertificate=false;" +
"hostNameInCertificate=*.database.windows.net;" +
"loginTimeout=30;";
我打算在完成后在Github上公开上传该项目,显然在那里有一个纯文本密码似乎是一个可怕的主意.
I intend to upload this project publicly on Github when complete, and it obviously seems like a terrible idea to have a plain-text password there.
但是,我不确定执行此操作的最佳方法是什么.我认为存储散列密码不起作用,因为数据库字符串要求使用纯文本格式.我能想到的最好的办法是将密码存储在文本文档中(以及其他几个单词/文本),然后使用IO读取器/子字符串/BufferedReader将其作为变量读取.至少对于普通读者来说,这是有点伪装的,但是任何了解基本Java的人仍然可以识别它(或者只是放置一个简单的System.out.print(pwd))
However, I'm not sure what the best way to do this is. I don't think storing a Hashed password would work, since the DB string requires it in plain-text. The best I could come up with was storing the password in a text document (along with several other words/text), and using the IO reader/substrings/BufferedReader to read it as a variable. This at least somewhat disguises it to the casual reader, but anyone that knows basic Java will still be able to identify it (or just put a simple System.out.print(pwd))
似乎应该有一个更好的方法,但是我还没有找到任何可行的解决方案来阻止用户仅打开文本文档/conf文件并读取密码.我想保持连接完全自动化,因此不想提示用户输入密码.对于如何实现这一目标的回应将不胜感激!
It does seem like there should be a better way, but I haven't found any workable solutions that prevent the user from just opening the text document/conf file and reading the password. I would like to keep the connection completely automated, so wouldn't want to prompt the user to enter the password. Responses on how to achieve this would be appreciated!
我是一名(主要是自学成才的)学生,在Java方面的实践经验有限,因此如果我错过了一个相当明显的解决方案,那么深表歉意.
I am a (largely self-taught) student with limited practical experience when it comes to Java, so apologies if I've missed a fairly obvious solution.
推荐答案
通常,这些值存储在系统环境变量中.
Usually such values are stored in system environment variables.
例如,设置以下系统变量:
For example, set following system variables:
-
DATABASE_URL =<您的网址>
-
DATABASE_NAME =<您的数据库名称>
-
DATABASE_USER_NAME =<您的数据库用户名>
-
DATABASE_USER_PASSOWRD =<您的数据库用户密码>
然后在代码中使用 System.getProperty("DATABASE_URL")
等检索它们.甚至更好的办法是将所有连接URL存储在系统环境变量中:
Then in the code retrieve them by using System.getProperty("DATABASE_URL")
etc.
Or even better would be to store all connection URL in the system environment variable:
-
DATABASE_CONNECTION_URL = jdbc:sqlserver:someUrl ...
您可以在它们的官方文档或在StackOverflow上.
这篇关于用Java存储数据库密码(在JDBC连接字符串中需要)的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!