在Swing中,密码字段有一个getPassword()(returns char[])方法,而不是通常的getText()(return String)方法。同样,我也遇到了一个建议,不要使用String来处理密码。
为什么字符串对密码安全构成威胁?使用char[]感觉不方便。
在Swing中,密码字段有一个getPassword()(returns char[])方法,而不是通常的getText()(return String)方法。同样,我也遇到了一个建议,不要使用String来处理密码。
为什么字符串对密码安全构成威胁?使用char[]感觉不方便。
当前回答
字符数组(char[])可以在使用后通过将每个字符设置为零而不设置为字符串来清除。如果有人能够以某种方式看到内存映像,那么如果使用字符串,他们可以看到纯文本的密码,但是如果使用char[],则在用0清除数据后,密码是安全的。
其他回答
虽然这里的其他建议似乎有效,但还有一个很好的理由。使用纯字符串时,意外将密码打印到日志、监视器或其他不安全的地方的可能性要大得多。char[]不那么脆弱。
考虑一下:
public static void main(String[] args) {
Object pw = "Password";
System.out.println("String: " + pw);
pw = "Password".toCharArray();
System.out.println("Array: " + pw);
}
打印:
String: Password
Array: [C@5829428e
大小写字符串:
String password = "ill stay in StringPool after Death !!!";
// some long code goes
// ...Now I want to remove traces of password
password = null;
password = "";
// above attempts wil change value of password
// but the actual password can be traced from String pool through memory dump, if not garbage collected
案例CHAR阵列:
char[] passArray = {'p','a','s','s','w','o','r','d'};
// some long code goes
// ...Now I want to remove traces of password
for (int i=0; i<passArray.length;i++){
passArray[i] = 'x';
}
// Now you ACTUALLY DESTROYED traces of password form memory
有些人认为,一旦您不再需要密码,就必须覆盖用于存储密码的内存。这缩短了攻击者从系统读取密码的时间窗口,并完全忽略了这样一个事实,即攻击者已经需要足够的访问权限来劫持JVM内存。具有如此多访问权限的攻击者可以捕获您的关键事件,使其完全无用(AFAIK,所以如果我错了,请纠正我)。
使现代化
感谢这些评论,我不得不更新我的答案。显然,在两种情况下,这可以增加(非常)轻微的安全改进,因为它可以减少密码在硬盘上的时间。但我仍然认为这对大多数用例来说都是过度的。
您的目标系统可能配置不正确,或者您必须假设它是错误的,并且您必须对核心转储(如果系统不是由管理员管理的,则可能是有效的)心存疑虑。您的软件必须过于偏执,以防止攻击者使用TrueCrypt(已停产)、VeraCrypt或CipherShed等工具访问硬件时发生数据泄漏。
如果可能,禁用内核转储和交换文件可以解决这两个问题。然而,它们需要管理员权限,可能会减少功能(使用的内存更少),从运行系统中取出RAM仍然是一个值得关注的问题。
字符串是不可变的,它将进入字符串池。一旦写入,就无法覆盖。
char[]是一个数组,当您使用密码时,应该覆盖该数组,这是应该这样做的:
char[] passw = request.getPassword().toCharArray()
if (comparePasswords(dbPassword, passw) {
allowUser = true;
cleanPassword(passw);
cleanPassword(dbPassword);
passw = null;
}
private static void cleanPassword (char[] pass) {
Arrays.fill(pass, '0');
}
攻击者可以使用它的一种情况是,当JVM崩溃并生成内存转储时,您将能够看到密码。
这不一定是恶意的外部攻击者。这可能是一个支持用户,可以访问服务器进行监控。他/她可以偷看垃圾堆并找到密码。
正如Jon Skeet所说,除了使用反射,没有其他方法。
然而,如果反射是您的选择,您可以这样做。
public static void main(String[] args) {
System.out.println("please enter a password");
// don't actually do this, this is an example only.
Scanner in = new Scanner(System.in);
String password = in.nextLine();
usePassword(password);
clearString(password);
System.out.println("password: '" + password + "'");
}
private static void usePassword(String password) {
}
private static void clearString(String password) {
try {
Field value = String.class.getDeclaredField("value");
value.setAccessible(true);
char[] chars = (char[]) value.get(password);
Arrays.fill(chars, '*');
} catch (Exception e) {
throw new AssertionError(e);
}
}
运行时
please enter a password
hello world
password: '***********'
注意:如果String的char[]作为GC循环的一部分被复制,那么前一个副本可能在内存中的某个位置。
这个旧副本不会出现在堆转储中,但如果您可以直接访问进程的原始内存,您可以看到它。通常,您应该避免任何人有这样的访问权限。