SyntaxError: Unexpected token V - javascript

I know this is a commonly asked question but I need to know theory wise, why this is happening?
I am trying to parse two encrypted values to my service.
Javascript
var encryptedlogin = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(Email), key,
{
keySize: 128 / 8,
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
var encryptedpassword = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(PasswordTwo), key,
{
keySize: 128 / 8,
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
var c = String(encryptedlogin);
var d = String(encryptedpassword);
var json = JSON.parse(c);
var json1 = JSON.parse(d);
$http.get("http://localhost:53101/TruckService.svc/validateUserA/" + json + '|' + json1 )
.success(function(data) {});
.error(function(data) {});

Try this:
var json = JSON.parse('"' + c + '"');
var json1 = JSON.parse('"' + d + '"');
JSON strings must be in double quotes
Why do you need to turn it into JSON?
By the look of your get request, you could just do:
$http.get("http://localhost:53101/TruckService.svc/validateUserA/" + encodeURIComponent(c + '|' + d))
.success(function(data) {});
.error(function(data) {});
Or your url may be in the format of
"http://localhost:53101/TruckService.svc/validateUserA/?parameterName=" + encodeURIComponent(c + '|' + d)

try to use
'/' instead of '|'
$http.get("http://localhost:53101/TruckService.svc/validateUserA/" + json + '/' + json1 )

Related

How to Generate and validate JWE in node js?

I tried the bellow code to create RSA-OAEP and A128GCM JWE generator and validator. it works with node js , ie, encrypt claims and generate the jwe and decrypt the same gives me the claims. but it is not working with the other clients , like nimbusds jose, jose4j. So for a sure I am missing something.
I am doing this by reading https://www.rfc-editor.org/rfc/rfc7516
index.js
var crypto = require('crypto');
var randomstring = require("randomstring");
var ursa = require("ursa");
var fs = require("fs");
var base64url = require('base64url');
var ascii = require("./ASCII");
var claims = {
firstName: "vimal"
};
var header = {
"enc": "A128GCM",
"alg": "RSA-OAEP"
};
var headerBase64Url = base64url.encode(JSON.stringify(header));
console.log("headerBase64Url : " + headerBase64Url);
console.log("headerBase64Url to UTF8 : " + base64url.decode(headerBase64Url));
var cek = randomstring.generate(16);
console.log("cek : " + cek);
var publicKey = ursa.createPublicKey(fs.readFileSync('./pubkey.pem'));
var encryptedKey = publicKey.encrypt(cek, 'utf8', 'base64');
console.log("encryptedKey : " + encryptedKey);
// var privateKey = ursa.createPrivateKey(fs.readFileSync('./privkey.pkc8.pem'));
// var decryptedKey = privateKey.decrypt(encryptedKey, "hex", "utf8");
// console.log("decryptedKey : " + decryptedKey);
var iv = randomstring.generate(12);
console.log("IV : " + iv);
var cipher = crypto.createCipheriv('aes-128-gcm', cek, iv);
cipher.setAAD(Buffer.from(ascii.toASCII(headerBase64Url)));
var chipherText = cipher.update(JSON.stringify(claims), "utf8", "base64");
chipherText += cipher.final('base64');
console.log("chipherText : " + chipherText);
var chipherTextAuthTag = cipher.getAuthTag().toString("base64");
console.log("chipherText Auth Tag : " + chipherTextAuthTag);
var jweToken = headerBase64Url + "." + base64url.encode(encryptedKey, "base64") + "." + base64url.encode(iv, "base64") + "." + base64url.encode(chipherText, "base64") +
"." + base64url.encode(chipherTextAuthTag, "base64");
console.log("jweToken : " + jweToken);
// decrypt
var jweTokenParts = jweToken.split(".");
var headerHex = base64url.decode(jweTokenParts[0]);
console.log(headerHex);
var encryptedKeyHex = base64url.decode(jweTokenParts[1], "base64");
console.log(encryptedKeyHex);
var ivHex = base64url.decode(jweTokenParts[2], "base64");
console.log(ivHex);
var chipperTextHex = base64url.decode(jweTokenParts[3], "base64");
console.log(chipperTextHex);
var chipherTextAuthTagHex = base64url.decode(jweTokenParts[4], "base64");
console.log(chipherTextAuthTagHex);
var privateKey = ursa.createPrivateKey(fs.readFileSync('./privkey.pkc8.pem'));
var decryptedKeyHex = privateKey.decrypt(encryptedKeyHex, "base64", "utf8");
console.log("decryptedKeyHex : " + decryptedKeyHex);
var dcipher = crypto.createDecipheriv('aes-128-gcm', decryptedKeyHex, iv);
dcipher.setAAD(Buffer.from(ascii.toASCII(jweTokenParts[0])));
dcipher.setAuthTag(Buffer.from(chipherTextAuthTagHex, "base64"));
var planText = dcipher.update(chipperTextHex, "base64", "utf8");
planText += dcipher.final('utf8');
console.log(planText);
ASCII.js
function toASCII(text) {
var ascii = "";
for (var f in text) {
ascii = ascii + text.charCodeAt(f);
}
return ascii;
}
module.exports = {
toASCII: toASCII
};
Generated public and private key using the below command
openssl genrsa -out ./privkey.pem 2048
openssl pkcs8 -topk8 -inform pem -in ./privkey.pem -outform pem -nocrypt -out ./privkey.pkc8.pem
openssl rsa -in ./privkey.pkc8.pem -pubout -out ./pubkey.pem
Please help me to fix this code.
This is my public key
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyT0HZHrlk8nN8HfTDq5t
dv6UCKHf7+RF1bICxaR4h2vzGCqcYUlzyW7Sp33BZAHDeO3d5tX26m7z2EOPaOPn
SSe6psgvBmE4Ivyc3+uyIYJm+Eo9bXiqqfvuDRidXsHj23w41l6GMERKbpOBVvp+
dmWt/cWU8FESvKUqNw/Au2R9mE1sQ5irMQj42hhUrVA1azs2AYpysKNZABm11YMb
/vd/xSPLsNqcDefuCs7j3CcT9xNLrMV6K63QjCAP+h0IMuA+ayi3WRUbl04D6cAC
AC97/cKMC0YLRumbf5x5/KjUBwNlzgRA3/n9KE+YjJ9Rs9dtiGnlg+c70Kgx4hm9
9QIDAQAB
-----END PUBLIC KEY-----
Generated JWE
eyJlbmMiOiJBMTI4R0NNIiwiYWxnIjoiUlNBLU9BRVAifQ.A_KMJqfr6FZSoejRGWPsZKMCNZmPyaWoNvpG6KMRpqyv7Alb8Ui5ELWLjpcaemjNM8EFU8d4-Yzz8jRRZ5TpK2pEEc4NXfDLcnj2b0-38_-P-0HbW1YyMkkGMVXIpJDYMo8vKgVHIBj0pNlzgF7xmxLFWZlJlXmYzXi4QZcig5HezHg7AAQB7U2HYry25cQDYam60747gRCH372NaSm_dfRCNvH8copVXqiJGNs6xhslxMt_LopnZt9iIcAC9o7m0FPdnu_0Ui_w0jp5OUam8i0v8k6SSajBvXSedtUENxcehPGRSFYzi8KqZ53u4CpRygir84wNFRTi7zmLV6TlVw.84xgyx6TTI8I.4zTt1fI1XCbvxW2L-pH8_Mfp_ySF.EPmpEHiMYAvA2nqz9M0v5Q
It looks like the IV is not correctly encoded using Base64 Url.
On my computer, when I execute the following line of code:
console.log(iv);
console.log(base64url.encode(iv, "base64"));
Then the two lines are identical.
When I modify your code:
var jweToken = headerBase64Url + "." + base64url.encode(encryptedKey, "base64") + "." + base64url.encode(iv, "base64") + "." + base64url.encode(chipherText, "base64") +
"." + base64url.encode(chipherTextAuthTag, "base64");
lnto these lines:
var bufferedIV = new Buffer(iv);
var jweToken = headerBase64Url + "." + base64url.encode(encryptedKey, "base64") + "." + base64url.encode(bufferedIV, "base64") + "." + base64url.encode(chipherText, "base64") +
"." + base64url.encode(chipherTextAuthTag, "base64");
Then it works fine ; I can load the resulting JWE using my PHP library.
From my understanding, the error comes from the base64url dependency that does not correctly encode the IV.

Python Javascript CryptoJS

I am looking for a module that I can use in both python & javascript so that can encrypt something in python then decrypt in javascript if I pass in a key (and vice versa).
So far I've checked out SlowAES and CryptoJS, but cant find any good documentation or examples. Is anyone able to help?
Below is my attempt to get this working:
JS:
var encoded_message = 'MTAxMTEyMTMxNDE1MTYxN2asfw3LtCtoL+mvWtJsIVSVCsvZdBIvZWWRuKEI85nd';
var my_iv = CryptoJS.enc.Base64.parse('1011121314151617');
var my_key = CryptoJS.enc.Base64.parse('824601be6c2941fabe7fe256d4d5a2b7');
console.log('my iv [' + my_iv + ']');
console.log('my key [' + my_key + ']');
console.log('my enc message [' + encoded_message + ']');
var data = CryptoJS.AES.decrypt(encoded_message, my_key, { iv: my_iv, mode: CryptoJS.mode.CBC });
console.log(data);
var dec = CryptoJS.enc.Hex.stringify(data);
console.log('data [' + dec + ']');
var encoded_message = CryptoJS.enc.Base64.parse('MTAxMTEyMTMxNDE1MTYxN2asfw3LtCtoL+mvWtJsIVSVCsvZdBIvZWWRuKEI85nd');
console.log('\n\n\n');
console.log('message [' + encoded_message + ']');
Python:
import os, random, struct
from Crypto.Cipher import AES
from Crypto import Random
import base64
class AESCipher:
def __init__(self, key):
BS = 16
self.pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
self.unpad = lambda s : s[0:-ord(s[-1])]
self.key = self.pad(key[0:16])
def encrypt(self, raw):
raw = self.pad(raw)
iv = "1011121314151617"
cipher = AES.new(self.key, AES.MODE_CBC, iv)
return base64.b64encode(iv + cipher.encrypt(raw))
def decrypt(self, enc):
enc = enc.replace(' ', '+')
enc = base64.b64decode(enc)
iv = enc[:16]
cipher = AES.new(self.key, AES.MODE_CBC, iv)
return self.unpad(cipher.decrypt(enc[16:]))
def main():
message = 'this is my new message'
print message[:16]
cipher = AESCipher('824601be6c2941fabe7fe256d4d5a2b7')
encrypteddata = cipher.encrypt('work you bloody thing!')
print encrypteddata
decryptdata =cipher.decrypt(encrypteddata)
print decryptdata
main()
I've recently been using sjcl in Javascript,..
http://bitwiseshiftleft.github.io/sjcl/
They also appears to be a python compatible version.
https://pypi.python.org/pypi/sjcl
At it's simplest you can just do ->
sjcl.encrypt("password", "data")
and
sjcl.decrypt("password", "encrypted-data")
But you still can do low level stuff with it too.

How to split the String in Javascript

I have a string [{"Latitude":8.55701,"Longitude":76.880934},{"Latitude":8.55701,"Longitude":76.880935},{"Latitude":8.55701,"Longitude":76.880935}]
I want output as [{8.55701,76.880934},..etc] only numbers.
This is a JSON string -
<script type="text/javascript">
var myVar = ' <%= request.getAttribute("Map") %>'; /* retrieve json from request attribute */
var result = myVar.split(',',2);
var latitude = parseFloat(result[0].replace('"Latitude":',''));
var longitude = parseFloat(result[1].split(':'));
alert(latitude);
</script>
I have tried but not getting it.
Use simple Regular expression to remove the strings:
.replace(/\"\w+\":/g, '');
'[{"Latitude":8.55701,"Longitude":76.880934},{"Latitude":8.55701,"Longitude":76.880935},{"Latitude":8.55701,"Longitude":76.880935}]'.replace(/\"\w+\":/g, '');
And if you want to get the values you can use JSON.parse:
var coords = JSON.parse('[{"Latitude":8.55701,"Longitude":76.880934},{"Latitude":8.55701,"Longitude":76.880935},{"Latitude":8.55701,"Longitude":76.880935}]');
// And loop
coords.forEach(function(coord) {
console.log('latitude', coord.Latitude);
console.log('longitude', coord.Longitude);
});
try this, this function will return a string as you expected out put.
function pareseJSONStr(str){
var json = JSON.parse(str);
var rslt = [];
json.forEach(function(obj){
rslt.push("{" + obj.Latitude + ", " + obj.Longitude + "}");
});
return "[" + rslt.join(",") + "]"
}
call this function as
var mystr = '[{"Latitude":8.55701,"Longitude":76.880934},{"Latitude":8.55701,"Longitude":76.880935},{"Latitude":8.55701,"Longitude":76.880935}]';
pareseStr(mystr);
returns a string
"[{8.55701, 76.880934},{8.55701, 76.880935},{8.55701, 76.880935}]"
If you really want your strange data format just use it:
var convertStrange = function( string ) {
return '[' + JSON.parse( string ).map( function( item ) {
return '{' + [ item.Latitude, item.Longitude ].join( ',' ) + '}';
} ).join( ',' ) + ']';
};
So,
convertStrange('[{"Latitude":8.55701,"Longitude":76.880934},{"Latitude":8.55701,"Longitude":76.880935},{"Latitude":8.55701,"Longitude":76.880935}]')
will return string
[{8.55701,76.880934},{8.55701,76.880935},{8.55701,76.880935}]
{8.55701,76.880934}
is wrong object construction. Objects must be name:value pairs so it can only be
{name1:8.55701, name2:76.880934}
or you can use an array like
[[8.55701, 76.880934], ... ]
if you want it as a string use this;
var string = '[{"Latitude":8.55701,"Longitude":76.880934}, {"Latitude":8.55701,"Longitude":76.880935}, {"Latitude":8.55701,"Longitude":76.880935}]';
var newString = string.replace(/\"Latitude\":|\"Longitude\":/g, "");

How to get back the original string after decompressing - Zlib

I am trying to compress and decompress the string using Zlib. Here is the JS file I'm using to compress and decompress.
Compression code:
compress_string = function () {
var string = document.getElementById("input_value").value;
var deflate = new Zlib.Deflate(string);
var compressed = deflate.compress();
var b64encoded = btoa(String.fromCharCode.apply(null, compressed));
var elem = document.getElementById("input_value");
elem.value = b64encoded;
var elemLabel = document.getElementById("zlsize");
elemLabel.value = ("Size of sample is: " + string.length) + " " + ("Compressed Value: " + b64encoded + " Size: " + b64encoded.length);
}
After compressing I'm setting the compressed value back to the input_value text field.
Decompression Code:
decompress_string = function () {
var string = document.getElementById("input_value").value;
var compressData = new Uint8Array(atob(string).split("").map(function(c) { return c.charCodeAt(0); }))
var inflate = new Zlib.Inflate(compressData);
var plain = inflate.decompress();
var elem = document.getElementById("input_value");
elem.value = btoa(plain);
var elemLabel = document.getElementById("zlsize");
elemLabel.value = ("Size of compressed string is: " + string.length) + " " + ("Decompressed Value: " + plain + " Size: " + plain.length);
}
I'm trying to compress below sample string:
<xml><username>myusername</username><password>mypassword</password></xml>
Size of sample is: 73
Compressed Value: eJxNibEJAAAMg/7/OjoEdCjGAoAnmqg6fF8T7QMfCxxR
Size: 44
When trying to decompress the above compressed string, I'm getting an object of Uint8Array as below:
Size of compressed string is: 44
Decompressed Value: [object Uint8Array]
Size: 70
While trying to convert the object Uint8Array to string using btoa(), the output is like below:
W29iamVjdCBVaW50OEFycmF5XQ==
Question: How to get the original string?
Your problem is text encoding.
Uint8Array is a binary representation of something, and strings can be written in many formats. You need to stick to one, and convert using that.
I've chosen UTF-8 in this example, using this library
function compress(input){
var binaryconverter = new TextEncoder('utf-8');
var binary = binaryconverter.encode(input);
var deflate = new Zlib.Deflate(binary);
var compressed = deflate.compress();
return btoa(String.fromCharCode.apply(null, compressed));
}
function decompress(b64encoded){
var compressed = new Uint8Array(atob(b64encoded).split("").map(function(c){return c.charCodeAt(0);}));
var inflate = new Zlib.Inflate(compressed);
var binary = inflate.decompress();
var binaryconverter = new TextDecoder('utf-8');
return binaryconverter.decode(binary);
}
var input = '<xml><username>myusername</username><password>mypassword</password></xml>';
var b64encoded = compress(input);
var output = decompress(b64encoded);
alert(output);
So, when encoding, I first convert the string to the binary representation of the text in UTF-8 format, then I'm using ZLib to compress, and then again this is converted to a base64 string for ease of transfer.
To decompress, you do the inverse thing: first decode the base64 string, then ZLib to inflate and finally again we convert binary to string using UTF-8
Documentation zlib.js appear to suggest plain (input) of type Array.<number> or Uint8Array
// plain = Array.<number> or Uint8Array
var deflate = new Zlib.Deflate(plain);
var compressed = deflate.compress();
at OP , var string appear to be type string , see
var string = document.getElementById("input_value").value;
var deflate = new Zlib.Deflate(string);
To retrieve the text value from compressed , base64 formatted string , below ; first , map var string to .charCodeAt() number , returning array of numbers representing text characters ; second , push .charCodeAt() numbers to map array ; third, call window.btoa(encodeURIComponent(escape(compressed[i]))) on each item within array of charCodeAt() values , pushed to same map array; fourth , decode base64encoded string in for loop , calling String.fromCharCode(plain[i]) on decompressed Uint8Array , returning original input string.
Try
var elem = document.getElementById("input_value")
, elemLabel = document.getElementById("zlsize")
, compress = document.getElementById("compress")
, decompress = document.getElementById("decompress")
, b64map = []
, _b64encoded
, b64encoded
, _string
, string
, _plain
, compressData;
function compress_string () {
string = elem.value;
_string = [].slice.call(string).map(function (value, key) {
return value.charCodeAt(0)
});
var deflate = new Zlib.Deflate(_string);
var compressed = deflate.compress();
for (var i = 0; i < compressed.length; i++) {
b64map.push([compressed[i]
, window.btoa(encodeURIComponent(escape(compressed[i])))])
};
_b64encoded = b64map.map(function (value, key) {
return value[1]
});
b64encoded = _b64encoded.join("");
elem.value = b64encoded;
elemLabel.innerText = ("Size of sample is: "
+ string.length) + " " + ("Compressed Value: "
+ b64encoded + " Size: " + b64encoded.length)
};
function decompress_string () {
string = elem.value;
elem.value = "";
compressData = _b64encoded.map(function (value, key) {
return new RegExp(value).test(string) ? b64map[key][0] : null
});
compressData = new Uint8Array(compressData);
var inflate = new Zlib.Inflate(compressData);
var plain = inflate.decompress();
b64map = b64encoded = [];
_plain = "";
for (var i = 0; i < plain.length; i++) {
_plain += String.fromCharCode(plain[i])
};
elem.value = _plain;
elemLabel.innerText = ("Size of compressed string is: "
+ elem.value.length) + " "
+ ("Decompressed Value: " + _plain + " Size: "
+ _plain.length);
};
compress.addEventListener("click", compress_string);
decompress.addEventListener("click", decompress_string);
jsfiddle http://jsfiddle.net/guest271314/ov6nwLak/
$.getScript("https://raw.githubusercontent.com/imaya/zlib.js/master/bin/zlib.min.js")
var elem = document.getElementById("input_value")
, elemLabel = document.getElementById("zlsize")
, compress = document.getElementById("compress")
, decompress = document.getElementById("decompress")
, b64map = []
, _b64encoded
, b64encoded
, _string
, string
, _plain
, compressData;
elem.value = "<xml><username>myusername</username><password>mypassword</password></xml>";
function compress_string () {
string = elem.value;
_string = [].slice.call(string).map(function (value, key) {
return value.charCodeAt(0)
});
var deflate = new Zlib.Deflate(_string);
var compressed = deflate.compress();
for (var i = 0; i < compressed.length; i++) {
b64map.push([compressed[i]
, window.btoa(encodeURIComponent(escape(compressed[i])))])
};
_b64encoded = b64map.map(function (value, key) {
return value[1]
});
b64encoded = _b64encoded.join("");
elem.value = b64encoded;
elemLabel.innerText = ("Size of sample is: "
+ string.length) + " " + ("Compressed Value: "
+ b64encoded + " Size: " + b64encoded.length)
};
function decompress_string () {
string = elem.value;
elem.value = "";
compressData = _b64encoded.map(function (value, key) {
return new RegExp(value).test(string) ? b64map[key][0] : null
});
compressData = new Uint8Array(compressData);
var inflate = new Zlib.Inflate(compressData);
var plain = inflate.decompress();
b64map = b64encoded = [];
_plain = "";
for (var i = 0; i < plain.length; i++) {
_plain += String.fromCharCode(plain[i])
};
elem.value = _plain;
elemLabel.innerText = ("Size of compressed string is: "
+ elem.value.length) + " "
+ ("Decompressed Value: " + _plain + " Size: " +
_plain.length);
};
compress.addEventListener("click", compress_string);
decompress.addEventListener("click", decompress_string);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="input_value" />
<button id="compress">compress</button>
<button id="decompress">decompress</button>
<br />
<label id="zlsize"></label>

Elfinder 2.0 decode filename

$("#elfinder").elfinder({
url: 'https://localhost/elfinder',
handlers: {
dblclick: function(event, elfinderInstance) {
var file = event.data.file; //l1_dGVzdC9iYW5uZXJfYmdfaG9yaXpvbnRhbC5qcGc
}
}
});
How to decrypt l1_dGVzdC9iYW5uZXJfYmdfaG9yaXpvbnRhbC5qcGc into banner_bg_horizontal.jpg (real filename) ?
For elFinder you'll need to modify the base64 keyStr values + / = to - _ .
var keyStr = "ABCDEFGHIJKLMNOP" +
"QRSTUVWXYZabcdef" +
"ghijklmnopqrstuv" +
"wxyz0123456789+/" +
"=";
change to...
var keyStr = "ABCDEFGHIJKLMNOP" +
"QRSTUVWXYZabcdef" +
"ghijklmnopqrstuv" +
"wxyz0123456789-_" +
".";
then strip the prefix "l1_" before decoding
because you do not use Base64
I use it and it works well
example Base64

Categories