3

Is there a way to do it? I am aware garbage collector in java will eventually do it if I dereference it. However I need to immediately clear the byte array memory as it is critical memory(passwords etc). Thus I was trying to clear memory via JNI. Is there a way to do it?

My java code :

    public void clearBytes(byte[] data) {
            clear(data);
    }

//private native method clear(byte[] bytes);
private native void clear(byte[] arr);

And Here's my JNI code

    JNIEXPORT void JNICALL Java_com_java_self_EncryptorUtil_clear(JNIEnv *env, jobject obj, jbyteArray arr)
    {
      //code to free/delete/clear memory
      free(arr);
      return;
    }

I am trying to clear the same memory as pointed to by "data" Please tell me if you guys need anything else.

Thanks.

  • You posted more-or-less the same question here, though with different code: https://stackoverflow.com/questions/55252691/i-was-trying-to-delete-the-memory-of-a-byte-array-present-in-java-using-jni –  Mar 21 '19 at 02:37
  • 4
    Possible duplicate of [Why is char\[\] preferred over String for passwords?](https://stackoverflow.com/questions/8881291/why-is-char-preferred-over-string-for-passwords) or [Java security: how to clear/zero-out memory associated with an object?](https://stackoverflow.com/questions/6473352/java-security-how-to-clear-zero-out-memory-associated-with-an-object-and-or-e) – Edward Thomson Mar 21 '19 at 02:41
  • Yes I did. It was downvoted before I could add(or as I had not added) the relevant code and I wanted the answer asap. Thanks for clarifying though. This helps. :) – user3424211 Mar 21 '19 at 17:14

1 Answers1

3

If the native code is in standard C, then free() has never guaranteed that it clears memory. And, is it legitimate to deallocate JVM-allocated data into the C malloc pool? Seems dangerous to me, but I don't use JNI. Note that the Java layer still has at least one reference (data) to the memory you've just deallocated.

I think what you want to do is to overwrite the byte array with zeroes, but you can do that in Java anyway. Once you've overwritten it, obliterating the secrets, you don't care when the garbage collector finally gets round to collecting it.

    for (int k; k<data.length; k++)
        data[k] = 0;

Maybe you're getting confused about the differences between a String, which is immutable (so you can't overwrite it) and a byte array which is mutable (so you can overwrite it).

  • This answer is correct. You can’t free Java objects in JNI code. Just clear the memory (in Java) and let the Java garbage collector take care of the memory. – prl Mar 21 '19 at 04:06