Can I encrypt a file multiple times without an exponential file increase? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Can I encrypt a file multiple times without an exponential file increase? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

The below results in an exponential increase in size for encrypted:

let original = 'something'
let passphrase = 'whatever'
let times = 100
let i = 0

let encrypted = CryptoJS.AES.encrypt(original, passphrase).toString()

while (i < times) {
  encrypted = CryptoJS.AES.encrypt(encrypted, passphrase).toString()
  i++
}

Is there some other CryptoJS algorithm/method/approach I can use that will not result in an exponential size increase?

Or is this not possible?

NOTE: If I don’t use toString() it breaks when I try to re-encrypt what has already been encrypted. I get a UnhandledPromiseRejectionWarning: RangeError: Invalid array length.

Answer

Running your code would timeout for me. The encryption string apparently getting very long as it was base64 encoded.

We can reduce how much it increases by encrypting the wordarray instead of the base64 encoded version of the wordarray:

let original = 'something'
let passphrase = 'whatever'
let times = 100
let i = 0

let encrypted = CryptoJS.AES.encrypt(original, passphrase).toString()
encrypted = CryptoJS.enc.Base64.parse(encrypted)

while (i < times) {
  encrypted = CryptoJS.AES.encrypt(encrypted, passphrase).toString()
  i++
  encrypted = CryptoJS.enc.Base64.parse(encrypted)
}

http://jsfiddle.net/dwvxua96/

This runs fast and creates a string that grows by only a few bytes each iteration. You can probably reduce that more by setting padding options, or passing in a key/iv pair which may prevent the addition of a salt parameter.

the decryption would look like:

i = 0
while (i <= times) {
  encrypted = CryptoJS.AES.decrypt(encrypted, passphrase)
  encrypted = CryptoJS.enc.Base64.stringify(encrypted);
  i++
}


encrypted = CryptoJS.enc.Base64.parse(encrypted);
encrypted = CryptoJS.enc.Utf8.stringify(encrypted)
We are here to answer your question about Can I encrypt a file multiple times without an exponential file increase? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji