繁体   English   中英

屏蔽从控制台输入的密码:Java

[英]Masking password input from the console : Java

如何从控制台输入屏蔽密码? 我正在使用 Java 6。

我试过使用console.readPassword() ,但它不起作用。 一个完整的例子实际上可能对我有帮助。

这是我的代码:

import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.io.InputStreamReader;

public class Test 
{   
    public static void main(String[] args) 
    {   
        Console console = System.console();

        console.printf("Please enter your username: ");
        String username = console.readLine();
        console.printf(username + "\n");

        console.printf("Please enter your password: ");
        char[] passwordChars = console.readPassword();
        String passwordString = new String(passwordChars);

        console.printf(passwordString + "\n");
    }
}

我收到一个 NullPointerException ......

一个完整的例子?。 运行此代码:(注意:此示例最好在控制台中运行,而不是在 IDE 中运行,因为在这种情况下 System.console() 方法可能返回 null。)

import java.io.Console;
public class Main {

    public void passwordExample() {        
        Console console = System.console();
        if (console == null) {
            System.out.println("Couldn't get Console instance");
            System.exit(0);
        }

        console.printf("Testing password%n");
        char[] passwordArray = console.readPassword("Enter your secret password: ");
        console.printf("Password entered was: %s%n", new String(passwordArray));

    }

    public static void main(String[] args) {
        new Main().passwordExample();
    }
}

您将使用Console

char[] password = console.readPassword("Enter password");  
Arrays.fill(password, ' ');

通过执行 readPassword 回显被禁用。 此外,在验证密码后,最好覆盖数组中的任何值。

如果您从 ide 运行它会失败,请参阅此解释以获取完整答案:已解释

Console console = System.console();
String username = console.readLine("Username: ");
char[] password = console.readPassword("Password: ");

如果您正在处理 Java 字符数组(例如您从控制台读取的密码字符),您可以使用以下 Ruby 代码将其转换为 JRuby 字符串:

# GIST: "pw_from_console.rb" under "https://gist.github.com/drhuffman12"

jconsole = Java::java.lang.System.console()
password = jconsole.readPassword()
ruby_string = ''
password.to_a.each {|c| ruby_string << c.chr}

# .. do something with 'password' variable ..    
puts "password_chars: #{password_chars.inspect}"
puts "password_string: #{password_string}"

另见“ https://stackoverflow.com/a/27628738/4390019 ”和“ https://stackoverflow.com/a/27628756/4390019

如果我们从控制台运行,给定的代码绝对可以正常工作。 并且类中没有包名

你必须确定你的“.class”文件在哪里。 因为,如果为类指定了包名,则必须确保将“.class”文件保存在指定的文件夹中。 例如,我的包名称是 "src.main.code" ,我必须创建一个代码文件夹,在主文件夹内,在 src 文件夹内,并将 Test.class 放在代码文件夹中。 那么它将完美地工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM