CryptoJS in Adobe Extendscript (ES3): Decrypting String Does Not Work - json

I'm working on a Photoshop CES extension and attempting to encrypt data using CryptoJS. This all works, except when I convert the encrypted data to a string and then try to decrypt it.
Here's a link to a JS Fiddle that works:
https://jsfiddle.net/davevsdave/atwpbmr5/3/
This same code in ExtendScript Toolkit or running in Photoshop does not return the correct finalResult var. Here's the code I'm running in extendscript, identical to what is in the above JSFiddle (except $.println instead of console.log and an extra line showing that decrypting the obj works):
//JSON from Panel
jsonStr = '{"date":"1563662582633","email":"email#email.com","password":"1234324","uniqueID1":"12345","uniqueID2":"asfdsa-asdfsa-adsfas-sadfsdf-asfsaf\n"}';
//JSON from Panel
jsonStr = '{"date":"1563662582633","email":"email#email.com","password":"1234324","uniqueID1":"12345","uniqueID2":"asfdsa-asdfsa-adsfas-sadfsdf-asfsaf\n"}';
//Encrypt Data
var encrypted = CryptoJS.AES.encrypt(jsonStr, 'secret_passcode');
//Convert OBJ to String so I can save it
var encryptedString = encrypted.toString();
$.writeln('encryptedString is ' + encryptedString);
//Decrypt string - DOES NOT WORK IN EXTENDSCRIPT
var decryptedValue1= CryptoJS.AES.decrypt(encryptedString, 'secret_passcode');
$.writeln('decryptedValue1 is ' + decryptedValue1);
//Decrypt OBJ - WORKS IN EXTENDSCRIPT
var decryptedValue2= CryptoJS.AES.decrypt(encrypted, 'secret_passcode');
$.writeln('decryptedValue2 is ' + decryptedValue2);
//Final Decrypt output from string
$.writeln('finalOutput from decryptedValue1 is ' + decryptedValue1.toString(CryptoJS.enc.Utf8));
//Final Decrypt output from obj
$.writeln('finalOutput from decryptedValue2 is ' + decryptedValue2.toString(CryptoJS.enc.Utf8));
I'm guessing the issue is Extendscript using ES3. Any suggestions on how I can convert the encrypted data to a string (so I can store it as JSON) and then still be able to decrypt it? Obviously being able to store data I can't decrypt does me no good.
Thanks!

Related

How do I get data from this json field?

How are you doing?
I'm trying to get data from a json to show on a screen that should be like the image below. I'm able to get most of the data, except for one field coded as String which consists of the image and a description like this one:
"lessonText": "{\"ops\":[{\"insert\":{\"image\":\"data:image/jpeg;base64,(IMAGE CODE HERE)=\"}},{\"attributes\":{\"color\":\"#444444\"},\"insert\":\"(LESSON TEXT HERE)\"},{\"insert\":\"\\n\"}]}",
How do I extract data from here? I have tried to convert this to a Map but it is not working.
Thanks for the help!
Something in line with this should give you the image
// json string containing the base64 image string
String jsonString = "{\"ops\":[{\"insert\":{\"image\":\"data:image/png;base64,(IMAGE CODE HERE)=\"}},{\"attributes\":{\"color\":\"#444444\"},\"insert\":\"(LESSON TEXT HERE)\"},{\"insert\":\"\\n\"}]}";
// convert the string to a map structure
Map<String, dynamic> json = jsonDecode(jsonString);
// extract the image string
String imageString = json['ops'][0]['insert']['image'];
// extract the base64 string
var prefix = "data:image/png;base64,";
var imageBase64String = imageString.substring(prefix.length);
// decode the base 64 string
var bytes = base64Decode(imageBase64String);
// build the image widget from bytes
var imageWidget = Image.memory(bytes);
As I mentioned in the comments, use a combination of decoding the base64 string to bytes and then loading the image from memory. See the the relevant documentation for base64Decode and Image.memory. If you would like a full code sample just let me know and I would be happy to throw one together.
Note: you should run the base64Decode method asynchronously, as it may take some time to decode an entire image (especially on lower-end hardware).

How to extract string from JSON object in protractor

I am not able to extract string from JSON object in protractor in webstorm. I want value of statusCode i.e :200, The code I've tried for this mentioned below...
CODE IS :
console.log('body is :' + JSON.stringify(body));
var jsonResponse = JSON.stringify(response);
console.log('---------response is: '+ jsonResponse);
var statusResponse = jsonResponse.getString("statusCode");
console.log('---- statusResponse is :'+ statusResponse.toString());
OUTPUT IS:
body is :{"oBody":{"payLoad":{"sLoginId":"HDB_TW_DSA#softcell.com","iInstId":4019,"sFirstName":"PRIYANKA","sLastName":"MADGUNDI","sEmail":"priyanka#softcell.com","sEmpId":"HDB18458","sMobile":"8237276692","bActive":true,"aRoles":["DSA"],"aDealers":[{"id":"TW423684019","iInstId":4019,"iDlrId":"42368","sDlrName":"GODSPEED MOTORCYCLE PVT LTD","iBranchId":1278,"sBranchName":"HYDERABAD-SF","sProduct":"TW","bActive":true},{"oStatus":{"iStatus":200,"sStatus":"OK"}}
---------response is:
{"statusCode":200,"body":{"oBody":{"payLoad":{"sLoginId":"HDB_TW_DSA#softcell.com","iInstId":4019,"sFirstName":"PRIYANKA","sLastName":"MADGUNDI","sEmail":"priyanka#softcell.com","sEmpId":"HDB18458","sMobile":"8237276692","bActive":true,"aRoles":["DSA"],"aDealers","path":"/gonogo-api/atm/login-web-v3","href":"https://ssg.serviceurl.in/login-web-v3"},"method":"POST","headers":{"Postman-Token":"7aad048f-f8ad-4765-a0b8-be3b3a485ab6","cache-control":"no-cache","Content-Type":"application/json","accept":"application/json","content-length":380}}}
Try the below option
var res= JSON.parse(response);
console.log(res[0].statusCode);
Hope it helps you
So it appears what jsonResponse is giving you from the stringifying is not recognized as perfect json by json parse. So you can do the parsing yourself by finding where it says "statusCode:", taking the response string from a space beyond that for as long as statusCode could be and then some (8 characters seemed plenty to me), then taking only up to the comma. I assumed you want the code as a number, not a string, so I converted it.
var temp =jsonResponse.search('"statusCode":')+'"statusCode":'.length;
var temp2 = jsonResponse.slice(temp,temp+8);
var status = parseInt(temp2.slice(0,temp2.search(',')),10);

Filter JSON data arduino

I am trying to filter JSON data with my Arduin (working with an ESP8266).
This is what I have :
if (httpCode > 0) {
// Parsing
const size_t bufferSize = JSON_OBJECT_SIZE(2) + JSON_OBJECT_SIZE(3) + JSON_OBJECT_SIZE(5) + JSON_OBJECT_SIZE(8) + 370;
DynamicJsonBuffer jsonBuffer(bufferSize);
JsonObject& root = jsonBuffer.parseObject(http.getString());
// Parameters
int id = root["Reismogelijkheid"];
const char* departure = root["ActueleVertrekTijd"];
// Output to serial monitor
Serial.print("Vertrijktijd:");
Serial.println(departure);
}
I can make connection to my wifi network and I can make connection to the website to get JSON data from here : http://hendriks.pm/ns.php but I want to filter the data and only get the ActueleVertrekTijd, so that I can store it in a const and that I can see it on my Serial monitor.
I tried to use this example : https://www.instructables.com/id/ESP8266-Parsing-JSON/ but that didn't worked for me.
This is the Json :
Hello and welcome to Stackoverflow,
The problem is that you dont traverse trough the JSON.
If you want to retreive a value of an Object you should use
root["Reismogelijkheid"]["ActueleVertrekTijd"]
or if it is consistent:
root["Reismogelijkheid"][5]
instead of
root["Reismogelijkheid"]
This will give you the value that you want.
EDIT
For more information about parsing JSON you can use this site:
https://randomnerdtutorials.com/decoding-and-encoding-json-with-arduino-or-esp8266/

Importing CSV file in MVC and converting it in JSON using C#

I am importing .CSV file from an angular app into MVC and i am able to get the files like this
Int32 strLen, strRead;
System.IO.Stream stream = Request.InputStream;
strLen = Convert.ToInt32(stream.Length);
byte[] strArr = new byte[strLen];
strRead = stream.Read(strArr, 0, strLen);
here the files which is being imported is converted into byte[] because i am reading the file using
System.IO.Stream stream = Request.InputStream
Then i convert it into string like this
string a = System.Text.Encoding.UTF8.GetString(strArr);
and try to split the content and retrieve the data but it becomes very complex, i wonder if there is any alternate way for it. In a simple .CSV file like this
I get the result after converting the byte[] to string like this
and once i apply logic for splitting the string and retrieving the data, the logic gets very messy like this
Is there any efficinet way where i can convert the imported .CSV file to JSON
Save stream as text file in to the TEMP folder.
Use any parcer for working with CSV file. (Example FileHelpers)
Use any Json helper to convert it to the output format. (Example: newtonsoft)
You can use Cinchoo ETL - an open source library, to convert CSV to JSON easily.
using (var parser = new ChoCSVReader("IgnoreLineFile1.csv")
.WithField("PolicyNumber", 1)
.WithField("VinNumber", 2)
.Configure(c => c.IgnoreEmptyLine = true)
.Configure(c => c.ColumnCountStrict = true)
)
{
using (var writer = new ChoJSONWriter("ignoreLineFile1.json")
.WithField("PolicyNumber", fieldName: "Policy Number")
.WithField("VinNumber", fieldName: "Vin Number")
)
writer.Write(parser.Skip(1));
}
In above, you can pass stream to the reader and writer as well for your requirement.
Hope this will help.
Disclaimer: I'm the author of this library.

Facing issue in creating dynamic objects from JSON

I am working on the requirement where a User can fetch the data from production box and insert it into developer sandbox by just giving production URL and creds. I am able to fetch data but somehow not able to convert the JSON to required object type. As I am newbie in Salesforce please don't mind for basic questions.
Below is the working logic and issue:
for(DataMigrationNAP__c d : dataMigrationNAP) // this loop will give all NAP object names and its corresponding fields like {'Account','Name,Phone,Id'},{'Opportunity', 'ID,Name, blah,blah'}...
{
final PageReference theUrl = new PageReference(SERVER_URL + '/services/data/v22.0/query/');
String soql = 'Select '+d.NAPObjectFields__c+' From '+d.Name+' a limit ' + recordCount;
theUrl.getParameters().put('q',soql);
request = new HttpRequest();
request.setEndpoint(theUrl.getUrl());
request.setMethod('GET');
request.setHeader('Authorization', 'OAuth ' + SESSION_ID);
String body = (new Http()).send(request).getBody();
JSONParser parser = JSON.createParser(body);
do{
parser.nextToken();
}while(parser.hasCurrentToken() && !'records'.equals(parser.getCurrentName()));
parser.nextToken();
String typeName = 'List<' + d.Name + '>';
Type t = Type.forName(typeName);
List<sobject> acc1 = (List<sobject>) parser.readValueAs(t);
insert acc1;
System.debug('Values inserted : ' + acc1);
}
Through above logic I am trying to fetch the data Object by Object and insert it into dev sandbox, I am able to fetch perfectly in JSON but not able to convert from JSON to required object. The issue is I can't hardcode Object or Type name because it will be a list of objects. Please let me know if you need any other detail and thanks in advance. Open for any other approach as well but it should be through apex coding only.
Have you tried JSON2Apex already, if not than this could be good candidate.