Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In java, how to clear byte[] array inside every method to protect the value from memory dump?

In java,

If I run below code, pwd value exists all over the memory because byte array value is copied to digest method which also copies the value to some other methods.

    import java.security.MessageDigest

    byte[] pwd = "some_pwd".getBytes();
    MessageDigest md = MessageDigest.getInstance("SHA");
    for (int i = 0; i < 100; i++) {
        byte[] hash = md.digest(pwd);
    }

Memory dump software shows the password value which my customer does not like.

I checked that byte[] is copied by value from method to method.

Is there anyway to protect the important byte array value ?

like image 403
tompal18 Avatar asked Jun 29 '26 01:06

tompal18


1 Answers

Password text should preferably not be passed as String, but let's assume this is an example:

Then ensure the bytes do not occur in the strings for the test.

byte[] pwd = "rnld^ovc".getBytes(StandardCharsets.UTF_8); // "some_pwd"
for (int i = 0; i < pwd.length; ++i) {
    pwd[i]++;
}

And then the solution:

MessageDigest md = MessageDigest.getInstance("SHA");
for (int i = 0; i < 100; i++) {
    //byte[] hash = md.digest(pwd);
    for (byte b : pwd) {
        md.update(b - 1); // Maybe -1 if the string was the real password
    }
    byte[] hash = md.digest();
}
Arrays.fill(pwd, (byte)0);

Now the MessageDigest cannot maintain a copy of the array on the call to digest.

If you do not want to even have the pwd array, you would need to just take a char/byte at a time from the password field.

like image 109
Joop Eggen Avatar answered Jun 30 '26 14:06

Joop Eggen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!