Skip to main content
1 of 2
Serverfrog
  • 578
  • 7
  • 18

Is it more secure to overwrite the value char[] in a String

I talk about a Java implementation. Is it more secure to use reflection to access to the internal Field value of type char[] inside a java.lang.String Instance and overwrite the containing values like the following example?

As a Example why someone could use it: Someone enter a Password and after the Password is used (maybe Authorization)this exact String will be no use after that, except to read out of the Memory, he could overwrite it and the Password as clear readable String will be out of the memory.

Example Implementation:

SecureRandom random = SecureRandom.getInstanceStrong();
String source = "1234SecureThingy"

Field charField = String.class.getDeclaredField("value");
charField.setAccessible(true);

char[] noise = new char[source.length()];
for (int i = 0; i < source.length(); i++) {
    noise[i] = (char) random.nextInt(Character.MAX_VALUE + 1);
}

charField.set(source, noise);

TL;DR: Is it more secure to Remove the value of a String with Reflection?

Serverfrog
  • 578
  • 7
  • 18