How can I safely erase sensitive data in memory in Java with the guarantee that it will not be "optimized"?

String secret="foo";
WhatILookFor.securelyWipe(secret);

And I need to know that it will not be deleted using the java optimizer.

+5
source share
4 answers

The string cannot be wiped. This is unchanging, and lacks some really dirty and dangerous tricks that you cannot change.

Thus, the safest solution is not to put data in a row in the first place. Instead, use a StringBuilder or an array of characters or another representation that is not immutable. (And then clean it when done.)


, String. , , String . , , JLS , , - .


, , / . , , " " . , , , "" , , .

+7

.

String, , - , .

, -

public class SecureString implements CharSequence {
    char[] data;
    public void wipe() {
       for(int i = 0; i < data.length; i++) data[i] = '.'; // random char
    }
}

, , , - - , , . , , - .

, , . , - :

public int wipe() {
    // wipe the array to a random value
    java.util.Arrays.fill(data, (char)(rand.nextInt(60000));
    // compute hash to force optimizer to do the wipe
    int hash = 0;
    for(int i = 0; i < data.length; i++) {
        hash = hash * 31 + (int)data[i];
    }
    return hash;
}

. , , , .

+4
+3
source

If you are going to use String, I think you are worried that it appears in a memory dump. I suggest using String.replace()for key characters, so when String is used at run time, it will change and then go out of scope after using it and will not display correctly in a memory dump. However, I highly recommend not using String for sensitive data.

0
source

All Articles