Ian W
Ian W

Reputation: 990

Simple Javascript Encryption that's safe for URL Querying

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

Upvotes: 0

Views: 4969

Answers (1)

Kapsonfire
Kapsonfire

Reputation: 1033

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"

Upvotes: 2

Related Questions