Tuesday, June 30, 2015

Monday, June 29, 2015

Code for Damerau Lavenshtein Distance in Java

Earlier I had posted a tutorial on Fuzzy String Matching with Python Code. Here in this post I am sharing the Damerau Lavenshtein Algorithm Code in Java.

package com.codehackersblog.editdistance;

/**
*
* @author psychocoder
* @version 1.0
*/
public class DamerauLavenshtein {

    private String s1;
    private String s2;
    private int len_s1;
    private int len_s2;

    public DamerauLavenshtein() {
        s1 = null;
        s2 = null;
    }

    public DamerauLavenshtein(String s1, String s2) {
        this.s1 = s1.toLowerCase();
        this.s2 = s2.toLowerCase();
    }

    private void putValue(String m, String n) {
        s1 = m.toLowerCase();
        s2 = n.toLowerCase();
    }

    private int getMinimum(int a, int b, int c) {
        return Math.min(a, Math.min(b, c));
    }

    private int getDamerauLavenshtein() {

        len_s1 = s1.length();
        len_s2 = s2.length();

        int[][] d = new int[len_s1 + 1][len_s2 + 1];
        int i, j, cost;

        if (len_s1 == 0) {
            return len_s2;
        }

        if (len_s2 == 0) {
            return len_s1;
        }

        for (i = 0; i <= len_s1; i++) {
            d[i][0] = i;
        }

        for (j = 0; j <= len_s2; j++) {
            d[0][j] = j;
        }

        for (i = 1; i <= len_s1; i++) {
            for (j = 1; j <= len_s2; j++) {
                if (s1.charAt(i - 1) == s2.charAt(j - 1)) {
                    cost = 0;
                } else {
                    cost = 1;
                }

                d[i][j] = getMinimum(
                        d[i - 1][j] + 1, /*Deletion*/
                        d[i][j - 1] + 1, /*Insertion*/
                        d[i - 1][j - 1] + cost /*Substitution*/
                );

                if (i > 1 && j > 1 && s1.charAt(i - 1) == s2.charAt(j - 1)
                        && s2.charAt(j - 1) == s1.charAt(i - 1)) {
                    d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + cost);  /*transposition*/

                }
            }
        }

        return d[len_s1][len_s2];
    }

    private int getDamerauLavenshtein(String s1, String s2) {

        s1 = s1.toLowerCase();
        s2 = s2.toLowerCase();

        len_s1 = s1.length();
        len_s2 = s2.length();

        int[][] d = new int[len_s1 + 1][len_s2 + 1];
        int i, j, cost;

        for (i = 0; i <= len_s1; i++) {
            d[i][0] = i;
        }

        for (j = 0; j <= len_s2; j++) {
            d[0][j] = j;
        }

        for (i = 1; i <= len_s1; i++) {
            for (j = 1; j <= len_s2; j++) {
                if (s1.charAt(i - 1) == s2.charAt(j - 1)) {
                    cost = 0;
                } else {
                    cost = 1;
                }

                d[i][j] = getMinimum(
                        d[i - 1][j] + 1, /*Deletion*/
                        d[i][j - 1] + 1, /*Insertion*/
                        d[i - 1][j - 1] + cost /*Substitution*/
                );

                if (i > 1 && j > 1 && s1.charAt(i - 1) == s2.charAt(j - 1)
                        && s2.charAt(j - 1) == s1.charAt(i - 1)) {
                    d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + cost);  /*transposition*/

                }
            }
        }

        return d[len_s1][len_s2];

    }

    public static void main(String... args) {
        DamerauLavenshtein ob = new DamerauLavenshtein("Ludo", "lludo");
        System.out.println(ob.getDamerauLavenshtein());
        System.out.println(ob.getDamerauLavenshtein("Hello", "olhel"));
    }

}

Continue Reading →

Code for Wagner Fisher Algorithm in Java

Earlier I had posted a tutorial on Fuzzy String Matching with Python Code. Here in this post I am sharing the Wagner Fisher Algorithm Code in Java.

package com.codehackersblog.editdistance;

/**
*
* @author psychocoder
* @version 1.0
*/
public class WagnerFisher {

    private String s1;
    private String s2;
    private int len_s1;
    private int len_s2;

    public WagnerFisher() {
        s1 = null;
        s2 = null;
    }

    public WagnerFisher(String s1, String s2) {
        this.s1 = s1.toLowerCase();
        this.s2 = s2.toLowerCase();
    }

    private void putValue(String m, String n) {
        s1 = m.toLowerCase();
        s2 = n.toLowerCase();
    }

    private int getMinimum(int a, int b, int c) {
        return Math.min(a, Math.min(b, c));
    }

    private int getWagnerFisher() {

        len_s1 = s1.length();
        len_s2 = s2.length();

        int[][] d = new int[len_s1 + 1][len_s2 + 1];
        int i, j, cost;

        for (i = 0; i <= len_s1; i++) {
            d[i][0] = i;
        }

        for (j = 0; j <= len_s2; j++) {
            d[0][j] = j;
        }

        for (i = 1; i <= len_s1; i++) {
            for (j = 1; j <= len_s2; j++) {
                if (s1.charAt(i - 1) == s2.charAt(j - 1)) {
                    d[i][j] = d[i - 1][j - 1];
                } else {

                    d[i][j] = getMinimum(
                            d[i - 1][j] + 1, /*Deletion*/
                            d[i][j - 1] + 1, /*Insertion*/
                            d[i - 1][j - 1] + 1 /*Substitution*/
                    );
                }
            }
        }

        return d[len_s1][len_s2];
    }

    private int getWagnerFisher(String s1, String s2) {

        s1 = s1.toLowerCase();
        s2 = s2.toLowerCase();

        len_s1 = s1.length();
        len_s2 = s2.length();

        int[][] d = new int[len_s1 + 1][len_s2 + 1];
        int i, j, cost;

        for (i = 0; i <= len_s1; i++) {
            d[i][0] = i;
        }

        for (j = 0; j <= len_s2; j++) {
            d[0][j] = j;
        }

        for (i = 1; i <= len_s1; i++) {
            for (j = 1; j <= len_s2; j++) {
                if (s1.charAt(i - 1) == s2.charAt(j - 1)) {
                    d[i][j] = d[i - 1][j - 1];
                } else {

                    d[i][j] = getMinimum(
                            d[i - 1][j] + 1, /*Deletion*/
                            d[i][j - 1] + 1, /*Insertion*/
                            d[i - 1][j - 1] + 1 /*Substitution*/
                    );
                }
            }
        }

        return d[len_s1][len_s2];

    }

    public static void main(String... args) {
        WagnerFisher ob = new WagnerFisher("loookes", "looks");
        System.out.println(ob.getWagnerFisher());
        ob.putValue("Hiya", "Hey");
        System.out.println(ob.getWagnerFisher());
        System.out.println(ob.getWagnerFisher("Hello", "Heoll"));
    }

}

Continue Reading →

Sunday, June 28, 2015

C Code for Longest Common Subsequence Using Dynamic Programming

Here's the C Code for LCS using Dynamic programming :-


Output:-
Output:-

Matrix Generated

0 |0 |0 |0 |0 |
0 |0 |0 |0 |0 |
0 |1 |1 |1 |1 |
0 |1 |2 |2 |2 |
0 |1 |2 |3 |3 |
0 |1 |2 |3 |4 |

Length of Longest Common Subsequence = 4

Continue Reading →

Saturday, June 27, 2015

C Code for Knapsack Problem using Dynamic Programming

Knapsack problem
Knapsack problem (Photo credit: Wikipedia)
Knapsack Problem using Dynamic Programming.

Code:-


Sample Output:- 

Enter the number of elements : 3
Enter the profit and weights of the elements
Item no : 1
4 6
Item no : 2
1 2
Item no : 3
7 3
Enter the capacity
7
Items in the KnapSack are :
Sl.no    weight          profit
----------------------------------------
1        2                1
2        3                7
Total profit = 8
Continue Reading →

Friday, June 26, 2015

Bouncing Ball Animation using Processing.js



Today I made the old school Bouncing Ball Animation using Processing.js

Here's the code with output :-




Continue Reading →

Introduction to Public Key Cryptography and RSA Encryption

Cryptographically secure pseudorandom number g...
Cryptographically secure pseudorandom number generator (Photo credit: Wikipedia)
Cryptography

The art of protecting information by transforming it (encrypting it) into an unreadable format, called cipher text. Only those who possess a secret key can decipher (or decrypt) the message into plain text. Encrypted messages can sometimes be broken by cryptanalysis, also called code breaking, although modern cryptography techniques are virtually unbreakable.

Cryptography systems can be broadly classified into:-

1. Symmetric-key Cryptography(or Secret Key Cryptography):-systems that use a single key that both the sender and recipient have.

2. Public-key Cryptography:-systems that use two keys, a public key known to everyone and a private key that only the recipient of messages uses.

3. Hash Functions: Uses a mathematical transformation to irreversibly "encrypt" information

See the Picture below :-

[Image: crypto_types.gif]

Today I will discuss with you Public Key Cryptography by taking RSA Encryption as an example:-

Public-Key Cryptography(PKC)

Public-key cryptography has been said to be the most significant new development in cryptography.Modern PKC was first described publicly by Stanford University professor Martin Hellman and graduate student Whitfield Diffie in 1976. Their paper described a two-key crypto system in which two parties could engage in a secure communication over a non-secure communications channel without having to share a secret key.

PKC depends upon the existence of so-called one-way functions, or mathematical functions that are easy to compute whereas their inverse function is relatively difficult to compute. Let me give you two simple examples:

Multiplication vs. factorization: Suppose I tell you that I have two prime numbers, 3 and 7, and that I want to calculate the product; it should take almost no time to calculate that value, which is 21. Now suppose, instead, that I tell you that I have a number, 21, and I need you tell me which pair of prime numbers I multiplied together to obtain that number. You will eventually come up with the solution but whereas calculating the product took milliseconds, factoring will take longer. The problem becomes much harder if I start with primes that have 400 digits or so, because the product will have ~800 digits.

Exponentiation vs. logarithms: Suppose I tell you that I want to take the number 3 to the 6th power; again, it is relatively easy to calculate 36 = 729. But if I tell you that I have the number 729 and want you to tell me the two integers that I used, x and y so that logx 729 = y, it will take you longer to find the two values.
While the examples above are trivial, they do represent two of the functional pairs that are used with PKC; namely, the ease of multiplication and exponentiation versus the relative difficulty of factoring and calculating logarithms, respectively. The mathematical "trick" in PKC is to find a trap door in the one-way function so that the inverse calculation becomes easy given knowledge of some item of information.

Generic PKC employs two keys that are mathematically related although knowledge of one key does not allow someone to easily determine the other key. One key is used to encrypt the plaintext and the other key is used to decrypt the ciphertext. The important point here is that it does not matter which key is applied first, but that both keys are required for the process to work (Figure 1B). Because a pair of keys are required, this approach is also called asymmetric cryptography.

In PKC, one of the keys is designated the public key and may be advertised as widely as the owner wants. The other key is designated the private key and is never revealed to another party. It is straight forward to send messages under this scheme. Suppose Alice wants to send Bob a message. Alice encrypts some information using Bob's public key; Bob decrypts the ciphertext using his private key. This method could be also used to prove who sent a message; Alice, for example, could encrypt some plaintext with her private key; when Bob decrypts using Alice's public key, he knows that Alice sent the message and Alice cannot deny having sent the message.

Examples of PKC :-
  • RSA
  • Diffie-Hellman
  • Digital Signature Algorithm(DSA)
  • Elliptic Curve Cryptography (ECC)
  • ElGamal

RSA

The first, and still most common, PKC implementation, named for the three MIT mathematicians who developed it — Ronald Rivest, Adi Shamir, and Leonard Adleman. RSA today is used in hundreds of software products and can be used for key exchange, digital signatures, or encryption of small blocks of data. RSA uses a variable size encryption block and a variable size key. The key-pair is derived from a very large number, n, that is the product of two prime numbers chosen according to special rules; these primes may be 100 or more digits in length each, yielding an n with roughly twice as many digits as the prime factors. The public key information includes n and a derivative of one of the factors of n; an attacker cannot determine the prime factors of n (and, therefore, the private key) from this information alone and that is what makes the RSA algorithm so secure.

Algorithm of RSA:-

To generate the encryption and decryption keys, we can

proceed as follows.

1. Generate randomly two “large” primes 'p' and 'q'.

2. Compute 'n' = pq and 'φ' = (p − 1)*(q − 1).

3. Choose a number 'e' so that gcd(e, φ) = 1.

4. Find the multiplicative inverse of 'e' modulo 'φ', i.e., find d so that
    e*d ≡ 1 (mod φ).

This can be done efficiently using Euclid’s Ex-tended Algorithm.

The encryption public key is KE = (n, e) and the decryption private key is KD = (n, d).

The encryption function is :- E(M ) = M^e mod n.
The decryption function is :- D(M ) = M^d mod n.
These functions satisfy D(E(M )) = M and E(D(M )) = M ,for any 0 ≤ M < n.
 

Now Let's take an example which will clear the facts :-

P = 61 <- first prime number (destroy this after computing E and D)
Q = 53 <- second prime number (destroy this after computing E and D)
PQ = 3233 <- modulus (give this to others)
E = 17 <- public exponent (give this to others)
D = 2753 <- private exponent (keep this secret!)


Your public key is (E,PQ).
Your private key is D.

The encryption function is:

encrypt(T) = (T^E) mod PQ = (T^17) mod 3233

The decryption function is:

decrypt(C) = (C^D) mod PQ= (C^2753) mod 3233

To encrypt the plaintext value 123, we do this:

encrypt(123) = (123^17) mod 3233 = 337587917446653715596592958817679803 mod 3233 = 855

To decrypt the ciphertext value 855, we do this:

decrypt(855) = (855^2753) mod 3233= 123

One way to compute the value of 855^2753 mod 3233 is like this:

2753 = 101011000001 base 2,
therefore, 2753 = 1 + 2^6 + 2^7 + 2^9 + 2^11= 1 + 64 + 128 + 512 + 2048

Consider this table of powers of 855:

855^1 = 855 (mod 3233)
855^2 = 367 (mod 3233)
855^4 = 367^2 (mod 3233) = 2136 (mod 3233)
855^8 = 2136^2 (mod 3233) = 733 (mod 3233)
855^16 = 733^2 (mod 3233) = 611 (mod 3233)
855^32 = 611^2 (mod 3233) = 1526 (mod 3233)
855^64 = 1526^2 (mod 3233) = 916 (mod 3233)
855^128 = 916^2 (mod 3233) = 1709 (mod 3233)
855^256 = 1709^2 (mod 3233) = 1282 (mod 3233)
855^512 = 1282^2 (mod 3233) = 1160 (mod 3233)
855^1024 = 1160^2 (mod 3233) = 672 (mod 3233)
855^2048 = 672^2 (mod 3233) = 2197 (mod 3233)


Given the above, we can do like this:

855^2753 (mod 3233)
= 855^(1 + 64 + 128 + 512 + 2048) (mod 3233)
= 855^1 * 855^64 * 855^128 * 855^512 * 855^2048 (mod 3233)
= 855 * 916 * 1709 * 1160 * 2197 (mod 3233)
= 794 * 1709 * 1160 * 2197 (mod 3233)
= 2319 * 1160 * 2197 (mod 3233)
= 184 * 2197 (mod 3233)
= 123 (mod 3233)
= 123



References :

http://www.garykessler.net/library/crypto.html
http://plansoft.org/wp-content/uploads/knowledge/inne/RSA.pdf


Thank You. Hope you like this tutorial. Share it among your friends :)


Continue Reading →

Thursday, June 25, 2015

5 Most Funny Java Videos on Youtube

Duke, the Java Mascot, in the waving pose. Duk...
Duke, the Java Mascot. (Photo credit: Wikipedia)
I found some really funny Java videos which are to be taken as jokes and for humour. If you have known Java then you will surely like these videos. I made a collection of them. So lets get started.

5. The Funny JavaRap

Lets with a little funny JavaRap.


4. The Java Heist

An old man thinks f*cking Technology sucks. Well he had put his hopes too high on his plan of action but ended up loving Java and Technology, "This is fucking Brilliant"


3. Java v/s .NET, Java Forever and Ever Movie

Nothing more to say. Watch the video and laugh your arse off :D



2. Javapocalypse and The dawn of Javatar

The world thinks Java is "A Virus" since it is less secure. But when Java was shut down. The inevitable Apocalypse soon took place. Now the Javatar is world last Hope.


1. Game of Codes

Its a Game of Thrones clone for Java. The following video is at the of my list.




Continue Reading →

SecurityOverride.org Software Cracking Level 1 | Basic Serial Disclosure

SecurityOverride.org is an Information Security related site, which provides security enthusiast a platform to communicate, share this ideas, views, exploits, research, and also contains several Hacking or Security challenges which judges your skills at different levels.

A few days back I stumbled upon this site (Not for first time) and decided to sign up. After that I straight away went to the challenges section and solved a few of them and picked an interest. So in this I will be sharing how I solved the Level 1 of Software cracking challenge.

Spoilers and Excitement Alert :- People who wish to solve it of their own do not proceed any further and go straight to some other threads.


========XXX Line of Interest XXX ========

Level 1 : A software program is given in compressed .rar archive format and you're required to crack it and get the password.

Step 1 : Know Your Target.

To learn and gather more information about the format of the executable should be known, also to execute the program and see the kind of task it requires us to perform to get the data. The application should be run in a sandboxed environment for security and privacy purpose.

To understand the format and specification of the PE file specially PEiD Signature I used a tool named PortExAnalyzer made by our very own and loved Deque.


I downloaded Sandboxie, a software application which runs programs in a sandboxed environment. You can download Sandboxie from here [~ 6.6 MB]:- http://www.sandboxie.com/SandboxieInstall.exe

After you can installed Sandboxie open the application  inside the archive downloaded from the SecurityOverride site.

It looks something like this :-

[Image: clLGHSK.png]

Step 2 : Research and Reverse Engineer

Now after we have a had a look at how the main program looks like its time to derive conclusion based on facts and results. On a visual level we first notice at the icon of the PE which denotes the application is made with some .NET language, but you can't be sure. Why ? because the icon could have been changed or fuzzed in order to confuse you. So its better to cross verify. Now we analyse the PE using PortEx we downloaded earlier. Following is the trace log created when I use it on the PE.

C:\Users\Psycho\Desktop>java -jar PortexAnalyzer.jar -o PortEx-Report-SL1.txt "Software Level 1.exe"
PortEx Analyzer

Creating report file...
Writing header reports...
Writing section reports...
Writing analysis reports...
Done!

C:\Users\Psycho\Desktop>

The report has been saved with the filename "PortEx-Report-SL1.txt". Open and see if you find something interesting.

Alternatively, we can extract the sections we are interested in and that is CodeView and PEiD Signature. You can use the above but I prefer writing a code to get what I need to know rather than the complete report. So I wrote the following code in Java using Deque's PortEx Library to get the sections we are interested in :-

package com.rawcoders.REStuffs;

import java.io.File;
import java.io.IOException;
import java.util.List;

import com.github.katjahahn.parser.PEData;
import com.github.katjahahn.parser.PELoader;
import com.github.katjahahn.parser.sections.SectionLoader;
import com.github.katjahahn.parser.sections.debug.DebugSection;
import com.github.katjahahn.tools.sigscanner.SignatureScanner;

/**
*
* @author Psycho_Coder 
*
*/
public class SoScL1 {

    public static void main(String[] args) throws IOException {
        File pefile = new File("C:\\Users\\Psycho\\Desktop\\Software Level 1.exe");
        
        /*
         * Get PE Signature.
         */            
        SignatureScanner scanner = SignatureScanner.newInstance();
        boolean epOnly = true;
        List sigs = scanner.scanAll(pefile, epOnly);
        System.out.println("PEiD Signature\n");    
        sigs.forEach(System.out::println);
        
        /*    
         * Print the CodeviewInfo
         */
        PEData pedata = PELoader.loadPE(pefile);
        DebugSection debug = new SectionLoader(pedata).loadDebugSection();
        System.out.println(debug.getCodeView().getInfo());        
    }
}

The Output for the above code :-

PEiD Signature

[Microsoft Visual C# v7.0 / Basic .NET] bytes matched: 54 at address: 13470

Codeview
--------

Age:  10
GUID: f512ffaf-b4c3-4f5a-b634-aa8f46bb8dce
File: C:\Users\overide\Documents\Visual Studio 2005\Projects\WindowsApplication1\WindowsApplication1\obj\Debug\WindowsApplicati​on1.pdb

Observations

The following gives the location of the pdb (Program database) file commonly used by .NET applications. From the forensic point of view the Username of the System that "overide" is important since it tells us that someone with a system account name "overide" made this (Most Probably but not with conclusive evidence)

Codeview
--------

Age:  10
GUID: f512ffaf-b4c3-4f5a-b634-aa8f46bb8dce
File: C:\Users\overide\Documents\Visual Studio 2005\Projects\WindowsApplication1\WindowsApplication1\obj\Debug\WindowsApplicati​on1.pdb
---------------------------------------------------------------------------------------------------------------

The following PEiD Signature tells us that the Application was programmed with C#.

PEID Signatures
***************

[Microsoft Visual C# v7.0 / Basic .NET] bytes matched: 54 at address: 13470

From here on we have two approaches. First we open the exe using any Hex Editor and see if we can find something interesting or if we can directly get the Serial from there(this step can be done earlier too). Now its a common sense that the serials or the password required will be stored in a string when it was coded (Not necessarily true because I can store them in hex or other encrypted format too which is being changed to other form by some other instructions.). So if you open the exe with any hex editor and observe thn you will come across something like this which is the serial we want :-

[Image: rS4fhbX.png]

The problem with this method is that if any PE file which is large in size or the serials are encrypted in some some binary form then it will be a problem to manually look for the serial and it could get difficult. So we will focus on the second approach which is much more easy.

Lets move on to the next approach. Based upon the above observation we can downloaded any .NET decompiler to reverse engineer the code. For such purpose you can use different tools, several free applications are available. The better one's would be ILSpy and dotPeek.

Download ILSpy : https://github.com/icsharpcode/ILSpy/releases/download/2.3/ILSpy_Master_2.3.0.1827_Binaries.zip
Download dotPeek : https://www.jetbrains.com/decompiler/download/

I will give show you both of them. You need to install ILSpy but dotPeek doesn't needs any installation.

Now all you have to do is open the PE file we have to crack with ILSpy or dotPeek and then locate :- "WindowsApplication1\Form1\button1_Click" and double press it to see the decompiled code. button1.Click is the event for the Register button. On the main panel the Serial Number and Password which you will be prompted with is clearly isible.

Observe the Images

ILSpy
[Image: ljUQZSy.png]

dotPeek
[Image: vtE1wKx.png]

Step 3 :Verify your Findings

So, these were the number of steps you can perform to get the serial and password. The following shows the password when you enter the password.
[Image: 9ETeKT7.png]


Conclusion

For software cracking, that concepts we learnt are applicable for many different scenarios and in different ways too like Source Code Theft forensics, Secure Code analysis etc.

I hope you enjoyed the tutorial. Stay tuned for the next Level 2 Walkathrough.

Tool Summary

1. PortExAnalyzer
2. Sandboxie
3. ILSpy or dotPeek.

Thank you,
Sincerely,
Psycho_Coder.
Continue Reading →

Basic Generative Art using Processing.js | Example 1

English: Vectorized Version of Processing Logo
English: Vectorized Version of Processing Logo (Photo credit: Wikipedia)
I started with Processing today and this is my first try to create some generative art using Processing.js, so here's the first version. More art or abstract programs to come soon.

Continue Reading →

Wednesday, June 24, 2015

[Funny Bash] Remove wife package and install sexy secretary



This is a very funny post. A general story takes the form of being written in bash shell code. I found this on Pastebin long ago and modified it a bit. This post is to taken as a hilarious joke and not in a serious way. Thank you.


Continue Reading →

PDF File Generation example in Java using iText Library

made an example where reports can be generated in PDF file format using iText library for Java. I made a swing app and we enter the data and then click the create pdf button to generate the pdf. Its not a tutorial but more like an example with a demo. Use the code, and I hope its readable enough.

[Image: 2Ssa87i.png]


Continue Reading →

Tuesday, June 23, 2015

L-Systems | Sierpinski Triangle in VB.NET


The Sierpinski triangle (also with the original orthography Sierpiński), also called the Sierpinski gasket or the Sierpinski Sieve, is a fractal and attractive fixed set with the overall shape of an equilateral triangle, subdivided recursively into smaller equilateral triangles.

Public Class Form1
   'We have used the following rules
   ' -1 = turn right by angle
   ' +1 = turn left by angle
   ' 2 = 'a'
   ' 3 = 'b'
   'Therefore te rules are represented like this
   ' 2 --> 3 -1 2 1 3
   ' 3 --> 2 +1 3 +1 2
   'Start Symbol : a
   ' 
   Dim angle As Double
   Dim size_of_triangle As Integer
   Dim no_of_iter As Integer
   Dim t As Integer
   Dim lst As List(Of Integer) = New List(Of Integer)

   Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
       numIter.Value = 7
       numSize.Value = 4
       numAngle.Value = 60
   End Sub

   Private Sub Form1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint
       Dim drawingPt As Point = New Point(250, Me.ClientSize.Height - 5)
       Dim D As Double = 0
       Dim P1 As Point
       For Each i As Integer In lst
           Select Case i
               Case -1
                   D -= angle
               Case 1
                   D += angle
               Case 2, 3
                   P1 = getNewPoint(drawingPt, D)
                   e.Graphics.DrawLine(Pens.Tomato, drawingPt, P1)
                   drawingPt = P1
           End Select
       Next

   End Sub

   Private Function getNewPoint(ByVal p0 As Point, ByVal d As Double) As Point
       Dim p1 As Point
       p1.X = p0.X + Math.Cos(d) * size_of_triangle
       p1.Y = p0.Y + Math.Sin(d) * size_of_triangle
       Return p1
   End Function

   Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
       Label4.Visible = True
       Me.TransparencyKey = Color.Beige
       angle = (numAngle.Value) * Math.PI / 180
       size_of_triangle = numSize.Value
       no_of_iter = numIter.Value
       t = 1
       If (no_of_iter Mod 2) = 1 Then t = -1
       lst = New List(Of Integer)
       lst.Add(2)
       For i As Integer = 0 To no_of_iter
           lst = Expand(lst)
       Next i
       Me.Invalidate()
   End Sub

   Private Function Expand(ByVal lst As List(Of Integer)) As List(Of Integer)
       Dim lst1 As List(Of Integer) = New List(Of Integer)
       For Each i As Integer In lst
           Select Case i
               Case -1, 1
                   lst1.Add(i)
               Case 2
                   ' 2 --> 3 -1 2 -1 3
                   lst1.Add(3)
                   lst1.Add(-1 * t)
                   lst1.Add(2)
                   lst1.Add(-1 * t)
                   lst1.Add(3)
               Case 3
                   ' 3 --> 2 +1 3 +1 2
                   lst1.Add(2)
                   lst1.Add(1 * t)
                   lst1.Add(3)
                   lst1.Add(1 * t)
                   lst1.Add(2)
           End Select
       Next
       Return lst1
   End Function

   Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
       Application.Exit()
   End Sub

   Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
       Label4.Visible = False
       Me.TransparencyKey = Color.Black
   End Sub
End Class



Related articles
Continue Reading →

NumPuzzler Game in VB.NET

[Image: num_zps2db96608.png]

A Simple game to chill your time . Enjoy your game . But the humor is that I have made this game and I was unable to win.

Complete Project Download
[Image: pL2R5.png]
Download EXE's Only [x64 and x86]
[Image: pL2R5.png]

Continue Reading →

Modified Atbash Cipher code in Python

English: Icon from Nuvola icon theme for KDE 3...
(Photo credit: Wikipedia)

The Atbash cipher is a very specific case of a Monoalphabetic substitution cipher where the letters of the alphabet are reversed. In other words, all A's are replaced with Z's, all B's are replaced with Y's, and so on. 

I modified this general scheme somewhat and added support for encrypting digits and special characters too to make it stronger because reversing the alphabet twice will get you actual alphabet, you can encipher and decipher a message using the exact same algorithm.
Example:

Plaintext  : Ex094, You are a very Nice Guy!
Ciphertext: [liZeB?~uo?8r4?8?n4rk?_064?-okX

class AtBash:

   def __init__(self):
       self.alphabets = ' ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789~!@#$%^&*()_+|:"<>-=[];,.?/`'

   def encode(self, plaintext):
       cipher = ""
       for i in plaintext:
           index = self.alphabets.index(i)
           cipher += self.alphabets[abs(len(self.alphabets) - index - 1) % len(self.alphabets)]
       return cipher

   def decode(self, ciphertext):
       return self.encode(ciphertext)


if __name__ == "__main__":
   atbash = AtBash()

   enc = atbash.encode("Hello World!")
   print(enc)

   dec = atbash.decode(enc)
   print(dec)

I hope you liked this post. Share this post. Thank you.
Continue Reading →

Follow Me!

Follow by Email

Blog Archive

Followers

Visitor Map