I am working on creating the symmetric encryption chains in JavaScript which can encrypt the message using multiple different encryption algorithms (eg. AES-DES-RC4). It was working just fine when I stumbled across a problem when trying to decrypt the same cipher twice.
I am using CryptoJS library and when trying to decrypt the cipher for the second time it either throws a Malformed UTF-8 data error or returns an empty string.
Here is my code:
import CryptoJS from 'crypto-js'
function createChain(chainName: string) {
const algos = chainName.split('-')
return {
encrypt: (content, key) => algos.reduce((cipher, algo) => CryptoJS[algo].encrypt(CryptoJS.enc.Utf8.parse(cipher), key).toString(), content),
decrypt: (cipher, key) => algos.reverse().reduce((message, algo) => CryptoJS[algo].decrypt(message, key).toString(CryptoJS.enc.Utf8), cipher)
}
}
const chain = createChain('DES-RC4-Rabbit-AES')
const message = 'test message'
const key = 'secret key'
const cipher = chain.encrypt(message, key)
console.log('Cipher:', cipher)
const l = 4
const decrypted = new Array(l).fill(0).map(() => {
try {
return chain.decrypt(cipher, key)
} catch (e) {
return e.message
}
})
decrypted.forEach((d, i) => {
console.log(`decrypted[${i}]=${d}`)
})
And here is my output:
Cipher: U2FsdGVkX19ENJVFoh1O1Y3RLTVph2k9eo1/bXxR9ccraZ912MDu7/PF+jJ0eSbSN060hIMudtO4J2J7YyADhQBIV5cTpFQIuKRkY9MZeh8ZC51RY+t7QdR/CSqWLzWjyUlaA8Lp02eAnf6xdnfiezbeiOrwo97WhHPRAcwVJMVuvN3K0L4xbWT+JOG6c1JY
decrypted[0]=test message
decrypted[1]=Malformed UTF-8 data
decrypted[2]=test message
decrypted[3]=Malformed UTF-8 data
As you can see it works alternately when I am trying to decrypt the same cipher. I have tried decrypting it more than 4 times, resulting with the same pattern.
What I have observed:
Does anyone have an idea what is going on? Thanks in advance.