본문 바로가기

StackOverflow

[JAVA] 패스워드에 String이 아닌 char[]를 이용하는 이유

http://stackoverflow.com/questions/8881291/why-is-char-preferred-over-string-for-passwords-in-java/8881376#8881376


Q: 왜 자바의 Swing에서 패스워드에 String 이 아닌, char[]를 이용하나요? 

(질문자: Ahamed)


A: String은 immutable 객체입니다. (생성 된 이후 수정할 수 없는 객체) 스트링으로 패스워드를 저장하면, GC가 동작하기 전에는 이것을 삭제할 수 없습니다.

그렇지만, char[]를 이용하면 패스워드 체크를 한 뒤 곧바로 다른 데이터를 거기에 덮어써서, 입력된 패스워드를 제거할 수 있습니다.

물론 이 방법은 공격자가 공격할 여지를 아주 조금 줄이는 정도의 효과밖에 없고, 또한 특정 유형의 공격에만 효합니다.

(답변자: Jon Skeet)


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 Stringto handle passwords.

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

shareeditflag














up vote2229down voteaccepted

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 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 beforegarbage 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.

EDIT: As noted in 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 GC 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.

shareeditflag