Simple Javascript Encryption that's safe for URL Querying - javascript

I want to write a simple encryption function that will encrypt the input text and produce a decryptable output that is also safe to transport over a URL query as a parameter.
This site provides an excellent starting point, however, some of the outputs contain '=' and '?' which would not play nice when sent as a parameter in a query. Code reproduced below:
var jsEncode = {
encode: function(s, k) {
var enc = "";
var str = "";
// make sure that input is string
str = s.toString();
for (var i = 0; i < s.length; i++) {
// create block
var a = s.charCodeAt(i);
// bitwise XOR
var b = a ^ k;
enc = enc + String.fromCharCode(b);
}
return enc;
}
};
var code = '1';
var e = jsEncode.encode("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789#,.-", code);
console.log(e);
var d = jsEncode.encode(e, code);
console.log(d);
I won't be able to use any external libraries, only vanilla js.
The inputs would only ever be email and thus these are the only characters I need to worry about:
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789#,.-

encodeURIComponent() should be your desired function
see more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
// encodes characters such as ?,=,/,&,:
console.log(encodeURIComponent('?x=шеллы'));
// expected output: "%3Fx%3D%D1%88%D0%B5%D0%BB%D0%BB%D1%8B"
console.log(encodeURIComponent('?x=test'));
// expected output: "%3Fx%3Dtest"

Related

IN Javascript, replace all after second existence of a character or replace all between two characters

javascript, what is the best way to replace following two scenario.
It is possible to use replace and add regex to do this, if yes, how?
I want to convert "aaa.bbb.ccc" TO "aaa.bbb.*"
I want to convert "aaa.bbb.ccc.ddd.eee" TO "aaa.bbb.*.ddd.*"
var map = 'qwertyuiopasdfghjklzxcvbnm'.split('');
var rand = function(){
var len = map.length,
arr = [],
i;
for (i = 0; i < 3; i++){
arr.push(map[Math.floor(Math.random()*len)]);
}
return arr.join('');
};
var randStr = [rand(), rand()];
/* ASSUME above code is how you get random string */
var string = 'aaa.bbb.' + randStr[0] + '.ddd.' + randStr[1];
// use new RegExp() to parse string as regular expression
var regexp = new RegExp(randStr[0] + '|' + randStr[1], 'gi');
console.log(string.replace(regexp, '*'));
Read more about new RegExp() here (easy one), here (detailed one) and here (working example).
You should be able to apply this concept in your code now.

javascript - Break search query string into object

I am trying to build api query in client side by breaking the user input in search field into object.
Example,
Search query
arg1:"2 words" business corporate arg2:val2
Desired value
{
arg1: "2 words",
arg2: "val2",
extra: "business corporate"
}
I tried doing this.
var query = initquery.split(' ');
var obj = {};
for(var i=0; i<query.length; i++){
var s = query[i].split(':');
if(s.length == 2) {
initquery = initquery.replace(query[i], '');
obj[s[0]] = s[1];
}
}
obj.extra = initquery;
This does not handle string in quotes.
You may want to take a look at this:
addEventListener('load', function(){
var wtf = 'arg1:"2 words" business corporate arg2:val2 arg3:"fixedIt"';
function customObj(string){
var a = string.split(/\s+(?!\w+")/), x = [], o = {};
for(var i=0,s,k,l=a.length; i<l; i++){
s = a[i].split(/:/); k = s[0];
s[1] ? o[k] = s[1].replace(/"/g, '') : x.push(k);
}
o['extra'] = x.join(' ');
return o;
}
console.log(customObj(wtf));
});
Thanks to #Barmar for this helpful comment, I came up with this regex to catch the args (assuming they are followed by a single digit number and a colon):
var pattern = /((^|\s)arg\d:").*?(?=")"?|(\sarg\d:\w*)/g;
Extracting the rest of the query can be done through:
query.replace(pattern,"");
And then creating the final object should be straightforward. Still, given the complexities that could rise from sprinkling double quotes in the query string, you should consider writing a parser for your application.
UPDATE:
Updated the regex to match beginning of the string and only match arg after white space character.

;How encode string like \x31, etc?

i saw a code and that code had all string in a array.. And each array index was like: "\x31\x32\x33", etc..
How i can convert for example "hello" to that encode format?
if is possible, there a online encoder?
As the #nikjohn said, you can decoded the string by console.log.
And the following code I found from this question. And I made some changes, the output string will be in a \x48 \x65 form.
It will convert the string in a hex coding, and each character will be separated by a space:
String.prototype.hexEncode = function(){
var hex, i;
var result = "";
for (i=0; i<this.length; i++) {
hex = this.charCodeAt(i).toString(16);
result += ("\\x"+hex).slice(-4) + " ";
}
return result;
};
var str = "Hello";
console.log(str.hexEncode());
The result of the above code is \x48 \x65 \x6c \x6c \x6f。
It is an hex coding encoding.
www.unphp.net
http://ddecode.com/hexdecoder/
http://string-functions.com/hex-string.aspx
are the few sites that can give you encoding and decoding using hex coding.
If you console log the string sequence, you get the decoded strings. So it's as simple as
console.log('\x31\x32\x33'); // 123
For encoding said string, you can extend the String prototype:
String.prototype.hexEncode = function(){
var hex, i;
var result = "";
for (i=0; i<this.length; i++) {
hex = this.charCodeAt(i).toString(16);
result += ("\\x"+hex).slice(-4);
}
return result
}
Now,
var a = 'hello';
a.hexEncode(); //\x68\x65\x6c\x6c\x6f

Replace multiple strings with Javascript

I'm trying to transform this string
.jpg,.gif,.png
into this (not dots and space after comma)
jpg, gif, png
I thought that something like PHP's str_replace for arrays in JS will do the trick, so I found this post, and specifically this answer. I tried it but is't not working as expected. I'm getting a blank string... Am I doing something wrong?
JS
String.prototype.replaceArray = function(find, replace)
{
var replaceString = this;
var regex;
for (var i = 0; i < find.length; i++)
{
regex = new RegExp(find[i], "g");
replaceString = replaceString.replace(regex, replace[i]);
}
return replaceString;
};
var my_string = ".jpg,.gif,.png";
alert(my_string.replaceArray([".", ","],["", ", "]));
Link to jsfiddle
The first thing you're trying to replace is a period ("."), which is a regular expression for any character. You need to escape it: "\\."
I just did this:
var target = '.jpg,.gif,.png';
target = target.replace(/\\./g, '');
target = target.replace(/,/g, ', ');
I'm sure it can be done more efficiently, but this will get the job done.
You can change your fn to this :
function strToArr(str)
{
var res = str.replace(/\./g, "");
return res.split(",");
}

How to parse a url using Javascript and Regular Expression?

I want to parse some urls's which have the following format :-
var url ="http://www.example.com/cooks/cooking-dress-wine/~no-order/pr?p%5B%5D=sort%3Dfeatured&sid=bks%2C43p&mycracker=ch_vn_clothing_subcategory_Puma&ref=b41c8097-8efe-4acf-8919-0fa81bcb590a"
Its not necessary that the domain name and other parts would be same for all url's, they can vary i.e I am looking at a general solution.
Basically I want to strip off all the other things and get only the part:
/cooks/cooking-dress-wine/~no-order/pr?p%5B%5D=sort%3Dfeatured&sid=bks%2C43p
I thought to parse this using JavaScript and Regular Expression
I am doing like this:
var mapObj = {"/^(http:\/\/)?.*?\//":"","(&mycracker.+)":"","(&ref.+)":""};
var re = new RegExp(Object.keys(mapObj).join("|"),"gi");
url = url.replace(re, function(matched){
return mapObj[matched];
});
But its returning this
http://www.example.com/cooks/cooking-dress-wine/~no-order/pr?p%5B%5D=sort%3Dfeatured&sid=bks%2C43pundefined
Where am I not doing the correct thing? Or is there another approach with an even easier solution?
You can use :
/(?:https?:\/\/[^\/]*)(\/.*?)(?=\&mycracker)/
Code :
var s="http://www.example.com/cooks/cooking-dress-wine/~no-order/pr?p%5B%5D=sort%3Dfeatured&sid=bks%2C43p&mycracker=ch_vn_clothing_subcategory_Puma&ref=b41c8097-8efe-4acf-8919-0fa81bcb590a";
var ss=/(?:https?:\/\/[^\/]*)(\/.*?)(?=\&mycracker)/;
console.log(s.match(ss)[1]);
Demo
Fiddle Demo
Explanation :
Why don't you just map a split array?
You don't quite need to regex the URL, but you will have to run an if statement inside the loop to remove specific GET params from them. In this particular case (key word particular) you just have to substring till the indexOf "&mycracker"
var url ="http://www.example.com/cooks/cooking-dress-wine/~no-order/pr?p%5B%5D=sort%3Dfeatured&sid=bks%2C43p&mycracker=ch_vn_clothing_subcategory_Puma&ref=b41c8097-8efe-4acf-8919-0fa81bcb590a"
var x = url.split("/");
var y = [];
x.map(function(data,index) { if (index >= 3) y.push(data); });
var path = "/"+y.join("/");
path = path.substring(0,path.indexOf("&mycracker"));
Change the following code a little bit and you can retrieve any parameter:
var url = "http://www.example.com/cooks/cooking-dress-wine/~no-order/pr?p%5B%5D=sort%3Dfeatured&sid=bks%2C43p&mycracker=ch_vn_clothing_subcategory_Puma&ref=b41c8097-8efe-4acf-8919-0fa81bcb590a"
var re = new RegExp(/http:\/\/[^?]+/);
var part1 = url.match(re);
var remain = url.replace(re, '');
//alert('Part1: ' + part1);
var rf = remain.split('&');
// alert('Part2: ' + rf);
var part2 = '';
for (var i = 0; i < rf.length; i++)
if (rf[i].match(/(p%5B%5D|sid)=/))
part2 += rf[i] + '&';
part2 = part2.replace(/&$/, '');
//alert(part2)
url = part1 + part2;
alert(url);
var url ="http://www.example.com/cooks/cooking-dress-wine/~no-order/pr?p%5B%5D=sort%3Dfeatured&sid=bks%2C43p&mycracker=ch_vn_clothing_subcategory_Puma&ref=b41c8097-8efe-4acf-8919-0fa81bcb590a";
var newAddr = url.substr(22,url.length);
// newAddr == "/cooks/cooking-dress-wine/~no-order/pr?p%5B%5D=sort%3Dfeatured&sid=bks%2C43p&mycracker=ch_vn_clothing_subcategory_Puma&ref=b41c8097-8efe-4acf-8919-0fa81bcb590a"
22 is where to start slicing up the string.
url.length is how much of it to include.
This works as long as the domain name remains the same on the links.

Categories