Search code examples
javascriptnode.jscryptojs

CryptoJs is not decrypting URL on my NodeJS server


I am forwarding API calls from my frontend to my backend. I encrypt the API calls using CryptoJS.AES using the passphrase 'somekey'.

My relevant client code is...

var host = 'http://localhost:3000'

$('.send-button').click(function(){
  var request = $('.request-input').val();
  var encryptedRequest = CryptoJS.AES.encrypt(request, 'somekey');
  console.log(encryptedRequest.toString())  
  var decryptedRequest = CryptoJS.AES.decrypt(encryptedRequest, 'somekey');
  console.log('Decrypted Request: ' + decryptedRequest.toString());
  handleRequest(encryptedRequest.toString());
});

var handleRequest = function(request){
    $.ajax({
        type: "GET",
        url: host + '/requests?call=' + request,
        success: function(data) {
        var rawJSON = JSON.stringify(data, null, 2);
        editor.setValue(rawJSON);
        },
        dataType: 'json'
   });
}

relevant server side code is...

var port = 3000;
var serverUrl = "127.0.0.1";

var http = require("http");
var path = require("path");
var fs = require("fs");
var express = require("express");
var CryptoJs = require("crypto-js");
var app = express(); 

app.get('/requests', function(req, res) {
    console.log('REQUEST: ' + req);
    var call = req.query.call;
    console.log(call)
    console.log("To send: " + CryptoJs.AES.decrypt(call, 'somekey'));
}); 

The problem I keep getting is that it that when I decrypt it it either doesn't get the original URL and instead returns a bunch of jibberish. An example of this is...

Encryption: U2FsdGVkX1/NRbZkyP60pPu3Cb9IcQ4b9n4zJkExp2LNR3O1EdEpqHLNACnYuatN

Decryption: 68747470733a2f2f6e6577736170692e6f72672f76312f61727469636c6573

OR... It just returns nothing and appears blank.

Ideally I would like something like this.

Encryption: U2FsdGVkX1/NRbZkyP60pPu3Cb9IcQ4b9n4zJkExp2LNR3O1EdEpqHLNACnYuatN

Decryption: https://newsapi.org/v1/articles 

Can anyone see what I am dong wrong?


Solution

  • Here is a working jsfiddle: https://jsfiddle.net/5Lr6z4zp/1/

    The encryption results in a Base64 string, while the decrypted string is Hex. To get back the “Message” you need to convert that to Utf8: decryptedRequest.toString(CryptoJS.enc.Utf8)

    Here is the relevant part of the code that works:

    var request = "testing decryption";
    var encryptedRequest = CryptoJS.AES.encrypt(request, 'somekey');
    console.log(encryptedRequest)  
    var decryptedRequest = CryptoJS.AES.decrypt(encryptedRequest, 'somekey');
    var decryptedMessage = decryptedRequest.toString(CryptoJS.enc.Utf8)
    console.log('Decrypted Request: ' + decryptedMessage);
    

    Here is a link for a resources that explains the encryption/decryption in more detail: http://www.davidebarranca.com/2012/10/crypto-js-tutorial-cryptography-for-dummies/