为什么 JPasswordField.getPassword() 创建一个包含密码的字符串? [英] Why does JPasswordField.getPassword() create a String with the password in it?

查看:19
本文介绍了为什么 JPasswordField.getPassword() 创建一个包含密码的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Swing 的 JPasswordFieldgetPassword() 方法返回一个字符数组.我对此的理解是数组可以在使用后立即归零,这样您就不会在内存中长时间挂起敏感的东西.检索密码的旧方法是使用 getText(),它返回一个 String 对象,但它已被弃用.

Swing's JPasswordField has the getPassword() method that returns a char array. My understanding of this is that the array can be zeroed immediately after use so that you do not have sensitive things hanging around in memory for long. The old way to retrieve the password was to use getText(), which returns a String object, but it has been deprecated.

所以,我的问题是为什么 Java 在检索过程中使用 getPassword() 实际使用它???更清楚地说,我正在调试我的测试应用程序以进行其他操作**,我按照调用进行操作...JPasswordField 中的 getText() 被调用,当然, 一个很好的带有我密码的 String 对象已经创建,现在挂在内存中.

So, my question is why it is actually being used by Java during the retrieval process using getPassword()??? To be clearer, I was debugging my test app for something else**, I followed the calls and bang... getText() in JPasswordField was called and, of course, a nice String object with my password has been created and now is hanging around the memory.

自己试试:

public class PasswordTest() {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPasswordField passField = new JPasswordField();
        pass.addActionListener(new ActionListener() {
            public ActionPerformed(ActionEvent evt) {
                char[] p = passField.getPassword(); // put breakpoint
                // do something with the array
            }
        });
        frame.add(passField);
        frame.setVisible(true);
        frame.pack();
    }
}

后续问题:getText() 的这种隐藏"使用是否有任何危险?当然,如果您的密码破坏了系统,那么专门的攻击者将获得您的密码,我说的是一个不那么专门的攻击者 ;)

Follow up question: is this 'hidden' use of getText() dangerous in any way? Of course a dedicated attacker WILL get your password if it has compromised the system, I am talking about a less dedicated one ;)

**我在寻找一种在不使用 String 对象的情况下在 Swing 组件上实际显示一些敏感数据的方法时遇到了这个问题.显然没有办法做到这一点,除非我愿意重写部分(全部?)Swing API..不会发生.

**I came across this while I was looking for a way to actually display some sensitive data on a Swing component without using a String object. Apparently there is no way to do it unless I am willing to rewrite part (all?) of the Swing API.. not gonna happen.

推荐答案

这对我有用,可以帮助您构建字符串化密码:

This works for me and helps you to build a Stringified password:

String passText = new String(passField.getPassword());

这篇关于为什么 JPasswordField.getPassword() 创建一个包含密码的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆