Skip to content
Advertisement

Decrypt AES in JavaScript

I am encrypting a text with AES256 in swift language and outputting it as hex. I want to decrypt this code I received with JS, but I could not reach the result. I tried the CryptoJS library but still couldn’t get the result I wanted. All I want is the js code that will give me the decoded version when I enter the IV, password and ciphertext.

JavaScript

With the Node.js code above, I achieve what I want, but I want to do it with normal JS code, not using node. I don’t want to mess with the server. I would be very happy if you help.

EDIT: I am using CryptoSwift library in Swift language.

JavaScript

I tried to do something with CryptoJS with the codes from the site below, but it didn’t work like the codes in Node.js.

EDIT2:

  • I’ve been trying different things but couldn’t quite figure it out. I get an error when I add PBKDF2. I don’t fully understand the problem.

JavaScript
JavaScript

Advertisement

Answer

CryptoJS uses WordArrays, so that key, IV and ciphertext have to be converted accordingly. For this purpose the appropriate encoders have to be applied. Furthermore decrypt() expects the ciphertext as CipherParams object.

This results in the following possible CryptoJS implementation:

JavaScript
JavaScript

which is functionally identical to the posted NodeJS code that also successfully decrypts the test data.


Regarding the question asked in the comment about the encodings:
In general, the decryption side must have knowledge of the encodings used for encryption. However, in this case the encodings can be derived from the posted NodeJS code:

Also, the data used is consistent with these conclusions.


Note that for security reasons a static IV may not be used. Instead, a random IV must be generated for each encryption.
Also, no password may be applied as key, even if it has the right length. If a password is to be used, a key derivation is necessary, e.g. with PBKDF2.
For test purposes, the data is of course enough.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement