0

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

1 Answer 1

2

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"
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Kapsonfire! Can't believe I overlooked this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.