问题描述
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()
的检索过程中实际使用它?更清楚地说,我正在调试我的测试应用程序**,我跟着调用并砰的一声...... JPasswordField
中的 getText()
被调用了,当然,一个带有我的密码的漂亮字符串对象已经被创建,现在挂在内存中.
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 ;)
**我在寻找一种在 Swing 组件上实际显示一些敏感数据而不使用 String
对象的方法时遇到了这个问题.除非我愿意重写 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() 会创建一个包含密码的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!