I can encrypt/decrypt with Python OR with JavaScript but passing encrypted data generated by Python to my JavaScript code fails.
The base64 encoding/decoding works across languages so that base encoding on Python and decoding on JavaScript retrieves the original encrypted string.
Outside of test functions I am not using Python decrypt or JavaScript encrypt but they are here for completeness as some readers miss text saying they exist.
In Python 2:
import base64
from pyaes import AESModeOfOperationCTR
SECRET_KEY = "This_key_for_demo_purposes_only!"
def encrypt(raw_data, key=SECRET_KEY):
aes = AESModeOfOperationCTR(key)
encrypted_data = aes.encrypt(raw_data)
base64_encrypted_data = base64.b64encode(encrypted_data)
return base64_encrypted_data
def decrypt(base64_encrypted_data, key=SECRET_KEY):
encrypted_data = base64.b64decode(base64_encrypted_data)
aes = AESModeOfOperationCTR(key)
decrypted = aes.decrypt(encrypted_data)
return decrypted
In Javascript (running Server-side, on Parse.com Cloud Code):
var Buffer = require('buffer').Buffer;
var Crypto = require('crypto');
encrypt: function(raw) {
var cryptoAlgorithm = "aes-256-ctr";
var key = "This_key_for_demo_purposes_only!"
var cipher = Crypto.createCipher(cryptoAlgorithm, key);
var encrypted = cipher.update(raw, 'utf8', 'binary');
encrypted += cipher.final('binary');
var base = toBase64(encrypted);
return base;
},
decrypt: function(base64raw) {
var raw = fromBase64(base64raw);
var cryptoAlgorithm = "aes-256-ctr";
var key = "This_key_for_demo_purposes_only!"
var decipher = Crypto.createDecipher(cryptoAlgorithm, key);
var decrypted = decipher.update(raw, 'binary', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
The output of the JavaScript function decrypt() is nonsense. Where is the mismatch?
The output of the two encrypt functions does not match when given the same raw string.
My guess: in the JavaScript I shouldn't be using 'binary'. The JavaScript decrypt()
function chokes if specify 'hex'
for the data generated from the Python side.