I'm encrypting data with AES, using CryptoJS.

CryptoJS returns an empty string in case the data couldn't be encrypted with the given passphrase. I'm not sure if this is intended, or happens in all libraries, but I need to know whether or not the data was decrypted successfully.

The problem is this:

if(decrypted == '') {
    // Not sure if decryption failed or if data was empty to begin with

Would it be okay to prefix the raw data before encryption? Like this:

Raw data:

Lorem ipsum a dolor sit amet.


this-string-is-used-to-verify-decryption;Lorem ipsum a dolor sit amet.

When decrypting the data, I could simply check if it has that prefixed data in. Meaning, an empty string would only be returned if the decryption failed.

var prefix = 'this-string-is-used-to-verify-decryption;';
if(decrypted.substr(0, prefix.length) == prefix) {
    // Decrypted successfully

Is there something wrong with this approach? Does it create a security risk, if an attacker knows all raw data will begin with a certain text?

I originally posted this question to StackOverflow. Thought I'd remove the code parts but they are fairly easy to understand, so I'll leave them.


1 Answer 1


There is no risk if the attacker knows part of the plaintext. This doesn't help to recover the rest of the plaintext. Even if the attacker knows all the bits but one, with any decent encryption algorithm, the attacker cannot tell what the last bit is from the ciphertext.

After all, it happens all the time with known data formats. For example, if you download a web page over HTTPS, the attacker knows that the page begins with <html><head> or some such.

Note that even if you find the expected prefix, this doesn't guarantee that the rest of the data isn't corrupted: encryption guarantees confidentiality, but not integrity. You need either to use an authenticated encryption mode (which Crypto-js doesn't provide) or to also transmit a MAC of the ciphertext (encrypt-then-MAC).

  • $\begingroup$ I assumed this would be the case. Good point about HTTPS. $\endgroup$ Apr 4, 2014 at 20:26
  • $\begingroup$ Good answer. @MarttiLaine Just throwing my 2 cents here, wouldn't checking for valid padding effectively do the same thing (padding can be seen as a known suffix)? I'm not familiar to CryptoJS btw $\endgroup$
    – rath
    Apr 6, 2014 at 14:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.