Flash's programming language ActionScript is used in a plethora of instances ranging from graphical use right up to technical backend database integration (along with other languages). In this tutorial I will discuss how to create a 1-bit encryption program using ActionScript -for the those who want that in English, simply its replacing letters for other letters in the alphabet to jumble it all up. Those of you who are familiar with Java, JavaScript and/or ActionScript will find this tutorial relatively easy. Although the code varies slightly, many methods/functions remain the same for string manipulation.
Criteria
The user will enter some text into a text field which will be encrypted on the event of a button click. This string will be encrypted on the basis of a key. This key is of English alphabet form and will be randomly generated (apart from the letter 'a'), after which the alphabet will continue - which will be known as the new alphabet. The new alphabet will be compared to the real (original) alphabet and letters will be substituted. The random key (letter) will be placed in front of the string entered into a text box. This is done for decryption purposes. Also, when encrypting the message, all non alpha characters must be ignored and only alpha characters replaced. See below for an example:
Original word entered into a textbox: hello!
Randomly generated key (i.e. letter in the alphabet): g
New alphabet: ghijklmnopqrstuvwxyzabcdef - the real alphabet begins with the letter 'a'. This new alphabet starts with 'g'. When it reaches 'z', it then continues until it reaches 'f'. This constitues the new alphabet (all 26 letters).
New word (based on the new alphabet): nkrru!
New word with the key in front: gnkrru!
Some of you may be puzzled how this works - at first it is a bit confusing, but once you get to understand the process you'll be able to work things out in your head even!
a b c d e f g h i j k l m n o p q r s t u v w x y z - real alphabet
g h i j k l m n o p q r s t u v w x y z a b c d e f - new alphabet
As shown above, the new alphabet begins with the letter 'g'. So taking the new word (encrypted word) 'nkrru' and substituting the letters in the new alphabet for the letters in the real alphabet, you will correctly decode the message:
n = h
k = e
r = l
r = l
u= o
Having understood this now, we will begin the process of understanding how to encrypt any word and decrypt it accordingly. Before we go on however, we should begin by setting up the Flash stage.
Step 1
Create the following interface with dimensions of 270 x 125 pixels, one textfield and three buttons:
The text field should be set to: Input text with a variable name of 'txtField'. We will be referencing this name later on to grab text from the field. Put this on it's own layer and name it 'text field'.
Create three buttons - encode, decode, clear - and place them on a one layer and label it 'buttons'. You can make it as fancy as you want, or as dull as you want; its up to you - just as long as it IS a button.
The 'encode' button should have an 'instance name' of 'encode' like so:
Follow the same step as above for both the 'decode' button and 'clear' button using their names as the instance name.
These four items are the only functional objects on the stage, everything else are for aesthetic purposes only.
Step 2
Create another layer and label it, 'ACTIONS'. I like to keep all my actions on one layer and everything else in appropriate layers; it just helps to keep things neat and manageable.
Select the first frame of the ACTIONS layer and open up the Actions Panel. Click on the 'View Options' button and change the mode from Normal to Expert like so:
This enables us to enter in our own scripts/type instead of selecting actions from the hierarchical menu on the left. Regardless of whether you are an amateur or not, you will find Expert Mode the most comfortable to use.
With the first frame still selected apply a 'stop' action using the following code:
| stop(); |
We will need this stop action in order to stop it at this frame; we don't have a need for any other frames and all our scripts will be in this first frame.
If you wish, you can also make a comment to yourself by adding two forward slashes before your comment:
Throughout my code, I like to comment it for various reasons. The most obvious one is to help me understand what the piece of code below it is doing if I just have a glance at it. It also helps others understand what the following code is about if I show it to them. Another thing you will see me do (in the source code) is use comments to highlight a section of code. I usually do this so its easier for me to identify where a function starts and ends. The colour of the comment isn't anything special, although if you're working in MX, chances are that the comments are grey and mine are pink. Pink just helps me see the comments better (and I'm an old skooler); its nothing important.
Step 3
We need a couple of global variables that will last for as long as this 'application' is open. We need to create a variable that will hold an alphabet string, the key (random key), a random number, and a temporary variable that will hold any temporary strings. Insert the following code under the stop action you created earlier:
|
// Global Variables
alphabet = "abcdefghijklmnopqrstuvwxyz"; randomAlpha = ""; randomNumber = 0; storeMessage = ""; |
Step 4
Now for the juicy parts, and that's to begin our scripts.
I will begin with the easiest part - the clear button!
With Flash MX, the ActionScript language has been revised to encompass more of an OO (Object Orientated) approach. Each object on the stage is exactly that - an object. It has properties/attributes and can be referred to via it's 'instance name' and/or 'variable name' - depending on the object. These two names should be familiar to you already as you have encountered this when creating the text field and creating your buttons - well giving them instance names rather. Instance names allow us to refer to it, to manipulate it (depending what object type it is), talk to it, receive information from it and more.
With this advanced OO ActionScript approach, we will no longer be using old methodology and scripting, instead we will learn to use the new ways to code.
For buttons, in the past you used the on(whatever) method like so:
In Flash MX however it is now Function based. The script for a released event for a button is now:
buttonInstanceName being the instance name you entered in for the button. You now no longer attach this script to a button; it stays in the first frame. How does it work? Remember the advanced OO approach I was talking about and how you can talk to objects. This is one such example. We have talked to it first by referencing its instance name 'buttonInstanceName' and have told it that onRelease is a function in which it need to act upon when the mouse button has been released. It will then run the code inside the curly braces - { }
So now for the clear button. We want the clear button to clear the text in the text field - obviously. Following the above example, this is how you would code it. Insert the function below the declaration of the Global Variables.
|
clear.onRelease = function() {
txtField = ""; } |
This clears the text field to by replacing whatever is currently there with nothing. We have again seen the OO approach in action. We have referenced the text field with the variable name 'txtField' and gave it a string - but a string of nothing (i.e. nothing inside the two quotation marks: ""). For those of you who are unfamiliar with the term, 'String', it basically means some text, or text. e.g. "hello" is a String, "what is your name?" is a String, "1234" is a String. So an empty string would be nothing, ie: "".
Step 5
Now we will move on to the encrypting/encoding part. As with the clear button and remembering that we called the button 'encode', it starts in the same fashion:
| encode.onRelease = function() |
What happens if the user doesn't a string at all and presses the Encode button? Well, mustn't allow for that to happen. So we need to use an IF statement to check IF there they have entered in a String or not. Again if you have used Java, JavaScript or ActionScipt before, you'll know exactly what to do and the syntax. If you have use another language such as C, C++, VisualBasic or the like, the IF statement still remains, but the syntax is slightly different. One such IF statement (in ActionScript) is below:
|
if (variable1 == variable2) {
// do something } else { // do something else } |
This is how an IF statement looks like and we will be using it to check if there has been any text entered. With the following scripts - and even the ones displayed above - you can simply copy and paste them into Flash.
When checking the text field, we want to say:
If there is some text in the text field, then convert the text to lowercase, remove the text from the text field and pass it to a method/function which will encode it for us and display the encoded message, else if there is no text, display the message, "Please enter in some text to encode".
For those unfamiliar with methods/functions (called different things to many people), you can pass variables/information to it.
In our encoding program we will be passing variables (String) from the text field (after we have verified that a String has been entered) to a method/function which will then do the encryption/decryption. A demonstration of a function that can receive variables/information is below:
|
function displayName(name) {
trace(name); } |
This function when called requires that you enter in some text to its constructor (the two brackets - ()), which will then print out the name inside the Flash environment (the trace command only works inside Flash. It is used mainly for testing purposes).
With this information, we can then start our coding. Insert the following function below the Clear button function:
|
encode.onRelease = function() {
// creates a new variable 'encodeTxt', which gets assigned the text // inside the text field with the instance name, 'txtField'. encodeTxt = txtField; // checks length of the text. If its more than 0, then it must contain // something. if (encodeTxt.length > 0) { // Converts text to lowercase, clears the text field and sends the // text to the 'coder' method. encodeTxt = encodeTxt.toLowerCase(); txtField = ""; coder(encodeTxt); } else { // Inserts alert message to the text field to tell the user to enter // some text. txtField = "Please enter in some text to encode"; } } |
I have commented the code so that anyone will be able to understand it. You may see that I've spanned my comments over multiple lines. This is just my habit of doing things. I don't like comments that go on and on. I'd much prefer to have my comments across two or more lines, then have to scroll across the screen - but thats just me.
Some may query me on the 'toLowerCase()' method. This (as the name suggests) converts a given string to lowercase. In this example of 1 bit encryption, it is only going to work with lowercase letters; well anything you enter in will get converted to lowercase. But for simplicity, I have just decided to stick to lowercase letters. You can by all means take this 'application' and experiment with it and take it further.
Step 5
We will now write the script for the decode button. The decode button has pretty much the same, if not the same (bar three things) code. The three pieces of code that are different are:
- the variable 'encodeTxt' now becomes 'decodeTxt'.
- instead of sending the string to be decoded to the 'coder' method, we will send it to the 'decoder' method.
- instead of the alert message telling the user to "... enter some text to encode", we will change it to "... enter some text to decode".
Apart from those three things, everything - including the structure - is the same.
Insert the following function below the Encode button function:
|
decode.onRelease = function() {
//creates a new variable 'decodeTxt', which gets assigned the text // inside the text field witht he instance name, 'txtField'. decodeTxt = txtField; // checks length of the text. If its more than 0, then it must contain // something. if (decodeTxt.length > 0) { // Converts text to lowercase, clears the text field and sends the // text to the 'decoder' method. decodeTxt = decodeTxt.toLowerCase(); txtField = ""; decoder(decodeTxt); } else { // Inserts alert message to the text field to tell the user to enter // some text txtField = "Please enter in some text to decode"; } } |
Again, my code has been commented for the benefit of others - as well as myself. Step 6 and 7 are the juiciest parts. They are the functions used to encode and decode the message.
Step 6
This step requires much more attention. There are basic things such as assigning variables to other variables and IF statements among other things that you should have become fluent in already while doing this tutorial.
The first step in creating the function that encodes the message is to accept the given message from the constructor. We do this by storing this message into a variable. The code I have used is:
| storeMessage = receive; |
In ActionScript, as long as you assign a variable on creation, you can create variables anywhere, just like I have done above. There is no need for specifying what variable type it is like in Java or other languages.
Next we need to create our key. Remembering at the start of the tute, I mentioned that the random key will be based on the English alphabet. I also mentioned that it can't be the letter 'a'. The reason being because, if the random key was the letter 'a', the message would get encrypted, but with itself; the letters would be substituted for its own letter. I.e. a = a, b = b etc etc. So it has to be anything but the letter 'a'.
So to create a random number, we need to use Flash's Math object and access its 'random' method. The following code creates a random number between 0 and 26:
| Math.random() * 26; |
When assigning the values to the alphabet, 0 = a. The letter 'a' cannot be used, as discussed earlier, therefore we have to change it. We have to be smart however, as we can't simply change 26 to 27. Why? There are only 26 letters in the alphabet! So we need to create a random number between 0 and 25 and then add 1 to it. Why? So that if it happens to create a random number of 0, then when we add 1 to it, the random number now becomes 1, and if it creates a random number of 25 (which would be the letter 'y' in the alphabet) and we add 1 to it, it then becomes 26 (which is the letter 'z').
So now to create a random number between 0 and 25 and add 1 to it, we use the following code:
| (Math.random() * 25) + 1; |
Remember your basic math and algebra? Do everything inside the brackets first before you do anything else? If you don't remember that, well then I just reminded you.
Next we need to create the new alphabet based on that random number. From that random number we need to reach the number 26 (which would be the real alphabet letter 'z') and start it again until it completes. I.e. if the random number generated was 20, I would have to cycle from 20 to 26, and then from 0 to 19 so that it completes all 26 numbers. This will require me to loop through the alphabet string (remember the variable 'alphabet' that we created up at the top) and assign the random key number's position in the alphabet to a new string variable.
For this I will introduce, funnily enough, a FOR loop. Again those of you who have used Java, JavaScript and/or ActionScript before, know exactly how a for loop works and the correct syntax (because it differs slightly). However, those who are familiar with Director's Lingo or VisualBasic or some other languages, you may have come across a FOR loop in a different way. It was most probably referred to as a repeat loop. Much like this Lingo code below:
|
repeat with i=0 to 10
put("hello, this message will repeat itself 10 times") end repeat |
A FOR loop however looks like this:
|
for (i=0; i<10; i++) {
trace("hello, this message will repeat itself 10 times"); } |
You can see the similarities with 'i' being a variable which is incremented from 0 to 10 and displaying the message 10 times.
Now back to the issue at hand of looping through 26 times and creating a new alphabet based on the random key the following code does exactly that:
|
for (i=0; i<26; i++) {
randomAlpha += alphabet.charAt(randomNumber); randomNumber++; // Once the number has reached the end (i.e. z = 26), it must then go and // start from the start of the real alphabet (i.e. a = 0). if (randomNumber == 26) { randomNumber = 0; } } |
The comments pretty much explain what it is doing. The only other thing to mention is that this loops through 26 times (which was defined up at the top by: i<26). After which the loop exits.
Next we need to do the part of encoding the string. Again we need to employ the help of the FOR loop. We need to loop through each letter in the current string (message) and substitute it with the letters in the new alphabet. As mentioned before, we need to loop through the entire message. However, we need to know how many times to loop. We can find this out by using the String object's 'length' method. This returns a number based on how many characters are in a string. If I were to as the length of the word: 'hello', it would return to me the number 5. The following code demonstrates its usage:
|
storeMessage = "hello peoples";
trace(storeMessage.length); |
The above code will print to the screen the number of letters contained in the String, "hello peoples" which was stored in the variable, 'storeMessage'; The number would be 13.
This is extremely useful to us seeing as though we need to know how many times to loop through to encode the message. You seen previously in the FOR loop that you have a condition specifying how many times the loop will actually loop for. In one of the code snippets above, we used:
| for (i=0; i<26; i++) |
This tells us to initialise the variable 'i' with the number 0, it will loop for 26 times and each time it loops it will increment the variable i by 1. We can however, instead of specifying an actual number for the amount of times to loop (i.e. 26), substitute the number for a variable which has a numerical value assigned to it. Hopefully the previous example of the .length method is ringing in your head. Remembering that the .length method returns a numerical value, we can easily substitute the number 26 for storeMessage..length, which will then be written to the FOR loop as:
| for (i=0; i<storeMessage.length; i++) |
After looping the amount of times specified using the above code, we then need to check if the given string contains non-alpha characters. There may be multiple ways of achieving this; I have found one of them. The ASCII (American Standard Code for Information Interchange) character set contains characters and their numerical equivalent. Searching this character set I have found that the alphabetical characters sit perfectly between the numbers 96 and 123. The number 96 is the apostrophe and the number 123 is the left curly brace. everything in-between those two numbers contain the English alphabet from a to z. This is perfect for what we need. What we need to do is use an IF statement again. However you cannot simply say if the whole string is in-between 96 and 123. You must cycle through each individual character and check it. If it is between the two numbers (i.e. it is an alpha character), then we need to substitute the current character with the appropriate character in the new alphabet. To check if the string is in-between those two numbers however, we need to talk to the String object and access it's 'fromCharCode()' method, and give it a number through its constructor:
| String.fromCharCode(97); |
This would give you the letter 'a'.
We need to also know which letter we are to access. However it comes to the dilema that we need to cycle through each character in the string. Fortunately for us, the String object has a method for exactly what we want. This method is the character at or charAt() method. This method allows us to target a specific character in a string, by the number. We pass a number to it through its constructor. If by now you are wondering what a 'constructor' is and I haven't explained it, it is the two brackets, or parenthesis - (). In the variable tempMessage which has the string "hello" stored:
| tempMessage.charAt(3); |
would return to us the first letter 'l' in that string. This is extremely useful to us, as it allows us to target a specific character. As mentioned before with the storeMessage.length example, we can substitute a number (in the charAt exmple, it is 3) for a variable that contains a numerical value. We can then use the variable 'i' in the FOR loop. Why? We can use it because it will start at 0 and stop at the storeMessage.length number; if that number is 10, then it will increment from 0 each time it exits the loop, thus allowing us to change and look at a different character each time. So now for the IF statement:
| if (storeMessage.charAt(i) > String.fromCharCode(96) & & storeMessage.charAt(i) < String.fromCharCode(123)) |
In English, the line above basically means: IF the current letter of the message is between a and z. We now need to fill in the THEN part. We've set the condition, so now we need to act upon it if it is indeed true. So if it is in-between a and z, then we want to substitute the current letter for the appropriate letter in the new alphabet. For this, we need to again use a FOR loop. To keep track, we currently have a first FOR loop that will loop X amount of times (the duration of the string). We then have an IF statement, which checks to see if the current letter of the string is an alpha character. Now we need another FOR loop, which this time loops through 26 times (i.e. the alphabet). This time we cannot use the variable 'i' as our incrementor, we need to use another one; I have chosen the letter 'j'.
We now need yet another IF statement which will check to see if the current letter is equal to the same letter in the real alphabet. If it is, then we will assign the random alphabet (which was generated based on the random number) and the character at which the loop number is (the letter 'j', which has a numerical value assigned to it) to a temporary variable named 'switchOver'. I am using a special operator that includes an assigning value as well as a start-from-where-you-finished value. It is the += operator. This basically (for strings anyway) picks up where you are and keeps adding to what you already have.
Now, looping though the letter and substituting it for the new alphabet is the beginning of our encryption. When the loop ends, this will complete the process of our 1 bit encryption! All this just to get 1 bit encryption - imagine a bank system that has 128 bit encryption... or more!
The following code is the first part of the encryption process, substituting alpha characters:
|
for (i=0; i<storeMessage.length; i++) {
if (storeMessage.charAt(i) > String.fromCharCode(96) & & storeMessage.charAt(i) < String.fromCharCode(123)) { for (j=0; j<26; j++) { if (storeMessage.charAt(i) == alphabet.charAt(j)) { switchOver += randomAlpha.charAt(j); } } |
Now to finish off the encryption process. I mentioned earlier that if the given string (the message entered in) was within the ASCII character set numbers of 96 and 123, to then encode it and everything else will be ignored. In similar fashion to the third last line above, we need to assign something to the switchOver variable. However we don't want to be substituting characters with anything in the random alphabet, or even anything in the alphabet. We want to replace the non-alpha characters with itself. To do this we need to complete the IF statement with an else. An IF statement has three main structures.
The first being:
IF
THEN
END IF
Second:
IF
THEN
ELSE
END IF
Third:
IF
THEN
ELSE
ELSE IF
THEN
END
The third example could keep going, depending on what the task at hand is. We will be using the second example of an if then else statement. I've already covered the if then clause, and we need to complete it. As complex as it may sound, all we need to do is to replace the character with its own character and we have covered everything that we need to know to allow as to do it. We need to employ the help of the charAt() method again. This time we need to use the storeMessage variable, which has the original message stored in it. We then need to assign it to the switchOver variable. All we have to do it use the following code to finish it off:
|
} else {
switchOver += storeMessage.charAt(i); } } |
This works because of our IF statement. We have said, if the current letter (using the charAt(i) bit) is within the ASCII character set numbers 96 and 123, then encode it. So the above statement will catch any non-alpha characters. Its easy as that!
The final code block for this bit looks like this:
|
for (i=0; i<storeMessage.length; i++) {
if (storeMessage.charAt(i) > String.fromCharCode(96) & & storeMessage.charAt(i) < String.fromCharCode(123)) { for (j=0; j<26; j++) { if (storeMessage.charAt(i) == alphabet.charAt(j)) { switchOver += randomAlpha.charAt(j); } } } else { switchOver += storeMessage.charAt(i); } } |
Since we have finished with our temporary variable 'switchOver', we won't be needing it anymore. We can now copy its contents over to the original variable, which was 'storeMessage'. Now we need to add our random key to the start of the message, else we wont be able to decode it. In programming terms, a Concatenator joins two things together (namely strings). Some languages (most I'm guessing) allow you to concatenate two or more strings on the fly using various operators, some the addition symbol (+), others with the period symbol (.) and yet others both. In ActionScript you can join two or more strings together using the addition symbol. However, there is also the Concat method from within the String object. It allows us to do just that, to concatenate two strings together. We will be using this method to join the random key to the now encoded message. When creating the random number, we also used the following code directly below the random number creation:
| letter = alphabet.charAt(randomNumber); |
I'm explaining this now because you can easily understand what it is doing now rather than befoe. It is talking to the alphabet string variable and specifying a certain character via charAt(randomNumber). It is then assigning the letter to the variable appropriately named 'letter'. Now to concatenate the letter to the encrypted message, use the following code:
| storeMessage = letter.concat(storeMessage); |
We no longer use the += operator, but use the assigning operator '='. With the Concat method, it concats everything supplied to the constructor to the variable prefixed to it (in this case 'letter'). All this is assigned to the storeMessage variable. They key (which will be used to decode the message) is now at the front of the message.
We now need to display the newly encrypted message to the textfield. to do that we simply reference the text field via its instance name and assign it the contents of the variable storeMessage as easily as you would assigning one variable to another:
| txtField = storeMessage; |
Next we need to clear the information stored in the variables storeMessage and switchOver. This is done by assigning them both empty strings:
|
storeMessage = "";
switchOver = ""; |
That's it! Well for the encoding part :) The following code is the final version of the coder function which is called from the 'encode' button.
|
function coder(receive) {
storeMessage = ""; storeMessage = receive; switchOver = ""; // Math.round() method rounds to the nearest whole number. Math.random() method // creates a random number between 1 and 26. randomNumber = Math.round((Math.random() * 25) + 1); letter = alphabet.charAt(randomNumber); // Fills the String starting from the position of the random number for (i=0; i<26; i++) { randomAlpha += alphabet.charAt(randomNumber); randomNumber++; // Once the number has reached the end (i.e. z = 26), it must then go and // start from the start of the real alphabet (i.e. a = 0). if (randomNumber == 26) { randomNumber = 0; } } // Goes through the message, and finds where the same values meet up. Once it // has found them, it then changes them over with the randomAlpha, which both is // the randomAlpha, but also the random text. // // Characters between 96 & 123 (a - z) will get replaced with the randomAlpha // array values. Everything else gets replace by itself. for (i=0; i<storeMessage.length; i++) { if (storeMessage.charAt(i) > String.fromCharCode(96) & & storeMessage.charAt(i) < String.fromCharCode(123)) { for (j=0; j<26; j++) { if (storeMessage.charAt(i) == alphabet.charAt(j)) { switchOver += randomAlpha.charAt(j); } } } else { switchOver += storeMessage.charAt(i); } } // Adds the randomAlpha to the front of the message using concat, then stores // the message back to the original. storeMessage = switchOver; storeMessage = letter.concat(storeMessage); txtField = storeMessage; storeMessage = ""; switchOver = ""; } |
Step 7
The decoder function works very much the same as the encoder function. It has a couple of things different, but most of it is the same. We again create the storeMessage variable and assign it the value of 'receive', which would be the message ready to be decoded. We again have a switch over variable, but this time with a different yet similar name: switchOverDecoded. We are also introduced to a new variable keyPosition that we haven't seen yet. This in conjunction with the next bit of code works together in finding the position of key in the real alphabet. Here is the code I am explaining:
|
keyPosition = 0;
// Finds the position of the key in the normal alphabet and stores it. for (i=0; i<26; i++) { if (storeMessage.charAt(0) == alphabet.charAt(i)) { keyPosition = i; } } |
As mentioned toward the end of Step 6, the key, which is used for decoding, is at the start of the message. To reference it, we use the charAt() method again. However, instead of using 'i' or 'j' like we have been using so much of, we need to always check the first letter of the message (i.e. it needs to remain static). So we simply use 0, as it is the first. We are looping 26 times using a FOR loop (i.e. the length of the alphabet) and checking to see if the first letter equals the current letter of the alphabet. If it does, it then stores the position to the variable keyPosition. We need this so that we can recreate the alphabet used to encrypt the message. Once we know it, we can then substitute it for the real alphabet.
As mentioned above, we need to recreate the alphabet. Similarly with the coder function, we created the new alphabet using the following code:
|
// Fills the String starting from the position of the random number.
for (i=0; i<26; i++) { randomAlpha += alphabet.charAt(keyPosition); keyPosition++; // Once the number has reached the end (i.e. z = 26), it must then go and // start from the start of the real alphabet (i.e. a = 0). if (keyPosition == 26) { keyPosition = 0; } } |
This therefore doesn't need any explanation as it has already been explained. The same goes for the next comment block. In this piece of code however, instead of encoding it is decoding the message, yet it uses the same code in order to decode; detect if it is alpha, if so then it will substitute it for the real alphabet, if not, then it will replace it with its own character. This is getting added each time using the += operator to the switchOverDecoded variable. Here is the decoding code:
|
// Goes through the message, and finds where the same values meet up. Once it
// has found them, it then changes them over with the key, which both is the // key, but also the random text. // // Characters between 96 & 123 will get replaced with the key array // values. Everything else gets replace by itself. for (i=0; i<storeMessage.length; i++) { if (storeMessage.charAt(i) > String.fromCharCode(96) & & storeMessage.charAt(i) < String.fromCharCode(123)) { for (j=0; j<26; j++) { if (storeMessage.charAt(i) == randomAlpha.charAt(j)) { switchOverDecoded += alphabet.charAt(j); } } } else { switchOverDecoded += storeMessage.charAt(i); } } |
As with encoding the message, we needed to add the key to the front of the message. This was done using the Concat() method. I will now introduce you to its reverse equivalent. It is the substring() method. There are two functions of the substring method. The first is to give it a starting position, through its constructor. The second is to give it a starting position as well as an ending position. The substring, when used with a starting and ending position, copy everything starting from the specified starting position and continue until it reaches the ending position. E.g. If I were to use the following code:
|
tempString = "what?";
trace(tempString.substring(1,4); |
This would print to the output window in Flash the word, "hat". This is because it copies everything from the starting position of 1 and ends at 4. When dealing with strings or arrays, the starting position is always 0 and never 1, this is why it starts at the letter 'h' and not 'w'. The ending position is different however, it stops at the specified letter and doesn't include it. The other function of the substring method is to simply specify the starting position and nothing else. It will need start at that position and continue until the very end. So now having learnt that, here is the code that removes the random key that was added to the start of the message:
| storeMessage = switchOverDecoded.substring(1); |
Again we now need to display the decoded message to the text field. We also need to clear the variables by assigning an empty string to them. As I have demonstrated this already in the coder function, I won't need to explain it again here. Below is the final code for the decoder function which gets called from the 'decode' button.
|
function decoder(receive) {
storeMessage = ""; storeMessage = receive; switchOverDecoded = ""; keyPosition = 0; // Finds the position of the key in the normal alphabet and stores it. for (i=0; i<26; i++) { if (storeMessage.charAt(0) == alphabet.charAt(i)) { keyPosition = i; } } // Fills the String starting from the position of the random number. for (i=0; i<26; i++) { randomAlpha += alphabet.charAt(keyPosition); keyPosition++; // Once the number has reached the end (i.e. z = 26), it must then go and // start from the start of the real alphabet (i.e. a = 0). if (keyPosition == 26) { keyPosition = 0; } } // Goes through the message, and finds where the same values meet up. Once it // has found them, it then changes them over with the key, which both is the // key, but also the random text. // // Characters between 96 & 123 will get replaced with the key array // values. Everything else gets replace by itself. for (i=0; i<storeMessage.length; i++) { if (storeMessage.charAt(i) > String.fromCharCode(96) & & storeMessage.charAt(i) < String.fromCharCode(123)) { for (j=0; j<26; j++) { if (storeMessage.charAt(i) == randomAlpha.charAt(j)) { switchOverDecoded += alphabet.charAt(j); } } } else { switchOverDecoded += storeMessage.charAt(i); } } // Stores back the decoded message, but starting from the 2nd position to // omit the key. storeMessage = switchOverDecoded.substring(1); txtField = storeMessage; // Resets the string. If you don't set it back to having no text once called // upon again, it doesn't overwrite properly, hence resetting. randomAlpha = ""; switchOverDecoded = ""; } |
That's it! If you're still reading till now, I congratulate you! Here is the final product in action:
If there are any bugs in this 'application' please leave a comment in the comments section. Have fun.
Note: Some may have seen this tutorial in the form of an assignment using Java; this tutorial has been adapted and built upon using the Flash environment and the ActionScript language, but is by no means the same. Credit for original assignment idea using the Sun's Java programming language goes to Mark Szota.

fred March 04, 2007 says:Hi, looks good. But i'm still having a couple of errors. Do you mind sending me the final block of code for the whole thing?











