Artem's blog

Mainly .NET (C#, ASP.NET) and my projects

Archives for Programming Tips

Visual Basic – Language Syntax

This is my current presentation about Visual Basic that summarizes information from http://msdn.microsoft.com/en-us/library/ms172579.aspx.

Visual Basic Tutorial (download as .ppt)

Please notice that you might find other presentations at learning.clizware.net

A collapse-able menu

This tutorial will show you how to create a menu that can be opened and collapsed. First of all, you need to include a certain script that will do the entire thing.

// JScript source code

function showHide(objId) {
    var obj = document.getElementById(objId).style.display;

    if (obj == "inline") {
        hideObj(objId)
    }
    else {
        showObj(objId);
    }
}

function showObj(objId) {
    document.getElementById(objId).style.display = "inline";
}
function hideObj(objId) {
    document.getElementById(objId).style.display = "none";
}

Basically, it checks whether the object is collapsed or opened, and then does the oppsite; it collapses if it is open, and opens if it is collapsed. You might already now use the code above. By making a for example link (“a”), it will show and hide everytime you press it.

<a href="#" onClick="showHide('toShowOrHide');">Press to show or hide</a><br />
<div id="toShowOrHide" style="display:none">
It seems that it works!
</div>

We have a link that executes a command showHide with an argument toShowOrHide, which is, as you might see, the ID of the div. By entering the link, you will either open or collapse the div object. Remember, you might also use other tags/elements that are to be showed or hided. To see this code in work, go to http://editor.clizware.net/?id=8

Get Hash Code with Java Script

Once, I wrote about hash function that I improved. Though, that was C#. In this post I will show you how to get hash code with Java Script. (previous post)

function getStableHash(input,hashLength)
{
	/* Copyright (C) 2012 Artem Los,
	 * All rights reserved.
	 *
	 * code based on:
	 * http://blog.clizware.net/news/631
	 *
	 * originaly from: http://stackoverflow.com/questions/548158/fixed-length-numeric-hash-code-from-variable-length-string-in-c-sharp
	 */	

	 var _length = Math.pow(10,hashLength); //result in 10 numbers, if hashLength is 10
	 var hash = 0;

	 for (var j = 0; j < input.length; j++)
	 {
		 hash += input.charCodeAt(j);
		 hash += (hash << 10);
		 hash ^= (hash >> 6);
	 }

	 hash += (hash << 3);
	 hash ^= (hash >> 11);
	 hash += (hash << 15);

	 var result = ((hash % _length) + _length) % _length;//hash.mod(_length)

	 var check = parseInt(_length / result);
	 if (check > 1)
	 {
		 result *= check;
	 }

	 return result;
}

In order to calculate a hash value, you need to define two main variables. First of all, the string to calculate hash from (input), and eventually, the length of the result (hashLength). It is recommended that you set the hashLength to 8 or in some cases 10.

Please take a look at this code in work http://editor.clizware.net/?id=9

Hash code generator

Dear Readers,

The last time I have spent on the development of SKGL API, which is a library for those of you who want to secure, protect your hard-coded .NET application. I meanwhile, I have also spent sometime on a code, (basically half an hour), that produces hash code. It is not the best way of doing it, however, so it would be a pleasure to see another version of this code. Much appreciated!

        static string twentyfiveByteHash (string s)
        {
            int amountOfBlocks = s.Length / 5;
            string[] preHash = new string[amountOfBlocks];

            if (s.Length <= 5)
            {
                //if the input string is shorter than 5, no need of blocks!
                preHash[0] = GetStableHash(s).ToString ();
            }
            else if (s.Length > 5)
            {
                //if the input is more than 5, there is a need of dividing it into blocks.
                for (int i = 0; i < amountOfBlocks-1; i++)
                {
                    preHash[i] = GetStableHash (s.Substring(i*5,5)).ToString ();
                }
                preHash[preHash.Length-1] = GetStableHash (s.Substring((preHash.Length-1) * 5, s.Length - (preHash.Length - 1) * 5)).ToString ();

            }
            return String.Join ("",preHash);
        }

        static public int GetStableHash(string s)
        {
            /*
             * modification of code from:
             * http://stackoverflow.com/questions/548158/fixed-length-numeric-hash-code-from-variable-length-string-in-c-sharp
             *
             * modified by Artem Los
             *
             */
            const int MUST_BE_LESS_OR_EQUAL_TO = 100000000;
            uint hash = 0;

            foreach (byte b in System.Text.Encoding.Unicode.GetBytes(s))
            {
                hash += b;
                hash += (hash << 10);
                hash ^= (hash >> 6);
            }

            hash += (hash << 3);
            hash ^= (hash >> 11);
            hash += (hash << 15);

            int result = (int)(hash  % MUST_BE_LESS_OR_EQUAL_TO);
            int check = MUST_BE_LESS_OR_EQUAL_TO / result;

            if (check > 1)
            {
                result *= check;
            }

            return result;
        }

The right modulo

Recently, I’ve published an article here about the modular operator, and its defect. I’m not quite sure if the content is  hundred pro cents right, though. The previous post was about an encryption in Java Script, where I’ve used a certain function to get the modulo.

Number.prototype.mod = function(n) {
return ((this%n)+n)%n;
}

The prototype above is solving the entire problem. By writing a number, ex, “5.mod(3)” you will perform an modular operation 5 mod 3. The code itself is from http://javascript.about.com/od/problemsolving/a/modulobug.htm where you also might read more about that particular issue.

To see the code in work, please view this example: http://editor.clizware.net/?id=7

Tip of this weekend (25/2-12)

Another good method to encrypt ASCII based text. To view this example in work, http://editor.clizware.net/?id=7 (remember to press compile)

//Copyright (C) 2012 Artem Los, All rights reserved

function mod_c(text,key,enc_dec)
{
	//only for 128 ascii values
	if (key == "")
	{
		return "Error: no key given";
	}
	if (enc_dec === true)
	{
		var result = "";

		for (var i=0; i < text.length; i++)
		{
			result += String.fromCharCode( (text.charCodeAt(i) + key.charCodeAt(i % key.length)).mod(128)    );
		}
		return result;
	}
	else if(enc_dec === false)
	{
		var result = "";

		for (var i=0; i < text.length; i++)
		{
			result += String.fromCharCode( (text.charCodeAt(i) - key.charCodeAt(i % key.length)).mod(128)  );
		}
		return result;
	}
	else
	{
		return "Error: enc_dec is not given";
	}
}

Number.prototype.mod = function(n) {
return ((this%n)+n)%n;
}

Investigating mod

Almost all languages have operators. Example of these are, “+” – addition, “-” – subtraction, “*” – multiplication, “/” division. There are also more advanced operators such as “Mod”, “Exponent”, and “And”. Let us investigate the mod.

I have seen that there are much misunderstanding about mod. Some claims that it performs a modulo operation, some claims that it is the reminder. Actually it is a reminder, and not a modulo operation.

In this investigation, I chosen Visual Basic as the default language. So, let us try to use mod operation as a modulo operation.

'default mod, "reminder"
MsgBox(3 - 4 Mod 6) ' result is -1
MsgBox(-1 + 4 Mod 6) ' result is 3

I would like to add that there is no problem to get the same answer back, i.e., 3 -4 mod 6 is -1, and then by adding 4 and again mod, will result 3. However, that is not the modulo. To display the modulo, use the function below:

   Function mod_r(ByVal x As Integer, ByVal y As Integer) As Integer
        'the "real" modulo operation
        Return x - y * Int(x / y)
    End Function

In arrays, tables, indexes, where the index should be positive, we can use the function above.

        MsgBox(mod_r(3 - 4, 6)) ' result is 5
        MsgBox(mod_r(5 + 4, 6)) ' result is 3

Visual Studio 2012 is comming

 Visual Studio will soon be upgraded to a new version, 2012. It will be more integrated into the new Windows 8 operating system, with all designing features available in Windows. For designers, it will be more easier to only use XAML as a language for the UI. XAML is also integrated into other designing products of Microsoft, especially in Expression Blend. Visual Studio’s IDE is also changing a lot. Now, you will have the same designer features for all supported languages, for example, C#, C++, VB. XAML designer is a new designing tool that should make it easier to synchronize Visual Studio with Expression Blend.

Source:
http://channel9.msdn.com/Events/BUILD/BUILD2011/TOOL-504T

.NET Languages, etc.

Currently, I am reading about the CLR (common language runtime), and I will briefly describe it.

CLR ease the programming process for all languages that target CLR. Languages like Visual Basic, Visual C#, Visual F#, et cetera, targets CLR. Actually, these languages are only a subset of those possibilities that are available in CLR. That means that you might not be available to express your programming ideas through only one language, or, that others won’t be able to use your work, simply because of that. For example, if you’ve created a dynamic link library in the language C#, which is case-sensitive, where the functions can be so similar that one capital letter will separate them, i.e., “static void Hello”, “static void hello” or “static void HELLO” (c#-static. vb- shared member) it will work fine inside the C# environment. But outside, ex, when the function is to be called outside that environment, for example through Visual Basic, it may cause an exception. Note, that is also because of that the member is set to static/shared. If the member would be private or only accessible inside that assembly, everything would work fine. A great tip for all .NET developers is to always write in CLS (common language specification). Just include this peace of code in your assembly:

[assembly:CLSCompliant(true)]

That will always check your code and it will report when it does not follow the CLS.

Encrypting a website

EDIT: Please check out the updated version of this article.

When encrypting a website, we need to understand the way a browser interprets our input, i.e. html/javascript. In this case, we can produce code that is only readable by a browser.

There are several ways to encrypt a page, the main idea behind all methods is it to convert a human-readable code to ONLY computer-readable one.

    • By HTML only
    • By JavaScript
      • Using hexadecimal values
      • Using “escape/unescape”
      • Using an advanced algarithm

By HTML Only
In HTML, all letters(chars) can be written in a ASCII form, i.e., if we have a small “a” that is to be converted, we simply look up its ASCII value and write it instead of the actual char: &#97;, and so on.To sum up, the prefix is “&#”, then the ASCII code, and lastly a semicolon, “;”.

function encToASCII(_text)
{
	var _newText="";

	for(var i=0; i < _text.length;i++)
	{
		_newText += "&#" + _text.charCodeAt(i) + ";";
	}

	return _newText;
}

 

By JavaScript
JavaScript website encryption can be divided into several parts. One way is by using the hexadecimal value of a char, and write it instead of the actual char. We have to use JavaScript to perform this action, as it is shown below:

function encToHex(_text)
{
	var _newText="";
	for (var i=0; i < _text.length; i++)
	{
		_newText += "%" + decimalToHex(_text.charCodeAt(i));
	}
	return _newText;
}
function decimalToHex(_num)
{
	return _num.toString(16);
}

This method will only encrypt the given text, though, but, the user has to be able to see the encrypted text as a result (the browser won’t understand this code unless we have a function that will interpret it). This method is based on JavaScript, and we therefore need to use JavaScript to decrypt. Let us say that we encrypt “Hello World!”, which results “%48%65%6c%6c%6f%20%57%6f%72%6c%64%21”. As you might see, the prefix is “%”, and then the hexadecimal number. If the result above is our webpage, the source of that webpage should look similar to the example below:

<script type="text/javascript">
document.write(unescape("%48%65%6c%6c%6f%20%57%6f%72%6c%64%21"));
</script>
NOTE: There is a big difference between the HTML Only encryption and JavaScript encryption. For example, if you encrypt your whole page with HTML Only encryption, including “tags”, the result in the web-browser will be the source of the page. Encoding “<p>Hi</p>” will result “<p>Hi</p>”. However, by using JavaScript, the result will be executed, as a normal page would. Encoding “<p>Hi</p>” will result “Hi”.


There is also, as you might see, an opportunity to use functions escape and unescape as they are. Their actual usage is to encode/decode the url, i.e., replacing spaces, “special chars.” to url friendly one. All letters and numbers will stay the same, they will not be changed.

document.write(escape("Hello World!"));

The result you will get is Hello%20World%21. It replaces spaces with %20, and “!” with %21. Both of them are special characters(chars).

Unescape function will decode to a normal string.

document.write(unescape("Hello%20World%21"));

 

By JavaScript – Advanced algorithm
It took a while for me to define what an advanced algorithm in our case would be. I would say that the more advanced algorithm you have, the more time it takes to “crack it”. The method that will be described in this section of the post is my own little version of advanced algorithm. The method is using a logical operation, called XOR. If you already now what that is, jump to the next section.XOR is an operator, and works at a binary level. A definition in words is that the first or second value is true, but not both. Truth table shown below: 

Input Output
A B
0 0 0
0 1 1
1 0 1
1 1 0
XOR Truth table

An operation, 5 XOR 6, would result 3. The thing is, if we take either 5 XOR 3 = 6 or 6 XOR 3 = 5, we always return to our previous numbers. Conclusion, if two numbers are known, we always will get the third one.

As you might see, the decimal value 5 corresponds to 101; 6 corresponds to 110; 3 corresponds to 011.
1 0 1
1 1 0
1 1 0

By using XOR operation, we might, for instance, set a secret number, or a series of numbers, which always will return our third number. In this post, we will go though how to use a series of numbers, but also how to do it with only one number.

function en_doc(t,k)
{
	var a;
	var b;
	var r=new Array();
	for (var i=0; i<t.length ;i++)
	{
		a=t.charCodeAt(i);
		b=k.charAt(i%k.length);
		a^=b;
		r[i]=String.fromCharCode(a);
	}
	return r.join("");
}

The code shown above is my own advanced algorithm. First, we declare “a”, which is a char at certain place in string t; and b, which is a digit at certain place in k. The text to encrypt is placed in t (all chars), and the key to encrypt with is placed in k (only digits). The variable r is an array of the result/output.

First of all, we assign a to the char code at i. The variable b is then assigned to the char at i mod the length of key.

The reason why I put  a modular operation there is simple. If the key length we use is smaller than the text length, we will not be able to encrypt the whole string without it. When we are encrypting something, the key has to be of the same length as the text. By using a modular operation, even if the key is smaller than the text, it will be repeated. For example, if the key is 567 (key length=3), and the text length is 6, the output key will result 567567.

Secondly, an logical operation is executed. In other words, variable a equals to itself XOR b. Variable a has therefore a new value which is later assigned to r[i], i.e., a place in the array r which corresponds to the index value i.

Lastly, we join our array without some joining char, and that will be our encoded text. To decrypt, use the same function; place your encrypted text in t, and the key in k.

You can, however, remove this key opportunity, or as I previously defined it, using a key series,  to a single key digit. You might still use this method, but only having a key, for instance, 6, or, you might remove it at all, and set the secret digit inside the function.

If you want to include this code in your project without typing the code above, include this code before all scripts (see this code in action):

Source 1:

<script src="https://dev.clizware.net/lib/scrypto1.js"></script>

Source 2:

<script src="https://clizware.webs.com/lib/scrypto1.js"></script>

I hope this article was useful, and that you hopefully have learned something new! Below you find some useful links:

Encrypter – (for html only encryption)
http://www.iwebtool.com/html_encrypter – (encrypting to hexadecimal values, javascript)
Bitwise Operators – (about logical operators)
Escape and Unescape
Eval – (advanced encryption, etc.)

This article was revised 17.03.2013.

Page 3 of 4:« 1 2 3 4 »