String to asterisk, masking password - java

I'm creating this simple login code for an ATM machine.
You enter username and password and you logs in, that works just great. Since I'm not connecting to a database or an external text file and I've just got 1 user, it's just written plainly in the Java code. But when you enter the password "p4ss" I want it to be masked, so instead of seing it on the screen while typing you should see "* * * *" or " " just blank (Like when you enter pass on Linux).
Currently my code looks like this:
String user;
String pass;
System.out.print("User: ");
user = Keyboard.readString();
System.out.print("Pass: ");
pass = Keyboard.readString();
if ((user.equals("Admin")) && (pass.equals("p4ss")))
{
menu();
}
else
{
out.println("Wrong username or password.");
}
Would appreciate any help I could get.

Michael, have a look at the description on Sun's website:
https://web.archive.org/web/20120214061606/http://java.sun.com/developer/technicalArticles/Security/pwordmask
Or, if you're using Java 5 or newer, you can use this:
How to mask a password in Java 5?

I assume this is a simulated ATM...
Dev has pointed out that password masking on the console is supported out of the box, so you can use that. However for anything but the most trivial of IO you'd be better off using Swing or a "curses-like" library:
http://www.pitman.co.za/projects/charva/index.html
http://sourceforge.net/projects/javacurses/

If you have JavaSE 6 or newer you can use Console.readPassword()

There's a special method Console.readPassword() for doing this, introduced in Java 6. You obviously couldn't run code like this on a real ATM, though! Swing has JPasswordField which lets you do this kind of masking in a GUI, and one could imagine a Swing-based ATM window.

Related

Not able to run password masking using char[] PASSWORD =cons.readPassword in gitbash terminal

hi im trying to run this programme for password masking using char[] PASSWORD =cons.readPassword()
but it is giving me
Exception in thread "main" java.lang.NullPointerException
at automateCFOSetup.App.main(App.java:32)
when i ran the programme in git bash terminal. But when i ran it on Windows cmd it was running fine...any reason why this occurred as i am only aware of issue of getting this null pointer when running within IDE
this is my code
Scanner scan = new Scanner(System.in);
Console cons = System.console();
log.info("ENTER YOUR ID :");
String SOEID = scan.nextLine();
char[] PASSWORD =cons.readPassword("ENTER YOUR PASSWORD :");
scan.close();
Any help with this?
A console is not guaranteed to support this feature. Given that you're getting the exception, the particular console you use here (your IDE and I'm not surprised - those 'consoles' for some reason don't usually support this), does not support password input.
There is no solution to this. But there are workarounds:
You can catch the exception and tell the user: Tough luck - no can do.
You can catch it, and decide, eh, whatever, ask with the usual tricks (scanner.nextLine()). Perhaps warn the user that their pw will be echoed. Surely, 'run it in the IDE' isn't how you intend to deploy your software, so this isn't all that much of a security issue (if this app is used on private developer's laptops, generally those already contain so much information, such as the code itself, git keys, etc - if that device is compromised, you have much bigger problems already).
Don't ask on the console at all, instead, get that password from elsewhere, such as a file, using PKI. Passwords are so 1990, you know.

Masking password in Java CLI application

I've made this little ATM application in Java (CLI) and in the beginning I want to have "Code: " and then the user should enter it, and in my Java application it should say something like String(or int?) code = 1234; and if that works then proceed, if not wrong, try again, if faulty 3 times, stop app.
How would something like that look? I've been googling for hours now after masked passwords and tried different types of code without any luck. I just want something simple that converts the string to asterisk.
Currently my password masking looks like this:
java.io.Console cons;
char[] passwd;
if ((cons = System.console()) != null && (passwd = cons.readPassword("[%s]", "Code:")) != null)
However I'm not able (don't know) how to set a password in the code.
Use the readPassword method of class java.io.Console.
The API documentation of class Console has an example that shows how to read a password from the console window without echoing it in plaintext.
edit
Michael, this code is to let a user enter a keyword in the console window without displaying it. After the user has done that, the password is stored in the variable passwd. It seems that what you really want is something completely different: you have some other program that asks for a password, and you want your program to enter that password automatically.
If that is indeed what you want to do, then you don't need to use class Console. You could try using class java.awt.Robot to enter keystrokes in another application (but I'm not sure that it would work with a console window - try it out).
This site has an example of pretty much exactly what you are trying to do: http://download.oracle.com/javase/tutorial/essential/io/cl.html
To be thorough, here are two more links to similar tutorials.
Do they answer your question?
Based on your comments, perhaps you do not understand Java syntax exactly.
You cannot write:
char["mypassword"] passwd;
I think you mean instead:
String str = "mypassword";
char[] passwd = str.toCharArray();
Update
Try this code:
Console c = System.console();
if (c == null) {
System.err.println("No console.");
System.exit(1);
}
char [] passwd = c.readPassword("Enter your password: ");
c.println("Password is:");
c.println(new String(passwd));
Take a look at this sun Java article... it highlights a number of different ways to do it.
Specifically it shows how to use AWT's TextField class with the setEchoChar() method, as well as a method that runs a separate thread to remove and replace typed characters in console applications.

J2ME converter program not accepting user's input

I am having problems with my converter program not accepting the value the user inputs. Everything seems so right but the result is always as if the user entered nothing. If anyone can just point me in the right direction I would greatly appreciate it!
my project consists of 2 files (1 midlet and 1 class).
code was too long to post on this forum so I uploaded the zip.
Edit hosted here now should be cleaner: removed
I can't really narrow it down to a small piece of code because it could be any number of things which I have already tried. I know its asking quite a bit but the code isn't insanely long. I'd be extremely grateful if anyone could take a look.
edit 2: the file seems to be trying to download an image... here is the code in another forum i posted in but got no answers.: http://www.codingforums.com/showthread.php?p=1024059#post1024059
edit 3: here is where I think the problem lies in the code:` public double customForm (String fName)
{
ui_form = new Form(fName);
ui_form.addCommand(Convert);
ui_form.addCommand(Back);
display.setCurrent(ui_form);
num = new TextField("Enter the number of units you would like to convert", "", MAX_CHARS, TextField.ANY);
ui_form.append(num);
ui_form.setCommandListener(this);
/***********************/
/* THIS IS NOT WORKING*/
// str = num.getString();
str = "The number is: " + num.getString();
try
{
numUnits = Double.parseDouble(str);
}
catch (NumberFormatException nfe)
{
}
finally
{
return numUnits;
}
//return str;
}
`
but you will probably need to look at the rest of the code to see where the problem lies. this is just the root i think
You cannot read the text field right after it has been added to a form. It looks like you assumed the num.getString() method to block until there's user input - this is not the case. User input is provided asynchronously, i.e. you should read the text field's content in response to a user command, somewhere in the commandAction() method (in your case when the Convert command has been issued by the user).
Handling user events asynchronously is a core pattern in GUI development. In this regard I recommend to read some example code for command handling in JavaME, for instance this or this.

writing a simple ofx4j program

I have been using http://ofx4j.sourceforge.net/userguide.html as a guide to write a small java program to download my bank account statement from wells fargo. I keep getting an error saying Invalid Signon. I have the right url. I am using the same password and username as I use to logon to their webpage. Does anyone have any other simple samples that I could look at or use?
I had the same problem.
I was trying to log into Chase Bank but I was getting an Invalid Signon.
The problem that I had is that I was using the wrong data, oxf4j might have obsolete data
stored for the banks it has stored.
Go to gnucash to get the right updated setting for your bank:
http://wiki.gnucash.org/wiki/OFX_Direct_Connect_Bank_Settings.
Then you need to create a new BaseFinancialInstitutionData object
like this (this example is for chase credit card):
BaseFinancialInstitutionData data = new BaseFinancialInstitutionData();
data.setFinancialInstitutionId("10898");
data.setOFXURL(new URL("https://ofx.chase.com"));
data.setOrganization("B1");
FinancialInstitutionService service = new FinancialInstitutionServiceImpl();
FinancialInstitution fi = service.getFinancialInstitution(data);

Automating HP Quality Center with Python or Java

We have a project that uses HP Quality Center and one of the regular issues we face is people not updating comments on the defect.
So I was thinkingif we could come up with a small script or tool that could be used to periodically throw up a reminder and force the user to update the comments.
I came across the Open Test Architecture API and was wondering if there are any good Python or java examples for the same that I could see.
Thanks
Hari
Example of using Python (win32com) to connect to HP Quality Center via OTA
HP Quality Center exposes a com based API called OTA.
Documentation on this is downloadable from an QC server
(OTA_API_Reference.chm) (Weirdly it is very hard to find online)
The documentation uses VBScript (The officially supported internal language for QC)
and you will need to mentally translate to Python. THis is usually very simple, but
a couple of gotchas exist.
You will need to install on your machine the Quality Center local code, this is on your windows PC
if you have been able to get to QC through the web interface.
You will also need to know the URL of the server and you username and password and the domain
of the QC project you are working on.
from win32com.client import Dispatch
conn = get_QCConnection()
for bug in get_bugs(qcConn):
print bug.Title
put_QCConnection(conn)
#below code needs to be in seperate module or at least above the fold but here
# for clarity
def get_QCConnection():
'''Get the hardcoded connection to the server and domain.
Can be made a "real" engine if you try hard.
Use makepy utility to determine if the version number has changed (TDApiOle80)
but this works to current version'''
QCConnection = Dispatch("TDApiOle80.TDConnection")
url = "http://qc.example.com/qcbin"
QCConnection.InitConnectionEx(url)
QCConnection.login("USER", "PASS")
QCConnection.Connect("google_projects", "Google_Chrome")
return QCConnection
def put_QCConnection(qcConn):
#If one person logged in to QC changes *anything* on a bug,
# they hold a global lock on writing to that bug till
# thier session times out, so really really remember to logout
# its painful to wait for your own session to time out
qcConn.Logout()
def get_bugs(qcConn):
'''just following boiler plate from vbscript
PS the SetFilter is not in QTA API, it uses Filter.
But due to the workarounds in
the very brilliant pythoncom code it supplies a virtual wrapper class
called SetFilter - this is one of those gotchas '''
BugFactory = qcConn.BugFactory
BugFilter = BugFactory.Filter
BugFilter.SetFilter(u"Status", "New")
#NB - a lot of fields in QC are malleable - and vary from site to site.
#COntact your admins for a real list of fields you can adjust
buglist = BugFilter.NewList()
return buglist
This is not a bad basis for going forward, however I create a dummy class for defects and run something like:
dfcts = [defect(b) for b in buglist]
Then I can put worker code into defect class and keep things neater.
One thing you want to do is keep access to the raw qc bug internal to the python wrapper class.
Information for others who may view this thread.
To start all this You will need install pywin32, like from here http://sourceforge.net/projects/pywin32/files/pywin32/Build216/
First of all You will need to import pywin32
'''#author: www.qcintegration.com #mailto:contact#qcintegration.com'''
import pywintypes
import win32com.client as w32c
from win32com.client import gencache, DispatchWithEvents, constants
Then as second operation I include here action on login to server
def connect_server(qc, server):
'''Connect to QC server
input = str(http adress)
output = bool(connected) TRUE/FALSE '''
try:
qc.InitConnectionEx(server);
except:
text = "Unable connect to Quality Center database: '%s'"%(server);
return qc.Connected;
def connect_login(qc, username, password):
'''Login to QC server
input = str(UserName), str(Password)
output = bool(Logged) TRUE/FALSE '''
try:
qc.Login(username, password);
except pywintypes.com_error, err:
text = unicode(err[2][2]);
return qc.LoggedIn;
def connect_project(qc, domainname, projectname):
'''Connect to Project in QC server
input = str(DomainName), str(ProjectName)
output = bool(ProjectConnected) TRUE/FALSE '''
try:
qc.Connect(domainname, projectname)
except pywintypes.com_error, err:
text = "Repository of project '%s' in domain '%s' doesn't exist or is not accessible. Please contact your Site Administrator"%(projectname, domainname);
return qc.ProjectConnected;
Second of all method which will include OTAapi dll file
def qc_instance():
'''Create QualityServer instance under variable qc
input = None
output = bool(True/False)'''
qc= None;
try:
qc = w32c.Dispatch("TDApiole80.TDConnection");
text = "DLL QualityCenter file correctly Dispatched"
return True, qc;
except:
return False, qc;
Then main method to connect to QCserver
def qcConnect(server, username, password, domainname, projectname):
print("Getting QC running files");
status, qc = qc_instance();
if status:
print("Connecting to QC server");
if connect_server(qc, server):
##connected to server
print("Checking username and password");
if connect_login(qc, username, password):
print("Connecting to QC domain and project");
if connect_project(qc, domainname, projectname):
text = "Connected"
connected = True;
return connected, text;
else:
text = "Not connected to Project in QC server.\nPlease, correct DomainName and/or ProjectName";
connected = False;
return connected, text;
else:
text = "Not logged to QC server.\nPlease, correct UserName and/or Password";
connected = False;
return connected, text;
else:
text = "Not connected to QC server.\nPlease, correct server http address";
connected = False;
return connected, text;
else:
connected = False;
text = "Unable to find QualityCenter installation files.\nPlease connect first to QualityCenter by web page to install needed files"
return connected, text;
And at the end how to execute all of those methods in one place with example of use
if __name__ == "__main__":
server= r"http://qualitycenterServer:8080/qcbin"
username= "alex_qc"
password= ""
domainname= "DEFAULT"
projectname= "QualityCenter_Demo"
connection_status, text = qcConnect(server, username, password, domainname, projectname);
print "connection_status:", connection_status
In case of any more question mailto: contact#qcintegration.com
or directly to web side: http://www.qcintegration.com
I'm not sure there are any good samples for Java, because OTA can't be consumed by Java directly, it needs a Java to COM bridnge like JIntegra.
About Python, well you can use Python COM api's. And then any OTA example will do. You got plenty in QC documentation of OTA.
But I think the real question here is, why would you want to do it in Python or Java. Why not write what you need directly in QC using it's Workflow feature. Which will allow you to write your logic in VBScript, and have it invoked inside QC UI on user actions. For instance you can bind to the Post event of a Defect / Bug and check if there is a comment and if there is not prompt the user directly with a message.
There is a REST API to HPQC (ALM11 and newer) if you want to access it from Linux without running a Windows COM component.
Here is an example that pulls in a "requirement" record (# 1202) after authenticating.
import requests
session = requests.session()
user='hpqc'
password='xxxxx'
r = session.get("http://hpqc-server:8080/qcbin/authentication-point/authenticate",auth=(user,password))
r = session.get("http://hpqc-server:8080/qcbin/rest/domains/Foo/projects/Bar/requirements/1202")
print(r.text)
The parsing of r.text from XML is left as an exercise.
Though you have asked for a Python or Java based solution, sharing the following VBA code that you can use insde HPQC/ALM's script editor (Defects module script) to accomplish the goal.
Function Bug_FieldCanChange(FieldName, NewValue)
On Error Resume Next
if not changed then
strCommentBeforeUpdate = Bug_Fields("BG_DEV_COMMENTS").Value
end if
If FieldName = "BG_DEV_COMMENTS" and blnAddCommentClicked = False Then
Msgbox "Cannot update the comments." & Chr(13)& "Changes made will not be saved."&Chr(13)& "Please use 'Add comment' button to insert new comment." &Chr(13)& " Or click Cancel without saving."
blnUpdateCommentError = true
blnAddCommentClicked = False
changed = true
End If
Bug_FieldCanChange = DefaultRes
End Function
You can use a new Test and select type (VPXP_API) which allow script to run. The good thing there is that you'd have the function definition ready to be dragged from within QC instead of having to heavily rely on doc.
I've done an implementation in Python running some script from within QC still using its API but via a QC test which is handy to retrieve directly the result (Output) etc.. going through some shell command which can then call any script on any server etc...

Categories