简体   繁体   中英

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

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM