Thursday 3 March 2016

Encode and decode of string into both JavaScript and C#.

Hello dear,
I know there is few complication while using JavaScript to encode or decode instead doing
programming in C#, specially when you are much familiar with .net. But dont worry i am giving you a simple vise versa solution for encoding and decoding in both  java script and C#. We will also tell you how we can create our own rule to encode and decode in JavaScript with will be little terrible for few who want to understand your Js logic in client side.

Keywords which we are going to cover in this blog are:

In Javascript

  • unescape(_stringEncoded) : same as UrlDecode
  • escape(_setringDecoded) : same as UrlEncode
  • eval(_stringCode) : Execute blocks
  • String.fromCharCode(_intAscii) : input 16 output A
  • _string.charCodeAt(_index) : char at index


In C#

  1. HttpUtility.UrlDecode(_string) : decode string
  2. HttpUtility.UrlEncode(_string) : encode string


Demo:-

Encode / decode by Key
Simple Text
Encode

Decode

Encoded Text



escapeTxt / unescapeTxt
Simple Text
Encode

Decode


Complete Code in JavaScript and C# both

       
<%@ Page Title="" Language="C#" %>
<script runat="server">
    int encN = 1;
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Write(encodeText("raj", encN));
        Response.Write(decodeTxt("sbk%2631lvnbs1"));
        Response.Write(unescapeTxt(escapeTxt("RAJ kumar")));
    }

    public string encodeText(string inputstring, int key)
    {
        string outString = "";
        for (var i = 0; i < inputstring.Length; i++)
        {
            outString += ((char)(((int)inputstring[i]) + key)).ToString();
        }
        outString = outString + key;
        return outString;
    }

    string decodeTxt(string s)
    {
        var s1 = HttpUtility.UrlDecode(s.Substring(0, s.Length - 1));
        var t = "";
        for (int i = 0; i < s1.Length; i++) t += (char)((int)s1[i] - Convert.ToInt32(s.Substring(s.Length - 1, 1)));
        return HttpUtility.UrlDecode(t);
    }

    string escapeTxt(string os)
    {
        var ns = "";
        var t = "";
        var chr = "";
        var cc = "";
        var tn = "";
        for (int i = 0; i < 256; i++)
        {
            tn = Convert.ToUInt16(i.ToString()).ToString("X2");
            if (tn.Length < 2) tn = "0" + tn;
            cc += tn;
            chr += HttpUtility.UrlDecode('%' + tn);
        }
        cc = cc.ToUpper();
        os.Replace((char)13 + "", "%13");
        for (int q = 0; q < os.Length; q++)
        {
            t = os.Substring(q, 1);
            for (int i = 0; i < chr.Length; i++)
            {
                if (t == chr.Substring(i, 1))
                {
                    t = t.Replace(chr.Substring(i, 1), "%" + cc.Substring(i * 2, 2));
                    i = chr.Length;
                }
            }
            ns += t;
        }
        return ns;
    }


    string unescapeTxt(string s)
    {
        return HttpUtility.UrlDecode(s);
    }
        
</script>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Demo for encode and decode in javascript and c#</title>
    <script language="javascript">


        var encN = 1;

        // DECODES AND UNESCAPES ALL TEXT.
        function decodeTxt(s) {
            var s1 = unescape(s.substr(0, s.length - 1));
            var t = '';
            for (i = 0; i < s1.length; i++) t += String.fromCharCode(s1.charCodeAt(i) - s.substr(s.length - 1, 1));
            return unescape(t);
        }

        // ENCODES, IN UNICODE FORMAT, ALL TEXT AND THEN ESCAPES THE OUTPUT
        function encodeTxt(s) {
            console.log(encN);
            s = escape(s);
            var ta = new Array();
            for (i = 0; i < s.length; i++) ta[i] = s.charCodeAt(i) + encN;
            return "" + escape(eval("String.fromCharCode(" + ta + ")")) + encN;
        }


        // CONVERTS *ALL* CHARACTERS INTO ESCAPED VERSIONS.
        function escapeTxt(os) {
            var ns = '';
            var t;
            var chr = '';
            var cc = '';
            var tn = '';
            for (i = 0; i < 256; i++) {
                tn = i.toString(16);
                if (tn.length < 2) tn = "0" + tn;
                cc += tn;
                chr += unescape('%' + tn);
            }
            cc = cc.toUpperCase();
            os.replace(String.fromCharCode(13) + '', "%13");

            console.log(cc);
            console.log(chr);
            for (q = 0; q < os.length; q++) {
                t = os.substr(q, 1);
                for (i = 0; i < chr.length; i++) {
                    if (t == chr.substr(i, 1)) {
                        t = t.replace(chr.substr(i, 1), "%" + cc.substr(i * 2, 2));
                        i = chr.length;
                    }
                }
                ns += t;
            }
            return ns;
        }


        // SIMPLY UNESCAPES TEXT (ONLY INCLUDED TO MAKE A COMPLEMENTARY FUNCTION FOR escapeTxt()
        function unescapeTxt(s) {
            return unescape(s);
        }


    </script>

</head>
<body>


    <form name="en">

        <table>
            <caption>Encode / decode by Key</caption>
            <tr>
                <td>Simple Text<br />
                    <textarea id="txtforencode"></textarea>
                </td>
                <td>
                    <input type="button" value="encode" onclick="en.txtfordecode.value = encodeTxt(en.txtforencode.value)" />
                    <br />
                    <input type="button" value="decode" onclick="en.txtforencode.value = decodeTxt(en.txtfordecode.value)" />
                    <br />
                    <select name="key" onchange="encN= parseInt(en.key.options[en.key.selectedIndex].value)">
                        <option value="1">1</option>
                        <option value="2">2</option>
                        <option value="3">3</option>
                        <option value="4">4</option>
                        <option value="5">5</option>
                        <option value="5">6</option>
                        <option value="5">7</option>
                        <option value="5">8</option>
                        <option value="5">9</option>
                    </select>
                </td>
                <td>Encoded Text<br />
                    <textarea id="txtfordecode"></textarea>
                </td>

            </tr>
        </table>




        <br />
        <br />
        <br />


        <table>
            <caption>escapeTxt / unescapeTxt </caption>
            <tr>
                <td>Simple Text<br />

                    <textarea id="txtforencodes"></textarea>
                </td>
                <td>
                    <input type="button" value="encode" onclick="en.txtfordecodes.value = escapeTxt(en.txtforencodes.value)" />
                    <br />
                    <input type="button" value="decode" onclick="en.txtforencodes.value = unescapeTxt(en.txtfordecodes.value)" />
                </td>
                <td>
                    <textarea id="txtfordecodes"></textarea>
                </td>
        </table>

    </form>
</body>
</html>

 


Or else we can use simple Base64 conversion of string both available in c# and javascript

//Javascript code       
//Base64 conversion Firefox, Chrome, Safari, Opera and IE10+ can handle Base64 natively.
var string = 'Hello World!';
var encodedString = btoa(string); // Encode the String
console.log(encodedString); // Outputs: "SGVsbG8gV29ybGQh"
var decodedString = atob(encodedString); // Decode the String
console.log(decodedString); // Outputs: "Hello World!"
//Cross - BrowserBase64 conversion
var Base64 = { _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", encode: function (e) { var t = ""; var n, r, i, s, o, u, a; var f = 0; e = Base64._utf8_encode(e); while (f < e.length) { n = e.charCodeAt(f++); r = e.charCodeAt(f++); i = e.charCodeAt(f++); s = n >> 2; o = (n & 3) << 4 | r >> 4; u = (r & 15) << 2 | i >> 6; a = i & 63; if (isNaN(r)) { u = a = 64 } else if (isNaN(i)) { a = 64 } t = t + this._keyStr.charAt(s) + this._keyStr.charAt(o) + this._keyStr.charAt(u) + this._keyStr.charAt(a) } return t }, decode: function (e) { var t = ""; var n, r, i; var s, o, u, a; var f = 0; e = e.replace(/[^A-Za-z0-9\+\/\=]/g, ""); while (f < e.length) { s = this._keyStr.indexOf(e.charAt(f++)); o = this._keyStr.indexOf(e.charAt(f++)); u = this._keyStr.indexOf(e.charAt(f++)); a = this._keyStr.indexOf(e.charAt(f++)); n = s << 2 | o >> 4; r = (o & 15) << 4 | u >> 2; i = (u & 3) << 6 | a; t = t + String.fromCharCode(n); if (u != 64) { t = t + String.fromCharCode(r) } if (a != 64) { t = t + String.fromCharCode(i) } } t = Base64._utf8_decode(t); return t }, _utf8_encode: function (e) { e = e.replace(/\r\n/g, "\n"); var t = ""; for (var n = 0; n < e.length; n++) { var r = e.charCodeAt(n); if (r < 128) { t += String.fromCharCode(r) } else if (r > 127 && r < 2048) { t += String.fromCharCode(r >> 6 | 192); t += String.fromCharCode(r & 63 | 128) } else { t += String.fromCharCode(r >> 12 | 224); t += String.fromCharCode(r >> 6 & 63 | 128); t += String.fromCharCode(r & 63 | 128) } } return t }, _utf8_decode: function (e) { var t = ""; var n = 0; var r = c1 = c2 = 0; while (n < e.length) { r = e.charCodeAt(n); if (r < 128) { t += String.fromCharCode(r); n++ } else if (r > 191 && r < 224) { c2 = e.charCodeAt(n + 1); t += String.fromCharCode((r & 31) << 6 | c2 & 63); n += 2 } else { c2 = e.charCodeAt(n + 1); c3 = e.charCodeAt(n + 2); t += String.fromCharCode((r & 15) << 12 | (c2 & 63) << 6 | c3 & 63); n += 3 } } return t } }
var string = 'Hello World!'; // Define the string
var encodedString = Base64.encode(string);// Encode the String
console.log(encodedString); // Outputs: "SGVsbG8gV29ybGQh"
var decodedString = Base64.decode(encodedString);// Decode the String
console.log(decodedString); // Outputs: "Hello World!"







Tags:
encodeText() function in Javascript & C# both
decodeTxt() function in Javascript & C# both
escapeTxt() function in Javascript & C# both
unescapeTxt() function in Javascript & C# both