为什么我们从char数组中读取密码而不是String [英] Why we read password from console in char array instead of String

查看:134
本文介绍了为什么我们从char数组中读取密码而不是String的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

为什么char []首选字符串作为密码?

当我准备 OCPJP 时,我遇到了主题 - 从控制台读取用户输入。

When I was preparing for OCPJP I came accross the topic - "Reading User input from console".

有一个例子,它在 String 引用中读取用户名,而密码 char [] 数组中,但我无法理解为什么它使用了char数组..这是代码: -

There was an example where it read username in String reference, whereas password in a char[] array, but I couldn't understand why it used char array.. Here is the code : -

Console console = System.console();

String username = console.readLine("User Name? ");
char[] password = console.readPassword("Password? "); 

这引起了我的疑问..为什么我们没有使用 String 对商店密码的引用。由于 字符串 不可变的,因此在字符串中读取密码必须更安全,因为其内容不能为此而改变。

This raised a doubt in my mind.. Why didn't we used String reference to store password. Since Strings are immutable, so it must be more secure to read password in a String, as its content could not be changed for that matter.

那么,在中阅读密码的重点是什么? char [] array ..

So, what's the whole point in reading password in char[] array..

有人可以解决这个问题吗?

Can anyone shed some light in this matter?

推荐答案

正如你所说,字符串是不可变的,这意味着一旦你创建了字符串,如果另一个进程可以转储内存,那么就没有办法(好吧,可能有反射)你可以得到在GC开始之前摆脱数据。

As you said, strings are immutable, meaning that once you've created the string, if another process can dump memory, there's no way (ok, may with reflection) you can get rid of the data before GC 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.

这篇关于为什么我们从char数组中读取密码而不是String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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