为什么char []比字符串更适合密码? [英] Why is char[] preferred over String for passwords?

查看:132
本文介绍了为什么char []比字符串更适合密码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Swing中,密码字段有一个 getPassword()(返回 char [] )方法而不是通常的 getText()(返回 String )方法。同样,我遇到了一个建议,不要使用 String 来处理密码。



为什么字符串在密码方面对安全构成威胁?
使用 char [] 感觉不方便。

解决方案

字符串是不可变的。这意味着一旦你创建了 String ,如果另一个进程可以转储内存,那就没办法了(除了反射)你可以在垃圾收集开始。



使用数组,您可以在完成数据后明确擦除数据。你可以用你喜欢的任何东西覆盖数组,即使在垃圾收集之前,密码也不会出现在系统的任何地方。



所以是的,这个 是一个安全问题 - 但即使使用 char [] 也只会减少攻击者的机会窗口,而且只针对这种特定类型的攻击。<​​/ p>

如评论中所述,垃圾收集器移动的数组可能会将数据的杂散副本留在内存中。我相信这是特定于实现的 - 垃圾收集器可以清除所有内存,以避免这种情况。即使它确实存在,仍然有时间 char [] 包含实际字符作为攻击窗口。


In Swing, the password field has a getPassword() (returns char[]) method instead of the usual getText() (returns String) method. Similarly, I have come across a suggestion not to use String to handle passwords.

Why does String pose a threat to security when it comes to passwords? It feels inconvenient to use char[].

解决方案

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.

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.

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 []比字符串更适合密码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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