0

Im trying to decrypt with Pycrypto an encrypted text with CryptoJS, and I would like to know how is generated the by default IV value from CryptoJS?An example code solving the decryption would be great.

This is the decryption code with JS:

var crypto_test = require('crypto-js'); 
var bytes = crypto_test.AES.decrypt(encrypted_text, 'test_key');

This is the equivalent Python version that Im trying to create:

BS = 32
key = 'test_key'
dkey = hashlib.sha256(key.encode()).digest()
encodedEncrypted = base64.b64decode(encrypted_text)
#block_size is 16
cipher = AES.new(dkey, AES.MODE_CBC, encodedEncrypted[:AES.block_size])
decrypted = _unpad(cipher.decrypt((encodedEncrypted[AES.block_size:])).decode('utf-8')

def _unpad(s):
    return s[:-ord(s[len(s)-1:])]

From the documentation of CryptoJS I found:

  1. If a passphrase has been used instead of a key then It will use AES 256 by default.
  2. The mode is CBC.
  3. The padding is PKCS7.

However Pycrypto by default is forcing me to use a 16 bytes IV not a 32 as the documentation from CryptoJS proposed..so Im a bit confused on the correct way to do the decryption here.. Also I saw in some documentation that CryptoJS applies to sha256 to passphrase..but still not sure about that ..

That code will not crash but will give an empty text..

chuseuiti
  • 783
  • 1
  • 9
  • 32
  • Check the following: 1- base64 encoding and decoding. 2- __block sizes and padding.__ – Ahmad Siavashi Oct 03 '16 at 22:31
  • 1
    An IV is always 16 bytes (for AES). The key in AES256 is always 32 bytes. You need to hash the passphrase with SHA256 in your Python script and use the result as the key, with the same IV used in your JS code. – Luke Joshua Park Oct 03 '16 at 23:48
  • Thanks, and do you know how CryptoJS generates the IV from the key? as from your comment that is what Im doing incorrectly – chuseuiti Oct 03 '16 at 23:56
  • 2
    The IV should not be generated from the key, it should be random bytes from a cryptographically secure generator. It is common to prefix the IV to the encrypted data so it is directly available for decryption. – zaph Oct 04 '16 at 00:17
  • 2
    @zaph The salt is generated randomly in CryptoJS. The the EVP_BytesToKey function generates a key+IV from salt+password. – Artjom B. Oct 04 '16 at 04:13
  • @Artjom B. exactly the info about the key and the IV that I was looking for and thanks for the link to the other question, I couldn't find it. – chuseuiti Oct 04 '16 at 14:50

0 Answers0