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

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

问题描述

Swing的 JPasswordField 包含 getPassword() 返回char数组的方法。我对此的理解是,数组可以在使用后立即归零,这样你就不会在内存中长时间处于敏感状态。检索密码的旧方法是使用 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()?为了更清楚,我正在调试我的测试应用程序的其他东西**,我跟着电话和爆炸... getText() JPasswordField 被调用了,当然,我的密码已经创建了一个很好的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()会创建一个包含密码的String?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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