1

going through some Fortify findings here and it is telling me not to use string data types for sensitive data because they can hang around in memory too long. This exposes the user's data should there be an unrelated memory attack, such as Heartbleed.

If I set a string var to null after use, does that memory location actually get cleared, or is a copy of the var created to store the null?

Thanks

Dave C
  • 246
  • 1
  • 9

2 Answers2

8

I think you're asking the wrong question.

If you set a variable to null, then sure, that reference points to null. The original value can be garbage collected.

The problem is that Strings are a bit more complicated than that. The question you should be asking is why else can Strings stick around in memory?

One answer to that is the String literal pool. Google is your friend, but here is a decent start:

What is the Java string pool and how is “s” different from new String(“s”)?

When will a string be garbage collected in java

Garbage collection of String literals

Community
  • 1
  • 1
Kevin Workman
  • 41,537
  • 9
  • 68
  • 107
  • So after reading all that, it sounds like the best method is the recommendation from Fortify and @K139 - use Char[ ] and null it when done. – Dave C May 19 '15 at 19:43
  • @DaveC If you're worried that somebody is going to go through the trouble of reading your program's memory, what's stopping them from simply reading the character array? – Kevin Workman May 19 '15 at 20:29
  • I wouldn't say Fortify is 100% accurate, but the logic goes like this. If I load a Char[ ] with sensitive data, I can wipe it immediately after use and the data is no longer in memory. Attacks like Heartbleed rely on data hanging around in memory long enough to get read by the exploit code. Using a Char[ ] doesn't completely mitigate the vuln, but if the time in memory is reduced from X number of minutes to X number of milliseconds then the likelihood is significantly reduced. – Dave C May 20 '15 at 01:45
  • And I have fewer noisy Fortify findings to look at every release. :-D – Dave C May 20 '15 at 01:46
  • On the flip side, your colleagues will inherit and maintain odd code. Everything has a price. – David Soroko May 20 '15 at 10:25
0

If you set String references to null, then it may not be removed from the actual memory, and could be available for potential hacker.

You could use a Char[] and set it to null/invalid chars to avoid this problem, and also it is always better to keep the sensitive data in encrypted format.

K139
  • 3,654
  • 13
  • 17