Simple Javascript Encryption that's safe for URL Querying

67
July 11, 2018, at 6:00 PM

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@,.-
Answer 1

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"
READ ALSO
My JS/JQuery Functionality Not working in Firefox, IE but working in chrome but not showing any error

My JS/JQuery Functionality Not working in Firefox, IE but working in chrome but not showing any error

My JS/JQuery functionality is not working in Firefox/IE but working just fine in chromeWhen opened in firefox it is working fine at first but after some functions it is not working and is showing no error in console

49
How to set data attribute with Jquery?

How to set data attribute with Jquery?

I am trying to change data-progress with jquery by

182
Disable multiple values in dropdowns based on another dropdown

Disable multiple values in dropdowns based on another dropdown

I want disable multiple values in the second and third dropdown based on first dropdown selected valuesI am able to do this for single selected value

69
How to compare two time picker using javascript or jquery

How to compare two time picker using javascript or jquery

I am using Time picker of AdminLTE, timeFrom field must not greater than or equal to timeTo Field, Code is something like this:

147