Encode in Python and decrypt in Javascript
Question: I've searched for this, there are lots of hits, but I can't find one that is
neither complete (pulls all the bits together) nor says its a bad idea, use
HTTP. I've tried lots of things based on the hits I've found, but I can't get
it to work.

The target problem is to AES encrypt textual data at one place, send it to a
web API where it is stored in a database, then retrieve from the database via
another API and decode it in the browser. This is not for security in
transmission, it is so that, if the originator and the receiver know the key
and IV, then it can be stored without the server knowing what the real content
is.

The originator code is python, and the web API is python, so to make life
easier initially, I'm storing the content unencrypted in the database. I've
done AES encrypt/decrypt in python before, so that's not an issue. What I'm
trying to do is encrypt in python as the content comes out of the database,
transmit it, then decrypt in javascript. I've been using the python 'from
Crypto.Cipher import AES' code, and javascript CryptoJS implementation from
code.google.com

I'm happy at this stage to write the key and the IV into the code,
distribution isn't really a problem as the originator and the client browser
are effectively the same system.

I've not added any code because I think it would be more trouble than its
worth at this stage.

Thanks in advance!

OK, some code. On the server python(3) side:

    
    
    text = 'This is a message'
    key = 'This is a key123'
    iv = 'This is an IV456'
    text += (16 - len(text) % 16) * ' '  # Pad to 16 chars, spaces are OK here
    aes = AES.new(key, AES.MODE_CBC, iv)
    enc = base64.b64encode(aes.encrypt(text)).decode()
    print(enc)
    

enc is passed along with other data, JSON encoded, as the response to an AJAX
request. On the client javascript side:

    
    
    enc = /* from JSON */ ;
    console.log(enc) ;
    key = 'This is a key123';
    iv  = 'This is an IV456';
    text = CryptoJS.AES.decrypt(Base64.decode(enc), key,
               { iv: iv, mode: CryptoJS.mode.CBC })) ;
    console.log(text)
    

The python print(enc) and the javascript console.log(env) are the same, so I
know the b64'd encoded data is coming over OK. The console.log(text) (in
Chrome) shows as

    
    
    l.WordArray.t.extend.init { ... }'
    

and not 'This is a message'. So why not!


Answer: **Solved, but another mystery**

I used the code from this gist:

<https://gist.github.com/andres-erbsen/1307675>

But: this uses code from <http://crypto-js.googlecode.com/files/>... which is
not what you get from the download at <https://code.google.com/p/crypto-
js/downloads/list>. The gist code uses Crypto.xxxx names; the download code
uses CryptoJS.xxxx names. The gist is 2 years old, has CryptoJS replaced
Crypto maybe?

