javascriptencryptioncryptojs

How to check if the decryption is correct?


I'm working on chat room that encrypt messages for more than one users and each user might have different encryption and key/password. The user's key won't work with all the message, therefore; return errors.

var message ="secret message";
var encrypted = CryptoJS.AES.encrypt(message, "Secret Passphrase");
try {
    var decrypted = CryptoJS.AES.decrypt(encrypted, "Secret Passphrase123").toString(CryptoJS.enc.Utf8);
    if (decrypted.length > 0) {
        alert(decrypted);
    } else {
        alert("false");
    }
} catch(e) {
    alert("false");
}

I'm currently catching the error, but sometimes the decryption returns with jumbled up letters and symbols. The current way I'm doing this is not efficient. Is there a better way?


Solution

  • What is needed is authenticated encryption, see Wikipedia.

    Essentially HMAC the encrypted data with the encryption key and append the result to the encrypted data.

    Prior to decryption, HMAC the encrypted data with the decryption key and compare to the appended HMAC value. (Use a constant time comparison function.)

    enter image description here