Log in page which reads details from XML file java - java

I have created a basic log in page in Java that allows a user to log in successfully, however I have hard coded the username and password into the program. I would like to extend the program so it can accept multiple users from the XML File, as hard coding the details will be inefficient. This is the chunk of code that validates the log in details.
private void loginActionPerformed(java.awt.event.ActionEvent evt) {
if(username.getText().length()==0||password.getText().length()==0){
JOptionPane.showMessageDialog(null,"Mistake");
} else if (username.getText().trim().equals("admin")&& password.getText().equals("hello")){
JOptionPane.showMessageDialog(null, "Success));
}else {
JOptionPane.showMessageDialog(null, "Error");
}
}
This code only allows admin to log in as it is hard coded into the program.
Would the best solution to be to create a new class that reads the XML file and then create a object in the code above with the parameters username and password.

Keeping your users/passwords in an xml file will be an improvement over your actual code.
However, cipher (MD5?) the passwords to avoid having files in your disk whith pwds in plain text!
So you need to cipher also the passwords the users are introducing and then compare the cyphered codes, not the raw ones.
Typically this info is stored in an XML file or preferably in a database (which is also protected by its own access security policy)

Related

How can i store MySQL database password and username to access the database?

I am working on a project which have to access the MySQL database username and password to read and update the user database.
Initially i wrote the username and password of the database directly to my code.
But my teacher asked me to create a prompt box which will take the username and password on 1st run of the program and not again.
So if do that i will not be able to access the database next time.
I was thinking to store that username and password into a local text file.
Is it good idea.
Or there are any good methods to do this type of work?
You can store the information in a properties file (https://docs.oracle.com/javase/tutorial/essential/environment/properties.html), but should use encryption. See: How to encrypt String in Java
In your case, the best way will be storing in .properties file.
And after getting a user input => store to the properties file.
Also, good practice for storing passwords in DB is to use one-way hash. A variety of hash methods is good for this: MD5, SHA-256, etc.
However, it works only for one way. More info here - MD5 algorithm Decryption in java.
And in your case properties file should be enough.
Example for db.properties:
db.username=MyUser
db.password=MyPassword
You can have default values for connection. If user input doesn't match with it just print a warning message with something, like: "DB username or password is incorrect. Try again."
You can use something like JOptionPane for asking from user:
public void start() throws CreateDocumentConfigurationException {
// Custom button text
Object[] options = {"Yes, please", "Use default instead"};
int n = JOptionPane.showOptionDialog(null,
"Would you like to enter DB credentials?",
"DB Question", JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE, null, options, options[1]);
estimateUserInput(n); // process result here. 0 - for entering new one, 1 - for using default
}
You can store the database login information in configuration file.
For Desktop Application,
.properties file can be use
For Web Based Application,
Store the password in context.xml of your Apache Tomcat Server.

Java: How to make an object written to a file unreadable to humans?

I have a class that stores a password (I'm going to be adding more things than just the password) called Data:
import java.io.Serializable;
public class Data implements Serializable{
public String password = "";
}
As a test I ran these two:
private static File datafile = new File("data.src");
public static void checkDatafile() {
try {
Data data = new Data();
data.password = "Newwww";
if (!datafile.exists()) {
datafile.createNewFile();
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream(datafile));
oos.writeObject(data);
oos.flush();
oos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static Data loadData(Data data) {
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(datafile));
data = (Data) ois.readObject();
ois.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return data;
}
It writes and reads perfectly but when I open the data.src in notepad it's somewhat readable by humans and the password is not secure, this is the output of data.src:
ャ・ sr data.Data克ラ淕6J・ L passwordt Ljava/lang/String;xpt Newwww
The password is easily seen and is not safe, is there a way to encrypt/encode the object when writing to a file so that it's unreadable by humans?
Also, I'd rather stick to the standard Java libs then to download and use others.
It depends on what you mean by "unreadable". If your goal is to prevent a malicious person from extracting the password, even if they have the necessary permissions to run your program, you'll be hard-pressed to do so. After all, if a program can decrypt the password, a person with the same permissions can too. Even without appropriate permissions, a malicious user could potentially inspect raw bytes in memory and extract the password if they have access to the machine.
On the other hand, if you can reasonably trust the user, but just want to avoid having them accidentally see the password in clear-text, any number of simple schemes will work; even just serializing the string as its hex codepoints would be good enough.
If you must store the password itself, i.e. you're accessing a third-party service that requires a password, you essentially have to lock down the machine and limit its access to people you absolutely trust. There's no way around that. There are a number of resources describing encrypting passwords, but they all rely on you being able to lock out users from some part of the system, generally either the encryption key or the cypher-text.
However you likely do not need to, and should not, actually be storing the password at all. The standard way to authenticate a user is to never store their password, and instead store a one-way hash of the password. This is (theoretically) impossible to decipher back into the original password, but by hashing the password the user enters when they log in and comparing it to the hash you have on file you can verify their identity without ever knowing what their password is.
Edit: One more thing about systems which need to store actual passwords. In addition to locking down the machine, you need to create a robust audit trail that records all attempts to access the passwords. Every interaction with that machine and its data should be logged and tracked so that, in the event something goes wrong, you can inspect your audit history and understand the scope of the problem. If you don't have an audit trail you'll have to assume your system is entirely compromised, because you'll have no evidence to the contrary.
not via ObjectOutputStream. you'll have to use a encryption library and either encrypt the complete file, or the password.
You can have the Data class implement the writeObject/readObject methods to encrypt/decrypt the passwords as you read and write the object.
private void writeObject(ObjectOutputStream os) throws IOException{
password = encrypt(password);
os.defaultWriteObject();
}
private void readObject(ObjectOutputStream os) throws IOException{
os.defaultReadObject();
password = decrypt(password);
}
Where encrypt/decrypt define the ecryption/decryption algorithm you wish to use. This being said and as noted in a comment by Gregor Raýman, you might consider just hashing the passwords rather than storing them.
You can try encoding/decoding your content. You can use MD5 hash-functioning. There are pre-written functions and its usage is pretty simple.
The following link can help you understand how to use it in you code.
http://www.asjava.com/core-java/java-md5-example/

Creating an email in Java

I would like to "create" an email using Java.
Here's what I mean:
Based on information I already have, I would like to make an email message open in Microsoft Outlook with the fields To, CC, Subject, Message Body, and attachments already populated (all now stored as strings, the directories for attachments are stored as strings as well).
The message needs to open in Outlook for the user to verify the contents and give the opportunity for adding more CC, slight adjustments to subject and message body.
From what I gather, it seems that the "best" way of achieving this is first creating a file on disk that Outlook can read, which contains my message, then opening it with outlook using something similar to the code below.
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("OUTLOOK Directory + CMD switches for opening files");
Ideally, I would like to use a simple framework for simply creating such a file using the strings I already have for the different fields (or achieving the same thing through a a non-simple framework).
If there's no "good" way of achieving the above, I'd settle for a method of just attaching my attachment file to a given Outlook template (.oft) file.
(3. I'll resort to my current solution of simply having the template open in Outlook, the attachment in Explorer, and prompt the user to drag the file into Outlook.)
I've looked at HSMF in Apache POI (I'm Apache POI for other parts of my program), but it appears to be rather experimental at this point, and I've been unable to find much documentation for it.
Does anyone have any suggestions on where to look?
Use the Desktop API with the URI constructor that will quote legal characters. This example code will open your default mail client with the headers populated.
public static void main(String[] args) throws Exception {
URI msg = new URI("mailto", "you#foo.com&cc=team#bar.com&subject=How to create email in Java?body=Use JavaMail.", (String) null);
Desktop.getDesktop().mail(msg);
}
The only limitation is that there is an upper limit to the length of the URI that the O/S can handle. On windows, the 'start' command also understands the syntax which is explained in RFC 2368.

Java program to add users into a database

I'm working on a simple java program that takes in user input, then parses the data and uploads it into a sql database to store online.
In my JDBC code I have the following: (Small example)
public class JDBCExample {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/";
// Database credentials
static final String USER = "username";
static final String PASS = "password";
I am wondering how safe it is to have my username and password just openly available in plain text in my programming code after I convert it to a jar file. Is it easy to reverse engineer an application like this and reveal the code?
Incredibly easy, yes. javap -c JDBCExample.class will do it in a heartbeat.
Generally the way this is done is by separating the client-side app, which you distribute publicly, from a server-side app that runs on a trusted server. The client app you distribute doesn't access the database directly; instead, it talks to the server program, which publishes an API (often a RESTful API over HTTP) through which the client can make requests. That trusted server-side program is what talks to the database directly.
And even then, it's best practice to not hard-code your credentials into the server-side code. Instead, have the service read those credentials from a file which you keep separate from the code base (for instance, don't check that file into your source control).
You could save the username and password in a separate property file so that you could change it anytime without having to recompile the codes.
On your question, whatever your code can read in your codes/files, most likely, users can also. Please see this as reference.
I use ciphering and deciphering in my code.
use javax.crypto class to encrypt your password and inside your class use deciphering to decipher and send the password.
This works only if you place class file for deciphering rather than .java file.
example for ciphering link.

How to programatically open a PDF with a User password

This is related to my other question... hope this one has a solution.
The requirement is to display a password-protected PDF in the browser but to pass the User password programatically. I create a PDF using Jasper and set the user password as follows:
exporter.setParameter(JRPdfExporterParameter.USER_PASSWORD, userPassword);
As soon as the PDF is created, it has to be displayed in the screen. While displaying in the browser, the user should not be prompted to key in the password ans hence the password should be supplied by the application However, if the user downloads the PDF and then tries to open it, he should be prompted to enter the password.
[Edit]: I am looking for an approach that does NOT involve licensed tools
You can open a password protected PDF using the PDF.JS library.
PDFJS.getDocument({ url: pdf_url, password: pdf_password }).then(function(pdf_doc) {
// success
}).catch(function(error) {
// incorrect password
// error is an object having 3 properties : name, message & code
});
I've written a blog post on it, also containing a demo. This is the link : http://usefulangle.com/post/22/pdfjs-tutorial-2-viewing-a-password-protected-pdf
I'm not sure whether something of this is possible. On the browser the pdf is opened by a Plugin - usually Adobe Reader plug-in. There are also other makes apart from Adobe Reader. Chrome has it own plugin.
On the browser when it detects any PDF file - the rendering plugin takes over - and this is browser specific. You hardly have any control.
Easy alternative is to show the same content in a web page - probably a modal window if the content is sensitive and give a link to download the password protected pdf file
my 2c
You could checkout PDF.js, an open source client based PDF renderer that also has support for encrypted PDFs.
http://mozilla.github.com/pdf.js/
This means you will have to put your password somewhere in the javascript though, so you will have to disguise it, but it should do the trick :)
You can use pdf.js of mozilla to render password protected PDF. The below url that will prompt for password, until the correct password is given. The password for the pdf is "test".
http://learnnewhere.unaux.com/pdfViewer/passwordviewer.html
Here is the sample code for prompting password
pdfJs.onPassword = function (updatePassword, reason) {
if (reason === 1) { // need a password
var new_password= prompt('Please enter a password:');
updatePassword(new_password);
} else { // Invalid password
var new_password= prompt('Invalid! Please enter a password:');
updatePassword(new_password);
}
};
If you want to close the password prompt on unsuccessful password attempts you can remove the else part(// Invalid password).
You could get the complete code from here https://github.com/learnnewhere/simpleChatApp/tree/master/pdfViewer

Categories