3836

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[].

0

17 Answers 17

4728

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.

24
  • 37
    If a process has access to memory of your application, then that is already a security breach, right?
    – Yeti
    Sep 1, 2015 at 11:26
  • 34
    @Yeti: Yes, but it's not like it's black and white. If they can only get a snapshot of the memory then you want to reduce how much damage that snapshot can do, or reduce the window during which a really serious snapshot can be taken.
    – Jon Skeet
    Sep 1, 2015 at 11:47
  • 74
    A common attack method is to run a process that allocates lots of memory and then scans it for left-over, useful data like passwords. The process doesn't need any magical access to another process's memory space; it just relies on other processes dying without first clearing out sensitive data and the OS also not clearing memory (or page buffers) before making it available to a new process. Clearing out passwords stored in char[] locations cuts off that line of attack, something not possible when using String.
    – Ted Hopp
    Sep 5, 2016 at 19:11
  • 24
    If OS does not clear memory before giving it to another process, the OS has major security issues! However, technically the clearing is often done with protected mode tricks and if the CPU is broken (e.g. Intel Meldown) it's still possible to read old memory contents. Apr 21, 2020 at 7:33
  • 12
    @PrateekPande: It would only be in the literal pool if it were present in the source code, or explicitly interned. Those are both bad ideas in general...
    – Jon Skeet
    Jan 10, 2021 at 12:35
1335

While other suggestions here seem valid, there is one other good reason. With plain String you have much higher chances of accidentally printing the password to logs, monitors or some other insecure place. char[] is less vulnerable.

Consider this:

public static void main(String[] args) {
    Object pw = "Password";
    System.out.println("String: " + pw);

    pw = "Password".toCharArray();
    System.out.println("Array: " + pw);
}

Prints:

String: Password
Array: [C@5829428e
12
  • 51
    @voo, but i doubt you'd log via direct writing to stream and concatenation. logging framework would transform the char[] into good output
    – bestsss
    Jan 18, 2012 at 1:14
  • 49
    @Thr4wn Default implementation of toString is classname@hashcode. [C represents char[], the rest is hexadecimal hash code. Jan 20, 2012 at 12:39
  • 22
    Interesting idea. I would like to point out that this does not transpose to Scala which has a meaningful toString for arrays.
    – mauhiz
    Jul 9, 2015 at 8:36
  • 48
    I'd write a Password class type for this. It's less obscure, and harder to accidentally pass somewhere.
    – user1804599
    Aug 31, 2015 at 17:32
  • 13
    @g.rocket The hashcode for an array does not depend on the contents of the array, it is effectively random: Online Example Jul 12, 2017 at 0:03
745

To quote an official document, the Java Cryptography Architecture guide says this about char[] vs. String passwords (about password-based encryption, but this is more generally about passwords of course):

It would seem logical to collect and store the password in an object of type java.lang.String. However, here's the caveat: Objects of type String are immutable, i.e., there are no methods defined that allow you to change (overwrite) or zero out the contents of a String after usage. This feature makes String objects unsuitable for storing security sensitive information such as user passwords. You should always collect and store security sensitive information in a char array instead.

Guideline 2-2 of the Secure Coding Guidelines for the Java Programming Language, Version 4.0 also says something similar (although it is originally in the context of logging):

Guideline 2-2: Do not log highly sensitive information

Some information, such as Social Security numbers (SSNs) and passwords, is highly sensitive. This information should not be kept for longer than necessary nor where it may be seen, even by administrators. For instance, it should not be sent to log files and its presence should not be detectable through searches. Some transient data may be kept in mutable data structures, such as char arrays, and cleared immediately after use. Clearing data structures has reduced effectiveness on typical Java runtime systems as objects are moved in memory transparently to the programmer.

This guideline also has implications for implementation and use of lower-level libraries that do not have semantic knowledge of the data they are dealing with. As an example, a low-level string parsing library may log the text it works on. An application may parse an SSN with the library. This creates a situation where the SSNs are available to administrators with access to the log files.

7
  • 6
    this is exactly the flawed/bogus reference I talk about below Jon's answer, it's a well known source w/ a lot of criticism.
    – bestsss
    Jan 22, 2012 at 20:45
  • 46
    @bestass can you please also cite a reference?
    – user961954
    Aug 11, 2012 at 11:27
  • 17
    @bestass sorry, but String is pretty well understood and how it behaves in the JVM... there are good reasons to use char[] in place of String when dealing with passwords in a secure manner.
    – SnakeDoc
    Jun 27, 2014 at 0:50
  • 5
    once again though the password is passed as a string from the browser to the request as 'string' not char? so no matter what you do it's a string, at which point it should be acted on and discarded, never stored in memory?
    – Dawesi
    Aug 5, 2018 at 19:50
  • 6
    @Dawesi - At which point - that's application specific, but the general rule is to do so as soon as you get a hold of something that is supposed to be a password (plaintext or otherwise). You get it from the browser as part of an HTTP request, for instance. You cannot control the delivery, but you can control your own storage, so as soon as you get it, put it in a char[], do what you need to do with it, then set all to '0' and let the gc reclaim it. Jan 3, 2019 at 19:25
392
+50

Character arrays (char[]) can be cleared after use by setting each character to zero and Strings not. If someone can somehow see the memory image, they can see a password in plain text if Strings are used, but if char[] is used, after purging data with 0's, the password is secure.

10
  • 17
    Not secure by default. If we're talking a web application, most web containers will pass the password into the HttpServletRequest object in plaintext. If the JVM version is 1.6 or lower, it'll be in permgen space. If it's in 1.7, it'll still be readable until it gets collected. (Whenever that is.)
    – avgvstvs
    Feb 5, 2016 at 15:19
  • 6
    @avgvstvs: strings are not automatically moved to the permgen space, that only applies to intern'ed strings. Besides that, the permgen space is also subject to garbage collection, just at a lower rate. The real issue with the permgen space is it’s fixed size, which is exactly the reason why no one should mindlessly call intern() on arbitrary strings. But you are right in that the String instances exist in the first place (until collected) and turning them into char[] arrays afterwards doesn’t change it.
    – Holger
    Mar 9, 2017 at 10:04
  • 4
    @Holger see docs.oracle.com/javase/specs/jvms/se6/html/… "Otherwise, a new instance of class String is created containing the sequence of Unicode characters given by the CONSTANT_String_info structure; that class instance is the result of string literal derivation. Finally, the intern method of the new String instance is invoked." In 1.6, the JVM would call intern for you when it detected identical sequences.
    – avgvstvs
    Mar 9, 2017 at 16:43
  • 4
    @Holger, you are correct I conflated constant pool and string pool, but it is also false that permgen space only applied to interned strings. Prior to 1.7, both the constant_pool and the string_pool resided in permgen space. That means the only class of Strings that were allocated to the heap were as you said, new String() or StringBuilder.toString() I managed applications with lots of string constants, and we had lots of permgen creep as a result. Until 1.7.
    – avgvstvs
    Mar 11, 2017 at 18:43
  • 7
    @avgvstvs: well, string constants are, as the JLS mandates, always interned, hence the statement that interned strings ended up in the permgen space, applied to string constants implicitly. The only difference is that string constants were created in the permgen space in the first place, whereas calling intern() on an arbitrary string could cause the allocation of an equivalent string in the permgen space. The latter could get GC’ed, if there was no literal string of the same contents sharing that object…
    – Holger
    Mar 13, 2017 at 11:20
237

Some people believe that you have to overwrite the memory used to store the password once you no longer need it. This reduces the time window an attacker has to read the password from your system and completely ignores the fact that the attacker already needs enough access to hijack the JVM memory to do this. An attacker with that much access can catch your key events making this completely useless (AFAIK, so please correct me if I am wrong).

Update

Thanks to the comments I have to update my answer. Apparently there are two cases where this can add a (very) minor security improvement as it reduces the time a password could land on the hard drive. Still I think it's overkill for most use cases.

  • Your target system may be badly configured or you have to assume it is and you have to be paranoid about core dumps (can be valid if the systems are not managed by an administrator).
  • Your software has to be overly paranoid to prevent data leaks with the attacker gaining access to the hardware - using things like TrueCrypt (discontinued), VeraCrypt, or CipherShed.

If possible, disabling core dumps and the swap file would take care of both problems. However, they would require administrator rights and may reduce functionality (less memory to use) and pulling RAM from a running system would still be a valid concern.

20
  • 39
    I'd replace "completely useless" with "just a minor security improvement". For example you could get access to a memory dump if you happen to have read access to a tmp directory, a badly configured machine and a crash in your application. In that case you wouldn't be able to install a keylogger, but you could analyze the core dump. Jan 16, 2012 at 16:23
  • 52
    Wiping unencrypted data from memory as soon as you're done with it is considered a best practice not because it's foolproof (it's not); but because it reduces your threat exposure level. Real time attacks aren't prevented by doing this; but because it serves a a damage mitigation tool by significantly reduces the amount of data that is exposed in a retroactive attack on a memory snapshot (eg a copy of your apps memory that was written to a swap file, or that was read out of memory yanked from a running server and moved to a different one before its state failed). Jan 16, 2012 at 16:26
  • 11
    I tend to agree with the attitude of this response. I'd venture to propose most security breaches of consequence occur at a much higher level of abstraction than the bits in memory. Sure, there are probably scenarios in hyper-secure defense systems where this may be of considerable concern but seriously thinking at this level is overkill for 99% of the applications where .NET or Java are being leveraged (as it related to garbage collection).
    – kingdango
    Jan 17, 2012 at 18:18
  • 13
    After the Heartbleed penetration of server memory, revealing passwords, I would replace the string "just a minor security improvement" with "absolutely essential to not use String for passwords, but use a char [] instead."
    – Peter vdL
    Jul 24, 2014 at 5:15
  • 11
    @PetervdL heartbleed only allowed reading of a specific reused collection of buffers (used for both security critical data and network I/O without clearing in between - for performance reasons), you cannot combine this with a Java String since they are by design not reuseable. Nor can you read into random memory using Java to get at the contents of a String. The language and design problems that lead to heartbleed are just not possible with Java Strings.
    – josefx
    Jul 30, 2014 at 17:39
93

I don't think this is a valid suggestion, but, I can at least guess at the reason.

I think the motivation is wanting to make sure that you can erase all trace of the password in memory promptly and with certainty after it is used. With a char[] you could overwrite each element of the array with a blank or something for sure. You can't edit the internal value of a String that way.

But that alone isn't a good answer; why not just make sure a reference to the char[] or String doesn't escape? Then there's no security issue. But the thing is that String objects can be intern()ed in theory and kept alive inside the constant pool. I suppose using char[] forbids this possibility.

2
  • 4
    I wouldn't say that the problem is that your references will or will not "escape". It's just that strings will remain unmodified in memory for some additional time, while char[] can be modified, and then it's irrelevant whether it's collected or not. And since string interning needs to be done explicitly for non-literals, it's the same like telling that a char[] can be referenced by a static field.
    – vgru
    Jan 16, 2012 at 17:26
  • 3
    isn't password in memory as a string from the form post?
    – Dawesi
    Aug 5, 2018 at 19:43
78

The answer has already been given, but I'd like to share an issue that I discovered lately with Java standard libraries. While they take great care now of replacing password strings with char[] everywhere (which of course is a good thing), other security-critical data seems to be overlooked when it comes to clearing it from memory.

I'm thinking of e.g. the PrivateKey class. Consider a scenario where you would load a private RSA key from a PKCS#12 file, using it to perform some operation. Now in this case, sniffing the password alone wouldn't help you much as long as physical access to the key file is properly restricted. As an attacker, you would be much better off if you obtained the key directly instead of the password. The desired information can be leaked manifold, core dumps, a debugger session or swap files are just some examples.

And as it turns out, there is nothing that lets you clear the private information of a PrivateKey from memory, because there's no API that lets you wipe the bytes that form the corresponding information.

This is a bad situation, as this paper describes how this circumstance could be potentially exploited.

The OpenSSL library for example overwrites critical memory sections before private keys are freed. Since Java is garbage-collected, we would need explicit methods to wipe and invalidate private information for Java keys, which are to be applied immediately after using the key.

5
  • One way around this is to use an implementation of PrivateKey that doesn't actually load its private content in memory: via a PKCS#11 hardware token for example. Perhaps a software implementation of PKCS#11 could take care of cleaning up the memory manually. Perhaps using something like the NSS store (which shares most of its implementation with the PKCS11 store type in Java) is better. The KeychainStore (OSX keystore) loads the full content of the private key into its PrivateKey instances, but it should not need to. (Not sure what the WINDOWS-MY KeyStore does on Windows.)
    – Bruno
    Jan 21, 2012 at 13:31
  • @Bruno Sure, hardware-based tokens do not suffer from this, but what about situations where you are more or less forced to use a software key? Not every deployment has the budget to afford an HSM. Software key stores will at some point have to load the key into memory, so IMO we should at least be given the option to clear the memory at will again.
    – emboss
    Jan 21, 2012 at 14:18
  • Absolutely, I was just wondering whether some software implementations equivalent to an HSM might behave better in terms of cleaning up the memory. For example, when using client-auth with Safari/OSX, the Safari process never actually sees the private key, the underlying SSL library provided by the OS talks directly to the security daemon which prompts the user for using the key from the keychain. While this is all done in software, a similar separation like this may help if signing is delegated to a different entity (even software based) that would unload or clear the memory better.
    – Bruno
    Jan 21, 2012 at 14:29
  • @Bruno: Interesting idea, an additional indirection layer that takes care of clearing the memory would indeed solve this transparently. Writing a PKCS#11 wrapper for the software key store could already do the trick?
    – emboss
    Jan 21, 2012 at 14:45
  • Funny you should say that they take great care to use char[] "now", because I'm looking at this nice new ConnectionBuilder class added in JDK 9, and it still has password(String) and no option to pass char[] at all. It seems that with Java there's a lot of "do what I say, not what I do".
    – Hakanai
    Jun 25, 2021 at 0:02
59

As Jon Skeet states, there is no way except by using reflection.

However, if reflection is an option for you, you can do this.

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);
    }
}

when run

please enter a password
hello world
password: '***********'

Note: if the String's char[] has been copied as a part of a GC cycle, there is a chance the previous copy is somewhere in memory.

This old copy wouldn't appear in a heap dump, but if you have direct access to the raw memory of the process you could see it. In general you should avoid anyone having such access.

6
  • 3
    Better to do also something to prevent printing the password's length which we get from '***********'. Aug 27, 2015 at 19:21
  • @chux you can use a zero width character, though this might be more confusing than useful. Its not possible to change the length of a char array without using Unsafe. ;) Aug 27, 2015 at 20:16
  • 11
    Because of Java 8's String Deduplication, I think doing something like that can be pretty destructive... you may end up clearing other strings in your program that by chance had the same value of the password String. Unlikely, but possible...
    – jamp
    Feb 8, 2016 at 14:48
  • 1
    @PeterLawrey It must be enabled with a JVM argument, but it is there. Can read about it here: blog.codecentric.de/en/2014/08/…
    – jamp
    Feb 8, 2016 at 16:20
  • 2
    There’s a high chance that the password still is in Scanner’s internal buffer and, since you didn’t use System.console().readPassword(), in readable form in the console window. But for most practical use cases, the duration of usePassword’s execution is the actual problem. E.g., when making a connection to another machine, it takes a significant time and tells an attacker that it is the right time to search for the password in the heap. The only solution is to prevent attackers from reading the heap memory…
    – Holger
    Jan 6, 2020 at 16:15
47

There is nothing that char array gives you vs String unless you clean it up manually after use, and I haven't seen anyone actually doing that. So to me the preference of char[] vs String is a bit exaggerated.

Take a look at the widely used Spring Security library here and ask yourself - are Spring Security guys incompetent or char[] passwords just don't make much sense. When some nasty hacker grabs memory dumps of your RAM be sure s/he'll get all the passwords even if you use sophisticated ways to hide them.

However, Java changes all the time, and some scary features like String Deduplication feature of Java 8 might intern String objects without your knowledge. But that's a different conversation.

6
  • 3
    Why is String-deduplication scary? It only applies when there are at least two strings having the same contents, so what danger would arise from letting these two already identical strings share the same array? Or lets ask the other way round: if there is no string-deduplication, what advantage arises from the fact that both strings have a distinct array (of the same contents)? In either case, there will be an array of that contents being alive at least as long as the longest living String of that contents is alive…
    – Holger
    Mar 9, 2017 at 17:45
  • @Holger anything that's out of your control is a potential risk... for instance if two users have the same password this wonderful feature will store both of them in single char[] making it evident that they are the same, not sure if that's a huge risk but still Mar 9, 2017 at 18:28
  • 1
    If you have access to the heap memory and both string instances, it doesn’t matter whether the strings point to the same array or to two arrays of the same contents, each is easy to find out. Especially, as it is irrelevant anyway. If you are at this point, you grab both passwords, whether identical or not. The actual error lies in using plaintext passwords instead of salted hashes.
    – Holger
    Mar 9, 2017 at 18:35
  • 5
    It seems, you have a fundamental misunderstanding about String Deduplication. It doesn’t “intern strings”, all it does, is letting strings with the same contents point to the same array, which actually reduces the number of array instances containing the plaintext password, as all but one array instance can be reclaimed and overwritten by other objects immediately. These strings are still collected like any other string. Maybe it helps, if you understand that the de-duplication is actually done by the garbage collector, for strings that have survived multiple GC cycles only.
    – Holger
    Mar 13, 2017 at 11:30
  • 2
    "are Spring Security guys incompetent": It's an important question in this context. I previously wondered this myself, when looking into the differences between BCrypt and BCryptPasswordEncoder. Even in the simultaneous initial commit they took an inconsistent approach: taking String for Bcrypt and taking CharSequence for BCryptPasswordEncoder (which calls Bcrypt). Sep 17, 2019 at 16:58
44

Edit: Coming back to this answer after a year of security research, I realize it makes the rather unfortunate implication that you would ever actually compare plaintext passwords. Please don't. Use a secure one-way hash with a salt and a reasonable number of iterations. Consider using a library: this stuff is hard to get right!

Original answer: What about the fact that String.equals() uses short-circuit evaluation, and is therefore vulnerable to a timing attack? It may be unlikely, but you could theoretically time the password comparison in order to determine the correct sequence of characters.

public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    }
    if (anObject instanceof String) {
        String anotherString = (String)anObject;
        int n = value.length;
        // Quits here if Strings are different lengths.
        if (n == anotherString.value.length) {
            char v1[] = value;
            char v2[] = anotherString.value;
            int i = 0;
            // Quits here at first different character.
            while (n-- != 0) {
                if (v1[i] != v2[i])
                    return false;
                i++;
            }
            return true;
        }
    }
    return false;
}

Some more resources on timing attacks:

4
  • But that could be there in char[] comparison as well, somewhere we would be doing the same in password validation too. so how is char[] better than string? Jul 1, 2015 at 5:41
  • 3
    You're absolutely correct, the mistake can be made either way. Knowing about the problem is the most important thing here, considering there's no explicit password-comparison method in Java for either String-based or char[]-based passwords. I'd say the temptation to use compare() for Strings is a good reason to go with char[]. That way you at least have control over how the comparison is done (without extending String, which is a pain imo). Jul 2, 2015 at 21:03
  • 1
    Besides comparing plaintext passwords isn’t the right thing anyway, the temptation to use Arrays.equals for char[] is as high as for String.equals. If anyone cared, there was a dedicated key class encapsulating the actual password and taking care of the issues—oh wait, the real security packages have dedicated key classes, this Q&A is only about a habit outside of them, say, e.g. JPasswordField, to use char[] instead of String (where the actual algorithms use byte[] anyway).
    – Holger
    Mar 9, 2017 at 10:22
  • 1
    Security relevant software should do something like sleep(secureRandom.nextInt()) before rejecting a login attempt anyway, that’s not only removing the possibility of timing attacks, it also makes counteracts brute force attempts.
    – Holger
    Mar 9, 2017 at 10:24
32

Strings are immutable and cannot be altered once they have been created. Creating a password as a string will leave stray references to the password on the heap or on the String pool. Now if someone takes a heap dump of the Java process and carefully scans through he might be able to guess the passwords. Of course these non used strings will be garbage collected but that depends on when the GC kicks in.

On the other side char[] are mutable as soon as the authentication is done you can overwrite them with any character like all M's or backslashes. Now even if someone takes a heap dump he might not be able to get the passwords which are not currently in use. This gives you more control in the sense like clearing the Object content yourself vs waiting for the GC to do it.

5
  • They'll only be GC'd if the JVM in question is > 1.6. Prior to 1.7, all strings were stored in permgen.
    – avgvstvs
    Feb 5, 2016 at 15:15
  • 2
    @avgvstvs: “all strings were stored in permgen” is just dead wrong. Only interned strings were stored there and if they weren’t originating from string literals referenced by code, they were still garbage collected. Just think about it. If strings were generally never GCed in JVMs prior to 1.7, how could any Java application survive more than a few minutes?
    – Holger
    Mar 9, 2017 at 10:28
  • @Holger This is false. Interned strings AND the String pool (pool of previously used strings) were BOTH stored in Permgen prior to 1.7. Also, See section 5.1: docs.oracle.com/javase/specs/jvms/se6/html/… The JVM always checked Strings to see if they were the same reference value, and would call String.intern() FOR YOU. The result was that every time the JVM detected identical Strings in the constant_pool or heap it would move them into permgen. And I worked on several applications with "creeping permgen" until 1.7. It was a real problem.
    – avgvstvs
    Mar 9, 2017 at 16:36
  • So to recap: Until 1.7, Strings started in the heap, when they were used they were put into the constant_pool which was located IN permgen, and then if a string was used more than once, it would be interned.
    – avgvstvs
    Mar 9, 2017 at 16:39
  • 2
    @avgvstvs: There is no “pool of previously used strings”. You are throwing entirely different things together. There is one runtime string pool containing string literals and explicitly interned string, but no other. And each class has its constant pool containing compile-time constants. These strings are automatically added to the runtime pool, but only these, not every string.
    – Holger
    Mar 9, 2017 at 17:34
29

String is immutable and it goes to the string pool. Once written, it cannot be overwritten.

char[] is an array which you should overwrite once you used the password and this is how it should be done:

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');
}

One scenario where the attacker could use it is a crashdump—when the JVM crashes and generates a memory dump—you will be able to see the password.

That is not necessarily a malicious external attacker. This could be a support user that has access to the server for monitoring purposes. He/she could peek into a crashdump and find the passwords.

5
  • 2
    ch = null; you can't do this
    – Yugerten
    Dec 2, 2018 at 22:56
  • 3
    But doesn't request.getPassword() already create the string and add it to the pool?
    – Tvde1
    Dec 9, 2019 at 11:09
  • 2
    ch = '0' changes the local variable ch; it has no effect on the array. And your example is pointless anyway, you start with a string instance you call toCharArray() on, creating a new array and even when you overwrite the new array correctly, it doesn’t change the string instance, so it has no advantage over just using the string instance.
    – Holger
    Jan 6, 2020 at 16:25
  • @Holger thanks. Corrected the char array cleanup code.
    – ACV
    Jan 8, 2020 at 11:00
  • 3
    You can simply use Arrays.fill(pass, '0');
    – Holger
    Jan 8, 2020 at 11:06
25

The short and straightforward answer would be because char[] is mutable while String objects are not.

Strings in Java are immutable objects. That is why they can't be modified once created, and therefore the only way for their contents to be removed from memory is to have them garbage collected. It will be only then when the memory freed by the object can be overwritten, and the data will be gone.

Now garbage collection in Java doesn't happen at any guaranteed interval. The String can thus persist in memory for a long time, and if a process crashes during this time, the contents of the string may end up in a memory dump or some log.

With a character array, you can read the password, finish working with it as soon as you can, and then immediately change the contents.

1
  • @fallenidol Not at all. Read carefully and you will find the differences. Sep 11, 2017 at 6:02
15

Case String:

    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

Case CHAR ARRAY:

    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
13

A string in Java is immutable. So whenever a string is created, it will remain in memory until it is garbage collected. So anyone who has access to the memory can read the value of the string.

If the value of the string is modified then it will end up creating a new string. So both the original value and the modified value stay in the memory until it is garbage collected.

With the character array, the contents of the array can be modified or erased once the purpose of the password is served. The original contents of the array will not be found in memory after it is modified and even before the garbage collection kicks in.

Because of the security concern it is better to store password as a character array.

3

It is debatable as to whether you should use String or use Char[] for this purpose because both have their advantages and disadvantages. It depends on what the user needs.

Since Strings in Java are immutable, whenever some tries to manipulate your string it creates a new Object and the existing String remains unaffected. This could be seen as an advantage for storing a password as a String, but the object remains in memory even after use. So if anyone somehow got the memory location of the object, that person can easily trace your password stored at that location.

Char[] is mutable, but it has the advantage that after its usage the programmer can explicitly clean the array or override values. So when it's done being used it is cleaned and no one could ever know about the information you had stored.

Based on the above circumstances, one can get an idea whether to go with String or to go with Char[] for their requirements.

1

A lot of the previous answers are great. There is another point which I am assuming (please correct me if I am wrong).

By default Java uses UTF-16 for storing strings. Using character arrays, char[] array, facilitates use of Unicode, regional characters, etc. This technique allows all character set to be respected equally for storing the passwords and henceforth will not initiate certain crypto issues due to character set confusion. Finally, using the character array, we can convert the password array to our desired character set string.

1
  • char in Java is a 16 bit value and char arrays are also assumed to be UTF-16 encoded. docs.oracle.com/javase/7/docs/api/java/lang/… If you mean to store strings in different encodings, I think you must use byte arrays instead. To get differently encoded strings, there is String.getBytes.
    – JayK
    Mar 12, 2022 at 12:39

Not the answer you're looking for? Browse other questions tagged or ask your own question.