Question

In my program i am trying to encrypt plain text with AES giving atleast 50 iterations. But the problem is that i am getting OutOfMemory Error. From the post, Recommended # of iterations.... i came to know that LastPass uses 100,000 iterations. But i am not even able to use 50 iterations ofcourse for AES.

Here is the code,

static String encrypt(String value, String salt) throws Exception {

    Key key = generateKey();
    Cipher c = Cipher.getInstance(ALGORITHM);  
    c.init(Cipher.ENCRYPT_MODE, key);

    String valueToEnc = null;
    String eValue = value;
    for (int i = 0; i < 100; i++) {
        valueToEnc = salt + eValue;
        byte[] encValue = c.doFinal(valueToEnc.getBytes());
        eValue = new BASE64Encoder().encode(encValue);
    return eValue;
    }

I know that using Base64Encoder gives a warning. So please don't post about it. I'll change it later.

My question is Is there any way of increasing iterations without getting this error?

Sorry if it is a dumb question and any answer is appreciated. Thanks in advance.

Here is the exception log,

Exception in thread "AWT-EventQueue-0" java.lang.OutOfMemoryError: Java heap space
    at java.lang.StringCoding$StringEncoder.encode(StringCoding.java:300)
    at java.lang.StringCoding.encode(StringCoding.java:344)
    at java.lang.StringCoding.encode(StringCoding.java:387)
    at java.lang.String.getBytes(String.java:956)

Here is the printed valueEnc (just a part of it)

TAtYyypIcW2kGWWKWRM1PWYCgi55hVnUqBv3Ze0c93R8tlUykr22xqeTLesPVlyepJv94ME/5JLQ
Was it helpful?

Solution 2

It might be because of the increasing value of the ciphertext and it is not being stored in the encValue variable. That huge amount of characters in the cipher text are taking a lot of memory and that resulted in OutOfMemory error.

OTHER TIPS

You problem is that your cipher is getting larger and larger.

Assuming that the salt is 5 characters and your value is 10 characters you need at least the following amount of memory for each iteration:

  • 10 bytes (value) + 5 bytes (salt) for the initial iteration
  • 20 bytes (base64 encoded) + 5 bytes (salt) for the second iteration
  • 32 bytes (base64 encoded) + 5 bytes (salt) for the third iteration
  • 48 bytes (base64 encoded) + 5 bytes (salt) for the fourth iteration
  • 72 bytes (base64 encoded) + 5 bytes (salt) for the fifth iteration

As you see your memory will grow faster than imagined. Your problem is that AES encrypts the value whereas a hash will stay in the same size all the time (e.g. SHA-256 will always be 256 bit after hashing).

So in my eyes you're using the wrong tool and create a memory leak with this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top