hi all
password masking in java seems to be very easy in awt/swings....what abt command line
well i am sending you an old and concentional solution to it.......enjoy :)
_____________________________________________
import java.util.*;
import java.io.*;
class MaskingThread extends Thread
{
private volatile boolean stop;
private char echochar='*';
public MaskingThread(String prompt)
{
System.out.print(prompt);
}
public void run()
{
int priority = Thread.currentThread().getPriority();
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
try{
stop = true;
while(stop)
{
System.out.print("\010" + echochar);
try{
Thread.currentThread().sleep(1);
}catch(InterruptedException e)
{
Thread.currentThread().interrupt();
return;
}
}
}finally
{
Thread.currentThread().setPriority(priority);
}
}
public void stopMasking()
{
this.stop = false;
}
}
class PasswordField {
public static final char[] getPassword(InputStream in, String prompt) throws IOException {
MaskingThread maskingthread = new MaskingThread(prompt);
Thread thread = new Thread(maskingthread);
thread.start();
char[] lineBuffer;
char[] buf;
int i;
buf = lineBuffer = new char[128];
int room = buf.length;
int offset = 0;
int c;
loop: while (true) {
switch (c = in.read()) {
case -1:
case '\n':
break loop;
case '\r':
int c2 = in.read();
if ((c2 != '\n') && (c2 != -1)) {
if (!(in instanceof PushbackInputStream)) {
in = new PushbackInputStream(in);
}
((PushbackInputStream)in).unread(c2);
} else {
break loop;
}
default:
if (--room < 0) {
buf = new char[offset + 128];
room = buf.length - offset - 1;
System.arraycopy(lineBuffer, 0, buf, 0, offset);
Arrays.fill(lineBuffer, ' ');
lineBuffer = buf;
}
buf[offset++] = (char) c;
break;
}
}
maskingthread.stopMasking();
if (offset == 0) {
return null;
}
char[] ret = new char[offset];
System.arraycopy(buf, 0, ret, 0, offset);
Arrays.fill(buf, ' ');
return ret;
}
}
public class PasswordApp {
public static void main(String argv[]) {
char password[] = null;
try {
password = PasswordField.getPassword(System.in, "Enter your password: ");
} catch(IOException ioe) {
ioe.printStackTrace();
}
if(password == null ) {
System.out.println("No password entered");
} else {
System.out.println("The password entered is: "+String.valueOf(password));
}
}
}