Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
305 views
in Technique[技术] by (71.8m points)

java - 为什么密码比字符串更喜欢char []?(Why is char[] preferred over String for passwords?)

In Swing, the password field has a getPassword() (returns char[] ) method instead of the usual getText() (returns String ) method.

(在Swing中,密码字段具有getPassword() (返回char[] )方法,而不是通常的getText() (返回String )方法。)

Similarly, I have come across a suggestion not to use String to handle passwords.

(同样,我遇到了不使用String处理密码的建议。)

Why does String pose a threat to security when it comes to passwords?

(为什么在密码方面String会对安全构成威胁?)

It feels inconvenient to use char[] .

(使用char[]感觉很不方便。)

  ask by Ahamed translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Strings are immutable .

(字符串是不可变的 。)

That means once you've created the String , if another process can dump memory, there's no way (aside from reflection ) you can get rid of the data before garbage collection kicks in.

(这意味着一旦创建了String ,如果另一个进程可以转储内存,就无法(除了Reflection )在垃圾回收开始之前摆脱数据。)

With an array, you can explicitly wipe the data after you're done with it.

(使用数组,您可以在使用完数据后显式擦除数据。)

You can overwrite the array with anything you like, and the password won't be present anywhere in the system, even before garbage collection.

(您可以用任何您喜欢的东西覆盖阵列,并且即使在垃圾回收之前,密码也不会出现在系统中的任何位置。)

So yes, this is a security concern - but even using char[] only reduces the window of opportunity for an attacker, and it's only for this specific type of attack.

(因此,是的,这一个安全性问题-但是即使使用char[]只会减少攻击者的机会之窗,并且仅针对这种特定类型的攻击。)

As noted in the comments, it's possible that arrays being moved by the garbage collector will leave stray copies of the data in memory.

(如评论中所述,垃圾回收器移动的数组可能会将数据的零散副本保留在内存中。)

I believe this is implementation-specific - the garbage collector may clear all memory as it goes, to avoid this sort of thing.

(我相信这是特定于实现的-垃圾收集器可能会清除所有内存,以免发生这种情况。)

Even if it does, there's still the time during which the char[] contains the actual characters as an attack window.

(即使这样做,在char[]仍然包含实际字符作为攻击窗口的时间内仍然存在。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...