I have to convert a encrypted data response back to plain text.
For this I am using a ajax post call to get the data response and than on sucess passing that data response a decrypto function and getting back the response in plain text (this is the idea)
Now, when I created a Ajax post call and than passing that decrypto their on success nothing is happening
I am sure my decrypto is working
Here is working fiddle for that
https://jsfiddle.net/yktup39e/
Now, problem is in the Ajax. I have only once make an Ajax call so I pretty much sure there will problem in that. But I am not getting that.
This is my code-
JS -
$('#action-button').click(function() {
var settings = {
async: true,
crossDomain: true,
url: "http://192.168.168.76:8080/HTMLPortingNewService/GetData?ChartName=widget3LineChart&lob=M&carrier=0&enrollmenttype=0&state=0&agent=0&fromdate=04%2F03%2F2015&todate=05%2F03%2F2015&requestID=499F6BF5E4610454A887AB37AF0814E8",
method: "POST",
headers: {
"cache-control": "no-cache",
"postman-token": "ac20a050-a8c8-6d58-4350-66141d519394",
"content-type": "application/x-www-form-urlencoded"
},
data: {
"username": "aHRtbHVzZXIx",
"password": "SHRtbDIwMTY="
}
}
$.ajax(settings).done(function (response) {
console.log(response);
decrypted = decryptByDES(response,DES);
console.log(decrypted);
});
});
function decryptByDES(cipherTextString, keyString) {
var keyHex = CryptoJS.enc.Utf8.parse(keyString);
var decrypted = CryptoJS.DES.decrypt({
ciphertext: CryptoJS.enc.Base64.parse(cipherTextString)
}, keyHex, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
alert(decrypted);
return decrypted.toString(CryptoJS.enc.Utf8);
}
HTML -
<script src="tripledes.js"></script>
<script src="mode-ecb.js"></script>
<button id="action-button">Click me to load info!</button>
<div id="info"></div>
Can anyone please help me with that??
Try to include jquery in your page.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.0/jquery.js"></script>
Related
I have to hit a URL and get its encrypted data response back and use that encrypted data to decrypt data bu using a key.
I used POSTMAN to get the data response back but when I looked into it was just some symbols and not anything like a data response. So, it is encrypted.
I already have a function that convert the encrypted response back to plain text but now, I am not understanding how will I convert that data response to plain text as I have to first get that data response and then only use that data response in a parameter of a decrypto function and with the help of key I can change the back it to plain text.
I know how to change a cipher text to pln text but here things are little bit different.
But as I have to get the data response back shouldn't I have to make a POST request to get it or maybe I am understanding it wrong.
This is my decrypto function-
function decryptByDES(cipherTextString, keyString) {
var keyHex = CryptoJS.enc.Utf8.parse(keyString);
var decrypted = CryptoJS.DES.decrypt({
ciphertext: CryptoJS.enc.Base64.parse(cipherTextString)
}, keyHex, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
alert(decrypted);
return decrypted.toString(CryptoJS.enc.Utf8);
}
Here when I calling it
<button onclick="decryptByDES('aHJHDJSHJhjsak=', 'ALSOWURNsa');">View</button>
I am giving or specifying the ciphertext string and key string as I using it only for testing there is no security issue. It is giving the decrypted value in alert-box.
So, in all I want to know how to get an encrypted data response and used that in the function so read it like a plain text.
EDIT:
With the help of POSTMAN I generated code for Javascript Ajax call
var settings = {
"async": true,
"crossDomain": true,
"url": "http://192.168.168.76:8080/HTMLPortingNewService/GetData?ChartName=widget3LineChart&lob=M&carrier=0&enrollmenttype=0&state=0&agent=0&fromdate=04%2F03%2F2015&todate=05%2F03%2F2015&requestID=499F6BF5E4610454A887AB37AF0814E8",
"method": "POST",
"headers": {
"cache-control": "no-cache",
"postman-token": "ac20a050-a8c8-6d58-4350-66141d519394",
"content-type": "application/x-www-form-urlencoded"
},
"data": {
"username": "aHRtbHVzZXIx",
"password": "SHRtbDIwMTY="
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
So, now how I can call this response in my function??
You have to call decryptByDES after ajax complete.
function callServer(){
var settings = {
"async": true,
"crossDomain": true,
"url": "http://192.168.168.76:8080/HTMLPortingNewService/GetData?ChartName=widget3LineChart&lob=M&carrier=0&enrollmenttype=0&state=0&agent=0&fromdate=04%2F03%2F2015&todate=05%2F03%2F2015&requestID=499F6BF5E4610454A887AB37AF0814E8",
"method": "POST",
"headers": {
"cache-control": "no-cache",
"postman-token": "ac20a050-a8c8-6d58-4350-66141d519394",
"content-type": "application/x-www-form-urlencoded"
},
"data": {
"username": "aHRtbHVzZXIx",
"password": "SHRtbDIwMTY="
}
}
$.ajax(settings).done(function (response) {
console.log(response);
decrypted = decryptByDES(response, keyString);
console.log(decrypted);
});
}
And in your HTML call this function:
<button onclick="callServer();">View</button>
I need to write a script inside of datorama.com to access pardot.com. Pardot does have an API that requires a request that has a request inside the body as
POST: https://pi.pardot.com/api/login/version/3
message body: email=&password=&user_key=
Right now here is my code:
phantom.casperPath = casperPath;
phantom.injectJs(casperPath + "/bin/bootstrap.js");
var casper = require('casper').create({
verbose: true,
logLevel: 'debug'
});
casper.start().thenOpen('https://pi.pardot.com/api/login/version/3',{
method: 'post',
content: {
'text' : 'email=<myemail>&password=<password>&user_key=<userKey>'
}
}, function(response) {
this.echo(this.getHTML());
});
casper.run();
I can tell that it is getting through to the server because it is responding this.echo(this.getHTML()); "Login Failed" . I am using the right email/password/user_Key because i am pulling that from the API Console for pardot and it is working there.... So I believe the issue is I am not setting the body of the request correctly.
So does anyone know a way to set the body on the request?
casper.open() or casper.thenOpen() don't understand the content setting. You probably wanted to use data:
casper.start()
.thenOpen('https://pi.pardot.com/api/login/version/3', {
method: 'post',
data: 'email=<myemail>&password=<password>&user_key=<userKey>'
}, function() { ... });
Don't forget to use encodeURIComponent() on the email, password and user key parameters if you build the string yourself.
You can also pass an object:
casper.start()
.thenOpen('https://pi.pardot.com/api/login/version/3', {
method: 'post',
data: {
email: '<myemail>',
password: '<password>',
user_key: '<userKey>'
}
}, function() { ... });
If you expect something else than HTML from the API, then you should use casper.getPageContent() instead of casper.getHTML().
I got a piece of code which drives me insane.
I am loading some Data from the server which takes some time, therefore I would like to display a "loading-icon". But the icon is not showing up, so I debugged the code in Chrome and then it is working.
$(".k-loading-mask").show();
//loading the data from the server
var purchaseInvoiceItems = getOpenPurchaseInvoiceItems(id);
viewmodel.Items = ko.mapping.fromJS(purchaseInvoiceItems, {}, viewmodel.Items);
var prepaymentableOrders = getPrepaymentableOrders(id);
viewmodel.PrepaymentableOrders = ko.mapping.fromJS(prepaymentableOrders, {}, viewmodel.PrepaymentableOrders);
//loading done... hide the loading-icon.
$("div.k-loading-mask").hide();
EDIT:
function getOpenPurchaseInvoiceItems(id) {
var result = jQuery.ajax({
url: '/purchaseinvoices/getopenpurchaseinvoiceitems',
data: JSON.stringify({ supplierId: id }),
async: false,
type: 'POST',
contentType: "application/json"
});
var json = result.responseText;
var purchaseInvoiceItems = eval("(" + json + ")");
return purchaseInvoiceItems;
}
function getPrepaymentableOrders(id) {
var result = jQuery.ajax({
url: '/purchaseinvoices/getprepaymentableorders',
data: JSON.stringify({ supplierId: id }),
async: false,
type: 'POST',
contentType: "application/json"
});
var json = result.responseText;
var purchaseInvoiceItems = eval("(" + json + ")");
return purchaseInvoiceItems;
}
EDIT2
After refactoring the calls to async ajax I ran into the problem, that the done() of getOpenPurchaseInvoiceItems is never called. The done() of getPrepaymentableOrders is called when I call the function directly.
But Chrome Networkanalysis tells me the networktransaction is finished after ~3 seconds.
Maris answer is also not working for me, done() is never called.
function getOpenPurchaseInvoiceItems(id) {
$(".k-loading-mask").show();
jQuery.ajax({
url: '/purchaseinvoices/getopenpurchaseinvoiceitems',
data: JSON.stringify({ supplierId: id }),
type: 'POST',
contentType: "application/json"
}).done(function (data) { //This done is never called.
viewmodel.Items = ko.mapping.fromJS(data, {}, viewmodel.Items);
getPrepaymentableOrders(id);
});
}
//This one works like a charm when called directly
function getPrepaymentableOrders(id) {
jQuery.ajax({
url: '/purchaseinvoices/getprepaymentableorders',
data: JSON.stringify({ supplierId: id }),
type: 'POST',
contentType: "application/json",
}).done(function (data) {
viewmodel.PrepaymentableOrders = ko.mapping.fromJS(data, {}, viewmodel.PrepaymentableOrders);
$("div.k-loading-mask").hide();
});
}
EDIT 3
Added an error-callback, which actually gets fired.
status 200
statusText OK
responseText (The Json of the result-items)
I don't quiet get why the result has an error ...
Fun-Fact:
This works, and it seems that my predecessor had the same problems, because this code is a modified version of my predecessors code.
.error(function (data) {
var json = data.responseText;
var purchaseInvoiceItems = eval("(" + json + ")");
viewmodel.Items = ko.mapping.fromJS(purchaseInvoiceItems, {}, viewmodel.Items);
getPrepaymentableOrders(id);
});
Seems like the result cannot be parsed directly?!
Fiddler Response
HTTP/1.1 200 OK
Server: ASP.NET Development Server/11.0.0.0
Date: Mon, 28 Sep 2015 11:29:15 GMT
X-AspNet-Version: 4.0.30319
X-AspNetMvc-Version: 3.0
Cache-Control: private, s-maxage=0
Content-Type: application/json; charset=utf-8
Content-Length: 126537
Connection: Close
[{"GoodsReceiptItemId":311360,"PurchaseOrderNumber":"BE0010018","SupplierProductNumber":"205.00-122","ProductNumber":"205.00-122","SupplierDeliveryNumber":"5503","GoodsReceiptDate":new Date(1442527200000),"Description":"001-4631-00, \"L-A-EE\"","ShouldBePayed":false,"Amount":500.00000,"Price":2.66000,"PriceUnit":1.00000,"TotalPrice":1330.00000,"PurchaseOrderId":309360,"ProductId":4792,"GoodsReceiptId":299080,"Id":0,"HasBeenSaved":false,"Errors":{"Errors":[],"HasAnyError":false,"HasSumError":false},....]
Since in the javascript there is only one thread and you are running sync calls to the api, UI is getting freezed until the requests is done. That is why you don't see the loading bar at all. So, you have to use async calls and promises to achieve what you want.
The next code should work.
function getOpenPurchaseInvoiceItems(id) {
return $.post('/purchaseinvoices/getopenpurchaseinvoiceitems', { supplierId: id });
}
function getPrepaymentableOrders(id) {
return $.post('/purchaseinvoices/getprepaymentableorders', { supplierId: id });
}
$(".k-loading-mask").show();
//loading the data from the server
var purchaseInvoiceItemsPromise = getOpenPurchaseInvoiceItems(id);
var prepaymentableOrdersPromise = getPrepaymentableOrders(id);
$.when(purchaseInvoiceItemsPromise, prepaymentableOrdersPromise ).done(function(purchaseInvoiceItems, prepaymentableOrders){
viewmodel.Items = ko.mapping.fromJS(purchaseInvoiceItems, {}, viewmodel.Items);
viewmodel.PrepaymentableOrders = ko.mapping.fromJS(prepaymentableOrders, {}, viewmodel.PrepaymentableOrders);
$("div.k-loading-mask").hide();
})
Never use the synchronous ajax calls. If you for some reason want to use synchronous calls then you definitely doing something wrong.
Try using asynchronous calls, like so:
jQuery.ajax({
url: '/purchaseinvoices/getopenpurchaseinvoiceitems',
data: JSON.stringify({ supplierId: id }),
type: 'POST',
contentType: "application/json"
}).done(function(purchaseInvoiceItems){
//.....
})
PS: never use "eval". If you're getting JSON, and the headers say that it's JSON, jquery is smart enough to transform the result to the actual object.
If however you need to convert a JSON string to object, use JSON.parse
I have following code to pull data from server. I want to call it on document.ready(). And I expect first request is made to server, get response and second request is made and so on.
But I see in Firebug, there are two request to server is being made at initial page load. I am not sure why two request.
Here is my code.
;var EVENTS = {};
;(function($) {
EVENTS.Collector = {
events: [],
getEventsData: function() {
var postData = {
'jsonrpc': '2.0',
'id': RPC.callid(),
'method': "events.getNewOrUpdated",
'params': {},
'auth': RPC.auth()
};
var events_request = $.ajax({
url: RPC.rpcurl(),
contentType: 'application/json-rpc',
type: "POST",
data: JSON.stringify(postData),
timeout: 30000
});
events_request.done(function(results) {
//console.log("Info " + results);
if (results.result.result !== null) {
if (EVENTS.Collector.events.length !== 0) {
alert(EVENTS.Collector.events.length);
} else {
alert(EVENTS.Collector.events.length);
}
}
});
events_request.fail(function(results) {
//console.error("Error " + results);
$("Error Message").insertAfter('.error');
});
events_request.always($.proxy(this.getEventsData, this));
}
};
})(jQuery);
EVENTS.Collector.getEventsData(); //function call
Thanks in advance
If you remove the code below does it call at all?
EVENTS.Collector.getEventsData(); //function call
By default ajax request are asynchronous. If you want each request to be kind of "blocking" until done, then proceed to next, you can send sync request just by adding async: false to ajax call parameters.
Give a try to the following snippet, if it's what you meant to do..??.
var events_request = $.ajax({
url: RPC.rpcurl(),
contentType: 'application/json-rpc',
type: "POST",
async: false,
data: JSON.stringify(postData),
timeout: 30000
});
Consider that sync requests causes the interpreter function pointer to wait till any result come back from the call, or till request timeout.
I'm posting this JSON from a form page
<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.7.1/dojo/dojo.js" type="text/javascript"></script>
<script type="text/javascript">
function poster()
{
var dataToPost = {grant_type: "password", username: dojo.byId("username").value, password: dojo.byId("password").value, redirect_uri: "http://localhost/default.html"};
var xhrArgs =
{
url: "https://localhost/api/did/authenticate?client_id=12345",
handleAs: 'json',
postData: dojo.toJson(dataToPost),
headers: { "Content-Type": "application/json; charset=UTF-8", "Accept" : "application/json" },
load: function(data, args)
{
alert("Data = " + data);
},
error: function(error, args)
{
alert("Error! " + error);
}
}
dojo.rawXhrPost(xhrArgs);
}
</script>
But I'm not able to get the JSON results from said POST. How can I get those results? Please help. The data I get on the load function is null
The script at https://localhost/api/did/authenticate needs to print or echo or write or otherwise return the JSON as text as it exits.
Turns out that what I was trying to do is not possible in JavaScript since I'm trying to do it from one domain into another... so the cross-domain implementation is not possible, unless I use an embedded flash object, or a proxy pass in my server. thanks for the help though...