a cryptographic learning tool - university of...

81
A Cryptographic Learning Tool Student: Anthony Williams Degree Programme: MEng. (Hons) Computer Science Supervisor: Dr. Uli Sattler Report for a Third Year Project University of Manchester School of Computer Science April, 2014

Upload: duongtuong

Post on 26-May-2018

214 views

Category:

Documents


0 download

TRANSCRIPT

A Cryptographic Learning Tool

Student: Anthony WilliamsDegree Programme: MEng. (Hons) Computer Science

Supervisor: Dr. Uli Sattler

Report for a Third Year ProjectUniversity of Manchester

School of Computer Science

April, 2014

A Cryptographic Learning Tool

Student: Anthony WilliamsSupervisor: Dr. Uli Sattler

Abstract

The way in which computing is taught in schools has undergone amajor change. Privacy and in particular data privacy on the webhas become much more important to people. These two separate,massive changes to the socio-political environment have lead tothe identification of a possible need for a cryptographic syllabusto be added to the National Curriculum.

This report suggests a syllabus that could be reasonably in-troduced to schoolchildren and describes a project aimed at cre-ating some software to facilitate the teaching of this new syl-labus. Two tools were created in this respect: an interactivewebsite and an entertaining and engaging mobile game.

2

Acknowledgements

I would like to thank my supervisor, Dr. Uli Sattler, for hersupport and guidance. I would also like to thank Dr. Dr LipingZhao for her feedback on my project deliverables. Additionally,I would like to thank my family, friends and everyone else whohelped me test and evaluate this project. Finally I would like tothank my finacee who had to put up with me and my questioningthroughout the development of this project. Without your helpnone of this would have been possible.

I love you all.

3

Contents

1 Introduction 51.1 Project Goals . . . . . . . . . . . . . . . . . . . . . . . . . . . 51.2 Brief Summary . . . . . . . . . . . . . . . . . . . . . . . . . . 61.3 Overview of the Rest of the Report . . . . . . . . . . . . . . . 6

2 Background 82.1 The National Curriculum . . . . . . . . . . . . . . . . . . . . 82.2 Classical Cryptography . . . . . . . . . . . . . . . . . . . . . 92.3 Modern Web Development . . . . . . . . . . . . . . . . . . . . 172.4 Android Game Development . . . . . . . . . . . . . . . . . . . 182.5 Other E-Learning Environments . . . . . . . . . . . . . . . . 18

3 Design 243.1 A Cryptographic Syllabus . . . . . . . . . . . . . . . . . . . . 243.2 General Design . . . . . . . . . . . . . . . . . . . . . . . . . . 253.3 CryptoLearn Design . . . . . . . . . . . . . . . . . . . . . . . 263.4 CrypTD Design . . . . . . . . . . . . . . . . . . . . . . . . . . 31

4 Implementation 414.1 CryptoLearn Implementation . . . . . . . . . . . . . . . . . . 414.2 CrypTD Implementation . . . . . . . . . . . . . . . . . . . . . 48

5 Testing and Evaluation 595.1 Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 595.2 Evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62

6 Summary and Outlook 676.1 Achievements . . . . . . . . . . . . . . . . . . . . . . . . . . . 676.2 Further Work . . . . . . . . . . . . . . . . . . . . . . . . . . . 696.3 Final Remarks . . . . . . . . . . . . . . . . . . . . . . . . . . 69

4

Bibliography 71

A Some Teaching Material 75A.1 The Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75A.2 The Ciphers . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76

List of Figures

2.1 Cipher Illustration . . . . . . . . . . . . . . . . . . . . . . . . 112.2 Web Usage on Different Platforms . . . . . . . . . . . . . . . 172.3 SAM Learning Screenshot . . . . . . . . . . . . . . . . . . . . 202.4 BBC Bitesize Screenshot . . . . . . . . . . . . . . . . . . . . . 212.5 Codeacademy Screenshot . . . . . . . . . . . . . . . . . . . . 222.6 Udacity Screenshot . . . . . . . . . . . . . . . . . . . . . . . . 23

3.1 CryptoLearn Architecture: PHP Files . . . . . . . . . . . . . 283.2 CryptoLearn Architecture: Javascript Files . . . . . . . . . . 283.3 CryptoLearn Architecture: CSS Files . . . . . . . . . . . . . . 293.4 Architecture Diagrams Key . . . . . . . . . . . . . . . . . . . 293.5 Screenshots of CryptoLearn . . . . . . . . . . . . . . . . . . . 303.6 The ZG Framework . . . . . . . . . . . . . . . . . . . . . . . . 333.7 Screen Sequence of CrypTD . . . . . . . . . . . . . . . . . . . 333.8 Domain Class Diagram of CrypTD . . . . . . . . . . . . . . . 343.9 System Class Diagram of CrypTD: Tutorials . . . . . . . . . 363.10 System Class Diagram of CrypTD: Questions . . . . . . . . . 373.11 System Class Diagram of CrypTD: Tower Construction . . . 383.12 System Class Diagram of CrypTD: Enemy Spawning . . . . . 393.13 System Class Diagram of CrypTD: Combat . . . . . . . . . . 39

4.1 Fill-in-the-blank Questions on Differently Sized Screens . . . 44

6.1 CryptoLearn on a Desktop Device . . . . . . . . . . . . . . . 686.2 CryptoLearn on a Mobile Device . . . . . . . . . . . . . . . . 686.3 Screenshots from CrypTD . . . . . . . . . . . . . . . . . . . . 69

5

List of Tables

2.1 Example Caesar Encryption Table . . . . . . . . . . . . . . . 112.2 Example Arbitrary Substitution Table . . . . . . . . . . . . . 122.3 Example Playfair Keysquare . . . . . . . . . . . . . . . . . . . 132.4 Example Pieces of Playfair Cipher Ciphertext . . . . . . . . . 142.5 Illustration of the Vigenere Key . . . . . . . . . . . . . . . . . 152.6 Comparison of Some E-Learning Environments . . . . . . . . 19

5.1 Test Cases for the PlayfairSqaure Class . . . . . . . . . . 605.2 Test Cases for the Ciphers class . . . . . . . . . . . . . . . . 615.3 Proxy Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63

A.1 Playfair Cipher Keysquare Cell Name . . . . . . . . . . . . . 77

List of Listings

4.1 The CSS for the sr-only-lg Class . . . . . . . . . . . . . . 444.2 Use of the sr-only-lg Class . . . . . . . . . . . . . . . . . 454.3 The Shift Function . . . . . . . . . . . . . . . . . . . . . . . 464.4 The removeDuplicates Function . . . . . . . . . . . . . . 474.5 Mark-up for a Fill-in-the-Blanks Question . . . . . . . . . . . 494.6 The checkBlanks Function . . . . . . . . . . . . . . . . . . 494.7 Use of the state Variable . . . . . . . . . . . . . . . . . . . . 514.8 Dealing with User Input: Pt. 1 . . . . . . . . . . . . . . . . . 534.9 Dealing with User Input: Pt. 2 . . . . . . . . . . . . . . . . . 554.10 Dealing with User Input: Pt. 3 . . . . . . . . . . . . . . . . . 56

6

4.11 The update Method: Pt. 1 . . . . . . . . . . . . . . . . . . . 574.12 The update Method: Pt. 2 . . . . . . . . . . . . . . . . . . . 58

7

Chapter 1

Introduction

This project was motivated by two separate social and political develop-ments. The first of these is the way in which computing is taught in schools.The old syllabus - ICT (Information Communication Technology), which fo-cussed on using programs like Word - has been scrapped and replaced with anew ‘curriculum for computing’. This new curriculum focusses on computerscience topics such as algorithms, architecture and problem solving. Com-puter Science and computational thinking are now seen as integral skills forthe modern workplace [1].

The second motivation is privacy. Privacy, especially internet privacy,has become a major socio-political topic. Hackers are becoming more dan-gerous, advertising more pervasive and governments and security agenciesthe world over are being accused of violating the privacy of civilians indis-criminately. Many activists and educational groups are starting to encouragepeople to learn more about how to keep their data safe. Cryptography isone of the main ways in which this is achieved and more and more peopleare reaching out and trying to learn about it [2].

With both a crying need for educating the general public about cryptog-raphy and a massive change in the way computing is taught in schools, it isreasonable to suggest that, some time in the future, cryptographic principlescould (and maybe should) be taught in schools.

1.1 Project Goals

This project aims to tackle two things:

1. Decide on a syllabus for cryptography

8

2. Create some electronic teaching material (software)

The creation of this syllabus should take into account what can feasiblybe taught to schoolchildren. This requires deciding on the age to aim thissyllabus at. This process should also take into account what knowledge isrequired and whether or not this is already included in other parts of thenational curriculum.

The software needs to encompass an interactive and engaging learningenvironment that encourages and facilitates learning and curiosity. Thesoftware needs to be as available as possible; no child should be at anydisadvantage because of the technology used to assist the teaching.

1.2 Brief Summary

The syllabus was first decided upon, including the learning objectives, theteaching methodology and method of assessment. This syllabus is centredaround teaching the basic principles with concrete ciphers as a vehicle. Assuch, the syllabus includes the learning of four ciphers: the Caeser Cipher,the Playfair Cipher, the Vigenere Cipher, and the One Time Pad.

Then the design of the learning environment began. It was quickly re-alised that one of the easiest and most effective ways of creating and in-formative and engaging environment was to separate the concerns into twotools: a website that presented the material to be learnt; and a game thatwould encourage learning and reinforce understanding.

The evaluation of the project began in tandem with the development.This was to allow ‘proxy users’ to quickly provide feedback that could dra-matically improve the quality of the project and to increase confidence inits ability to meet its goal of facilitating teaching. The development cyclefollowed a vaguely agile and user centred methodology.

1.3 Overview of the Rest of the Report

The rest of this report describes how this project was undertaken and itsresults. The following chapter provides the reader with the necessary back-ground to understand the work done in the project and thus, the rest ofthe report. This is followed by a brief look at some similar work. Then, inlater chapters, the design, implementation and evaluation of the software isdiscussed. This is not a detailed walkthrough of these phases, but insteadan overview of the main issues, problems, major decisions made and results

9

found. After this, the report concludes with a brief summary of the results,what would have been done differently and what could be added if moretime was available.

10

Chapter 2

Background

This chapter provides the reader with the background information necessaryto understand the project and the rest of this report. The education sideof the project will likely be unknown to most readers and is necessary tounderstand why certain choices were made. Therefore most readers will needto read the section on the National Curriculum. Classical cryptographyplays a major part of the project and readers will need to know how theciphers work in order to understand why the project was built the way itwas, all readers will want to read this, if they are not already well read inthis field.

The product of this project was a website and a game, the technologies(web technologies and Android with Java, respectively) involved will morelikely be known to the reader. If any of these technologies are not known,the reader is invited to Google for Android, Java, Javascript, jQuery, HTMLand CSS as these topics are very involved and in depth. As such they arenot described here. It is unlikely that the reader need a deep knowledgeof the Android platform or the web technologies used, but a cursory glanceover them is given later in this chapter.

2.1 The National Curriculum

The National Curriculum is a statement set by the government that de-scribes what schoolchildren are expected to know and by what age. Becausethis project involves creating a syllabus for cryptography, the National Cur-riculum had to be consulted. The National Curriculum for England andWales can be found in [3].

The National Curriculum is split up into age brackets called ‘key stages’.

11

There are four key stages in total:

• Key Stage 1 (KS1): ages five to seven

• Key Stage 2 (KS2): ages seven to eleven

• Key Stage 3 (KS3): ages eleven to fourteen

• Key Stage 4 (KS4): ages fourteen to sixteen.

Each key stage is split further into a number of curricula, one for eachsubject like Mathematics, English and Science. Each curriculum is furthersplit into multiple syllabi. For instance, Mathematics in KS3 is split intoalgebra, statistics, geometry and so on.

There is currently no syllabus in the National Curriculum similar tocryptography. Mathematics would be the natural umbrella for cryptogra-phy as it would fit in nicely with algebra, number and statistics. Algebrais used to help define and use ciphers - the main product of cryptography.Number and Statistics are used in the and the analysis side of cryptography.This analysis makes use of powers, mathematical operators (addition, mul-tiplication, subtraction, division) and the properties of number sets, whichcome under the Number syllabus. This analysis also uses statistics which,unsurprisingly, comes under the Statistics syllabus.

2.2 Classical Cryptography

Broadly speaking, cryptography is the study of ciphers. A cipher is a methodused to conceal the contents of one’s correspondence with another party, i.e.a method that changes data so that only the intended recipient can readit. Classical cryptography refers to ciphers created before computerisation.This includes all ciphers invented before the creation of the Rotor Machines(the first mechanised encryption devices, creating during WWII). Moderncryptography refers to ciphers built after the invention of the Rotor Ma-chines. These are the kinds of cipher in use today to protect things likesecure links, email and wi-fi. They include DES (Data Encryption Stan-dard) and AES (Advanced Encryption Standard).

2.2.1 Why Classical Cryptography?

Classical cryptography is always the starting point for learning about ciphersand secret writing. The more modern aspects cannot be well understooduntil classical cryptography is. Thus, the syllabus must start there. This

12

project is aimed at KS3 schoolchildren. By this age, schoolchildren have anexcellent grounding in number, a good knowledge of algebra and some goodstatistical knowledge. These are the requirements of classical cryptography.Classical ciphers are based on simple algebra and their analysis is based onsimple statistics (ratios, rates, percentages) and some simple number theory(sizes of sets).

Moving any further is too ambitious. Modern cryptography could not betaught as well, there are university courses on modern cryptography alone,there is no way a modern cipher like DES could be taught in the timeavailable. Not only this, but binary is only just introduced in Computing(the new curriculum) at KS3. Rotor machines, also, would be too far, withnot enough gain. The working of a rotor machine is not so different fromother classical ciphers (discussed shortly), their only strength came fromtheir mechanisation. There would be no point including this.

It can be seen, then, that classical cryptography and classical cryptog-raphy only will encompass this project. The rest of this section describesthe ciphers used throughout the rest of this report and the project. Thisinformation is effectively a collation and reproduction of [4, 5, 6, 7].

2.2.2 What is a Cipher?

A cipher is used by communicating parties to hide messages from people whomay read them in transit. There are two parts to a cipher: the encryptionmechanism and the decryption mechanism. They encryption mechanismtakes the message, called the plaintext, and transforms it in such a way thatno one but the intended recipient(s) can read it. This form is called theciphertext. The ciphertext is decrypted by the decryption mechanism backto the original plaintext message.

In order for it to be secret and decryptable, the ciphertext has to dependon the plaintext and another piece of secret information, called the key. Thekey is shared by all communicating parties and no one else. The method bywhich the plaintext and key are mixed to produce the ciphertext dependson the type of cipher. So that is what a cipher is: a particular method oftaking a plaintext message and a key and creating ciphertext that can onlybe decrypted (but always can be decrypted) by someone with the same key.

Some ciphers are better than others and one of the main goals of cryp-tography is to build the best cipher possible. The strength of a cipher (orencryption scheme) is how easy it is to decrypt some ciphertext withoutbeforehand knowing the key. This can be done in two ways. The first andsimplest is the ‘brute force attack’. In the brute force attack, all possible

13

Figure 2.1: Illustration of the working of a cipher.

Plaintext a b c d. . .

w x y z

Ciphertext d e f g z a b c

Table 2.1: Some of the encryption table for a Caesar Cipher with a key ofthree.

keys are tried until a plausible decryption is found. This is easy if thereare few possible keys. The second method is more sophisticated, it is calledcryptanalysis. This involves studying the statistical properties of the cipher-text (letter frequencies and so on) to try and work out the cipher used, thekey, and/or the plaintext directly.

Some classical ciphers are explained below. Please note, these cipherscan be adapted for use on most alphabets and languages, but for the sakeof simplicity, they are presented to work on the English language.

2.2.3 The Caesar Cipher

One of the earliest and simplest ciphers, the Caesar Cipher is the classicstarting point for anybody looking to learn about cryptography. It is tocryptography what ‘Hello World’ is to programming.

The Caesar Cipher encrypts letter by letter (i.e. it is a stream cipher).The encryption process is a simple modulo based function. The key is anumber < 26 that defines a ‘shift’ of the alphabet. Each letter is thenencrypted by replacing it with the letter key places to the right in thealphabet. As each letter is always replaced with the same letter, this definesan encryption table. Table 2.1 shows such a table, where the key is three.

14

Plaintext a b c d. . .

w x y z

Ciphertext y r t b z e c d

Table 2.2: Some of an example arbitrary substitution table.

The cipher can be expressed mathematically as in Equation 2.1. Eachletter is represented as a number (a = 0, b = 1, c = 2, . . . ) and then theencryption is just addition modulo 26. Decryption is just subtraction.

cn = pn + k mod 26 (2.1a)

pn = cn − k mod 26 (2.1b)

Where:

• cn is the nth letter of the ciphertext

• pn is the nth letter of the plaintext

• k is the key

As there can be only 25 effective keys, it is very susceptible to a bruteforce attack and is not in any way secure.

2.2.4 Arbitrary Mono-Alphabetic Substitution Cipher

The weakness of the Caesar Cipher is its small number of keys. This weak-ness can be overcome easily and effectively by changing the substitutionmethod. Instead of replacing each letter with one a little further down inthe alphabet, replace it with an arbitrarily chosen one. Table 2.2 shows apossible substitution table for this kind of cipher.

However, this is still not even close to secure. As each letter is alwaysreplaced by the same letter, the statistical properties of the plaintext arepreserved in the ciphertext. These properties can be analysed to easilybreak this cipher. In fact, many newspapers have breaking one of theseciphers in their puzzle sections.

2.2.5 The Playfair Cipher

The Playfair Cipher is much newer than the Caesar Cipher, and is far moresophisticated. It uses a 5 x 5 square as a key and thus requires a 25 letter

15

P L A Y FI R B C DE G H K MN O Q S TU V W X Z

Table 2.3: The key square created from the keyword ‘PLAYFAIR’

alphabet to work (in fact will work on any language whose number of lettersis a square number by changing the size of the key). For it to work with theEnglish alphabet (which has 26 letters), a letter has to be removed. Usually,the letter ‘j’ is replaced with the letter ‘i’.

Key Creation

The key is generated by use of a keyword. The letters of the keyword areentered into the square left to right, top to bottom. Any duplicates areignored. Then the rest of the square is filled using any remaining letters inthe alphabet in question. Table 2.3 is the key square generated from thekeyword ‘PLAYFAIR’.

Cipher Operation

The Playfair Cipher is a pairwise cipher, it operates on pairs of letters at atime (i.e. a block cipher with a block size of two letters). The two lettersin a pair must be different, if next pair of letters to be encrypted are thesame (e.g. two ‘l’s) the second left in the message and an ‘x’ is used instead(this could be any letter, as long as it is kept consistent and is known by theother communicating party), an ‘x’ is also used if there is only one letterleft to encrypt.

The position of the pair of letters in the key square determine the ci-phertext pair produced. There are three rules to follow:

1. If both letters are in the same row, the letters on the right are used(wrapping if necessary). For instance if the next two letters were ‘af’and the keyword was ‘playfair’, as above, the ciphertext letters wouldbe ‘yp’.

2. If both letters are in the same column, the letters below are used(again, wrapping if necessary). For instance, if the pair is ‘rv’ and thekeyword was ‘playfair’, as before, the ciphertext letters would be ‘gv’.

16

Plaintext Pairs Ciphertext

Balloon Ba lx lo on HB YV RV QOJam Ia mx BP KZPlayfair Pl ay fa ir LA YF YP PB CVIncorrect In co rx re ct EU RS CV IG DS

Table 2.4: Examples of words encrypted with the Playfair Cipher and thekeyword ’PLAYFAIR’.

3. Otherwise, the letter in the same row as the first and the same columnas the second, followed by the letter in the same row as the secondand the same column as the first is used. For instance, if the pair was‘ph’ and the keyword was, again, playfair, the pair produced would be‘ae’. Another example, ‘co’ becomes ‘rs’.

Decryption uses the reverse process, using the letters to the left and above.The third rule actually remains the same.

The Playfair Cipher is a significant improvement over the Caesar Cipherand the Arbitrary Substitution Cipher because it is polyalphabetic - eachplaintext letter can be encrypted by many other letters. This makes statis-tical analysis harder, but not impossible. The Playfair Cipher is still fairlyeasy to break by looking at the digraph frequencies - frequencies of pairs ofletters.

2.2.6 The Hill Cipher

The Hill Cipher is also a block cipher, however the block size is chosen bythe user to be m. The transformation performed by the Hill Cipher thenoperates on m letters. It can be expressed as a series of m linear equationsor a matrix equation of the form C = PK mod 26 where C and P arerow vectors of size m and K is an m × m matrix. The elements of C arethe ciphertext letters (represented as numbers, a = 0, b = 1, c = 2, . . . ),the elements of P are the plaintext letters to be transformed and K is thekey matrix whose elements are numbers < 26 (these can also be seen asletters). The key matrix K has to be invertible and should, therefore, bechosen randomly from the set of allowable matrices.

The operation of the Hill Cipher effectively boils down to two equations,one for encryption and one for decryption. Equation 2.2 is encryption andEquation 2.3 is decryption, both when m = 3.

17

Keyword lemonMessage attackatdawn

Repeated Keyword lemonlemonle

Table 2.5: The keyword is repeated to be as long as the message in theVigenere Cipher.

(c1c2c3) = (p1p2p3)

k11 k12 k13k21 k22 k23k31 k32 k33

mod 26 (2.2)

(p1p2p3) =

k11 k12 k13k21 k22 k23k31 k32 k33

−1

(c1c2c3) mod 26 (2.3)

Encryption and decryption is just the process of splitting the messageinto blocks of m letters and applying the Equation 2.2 for encryption andapplying Equation 2.3 for decryption.

The number of keys is the same as the number of invertible m × mmatrices modulo 26. Thus, there are at most log2(26m

2) keys. The cipher

resists statistical analysis, but it is linear in its operation. Consequently,ciphertext is linearly related to the plaintext and the key. Both can befound by linear analysis without too much effort.

2.2.7 The Vigenere Cipher

The Vigenere Cipher is one of the strongest ciphers from the classical era.It, in fact, remained practically unbreakable for three centuries after it wasfirst put forward in 1553. It was so strong that is was nicknamed ‘le chiffreindechiffrable’ which is french for ‘the indecipherable cipher’.

The key is a word of length m. There is no restriction on the keywordand thus there are arbitrarily many keys. The keyword is repeated to beas long as the message to be encrypted. For example, if the message to beencrypted was ‘attackatdawn’ and the keyword was ‘lemon’, the keywordwould be extended to be ‘lemonlemonle’.

During operation, letters are treated as numbers modulo 26 (a = 0, b= 1, c = 2, . . . ). The cipher is a stream cipher, i.e. it works letter byletter. Each letter of the message is encrypted with the Caesar Cipher, thekey used is determined by the keyword. The nth letter of the message is

18

encrypted with the nth letter of the (repeated) keyword. Equation 2.4 showsencryption mathematically. Decryption, shown mathematically in Equation2.5, works in the same way, the nth letter of the ciphertext is decrypted withthe Caesar Cipher using the nth letter of the (repeated) key.

cn = CaesarEncryption(pn, kn) (2.4a)

cn = pn + kn mod 26 (2.4b)

pn = CaesarDecryption(cn, kn) (2.5a)

pn = cn − kn mod 26 (2.5b)

Where:

• cn is the nth letter of the ciphertext

• pn is the nth letter of the plaintext

• kn is the nth letter of the key

The easiest way to break this cipher is to find the length of the keyword.Then the cipher breaks down into a number of Caesar Ciphers, each of whichcan be broken individually quite easily. How to find length of the keyword ina Vigenere Cipher will not be explained here, but the Kasiski Examination[8] is one way. A good explanation of the Kasiski Examination can be foundin [9]. The main weakness that is exploited is the fact that the key repeatsand thus repeated sections may be encrypted identically.

2.2.8 The One Time Pad

The One Time Pad is the ultimate upgrade to the Vigenere Cipher. En-cryption and decryption work in exactly the same way, but the key is nolonger chosen. Instead, the key is a truly random stream of letters, whichnever repeat.

With the key being completely random, the ciphertext bears no statis-tical resemblance to the plaintext. This pretty much makes cryptanalysisimpossible. As the only other weakness of the Vigenere Cipher is the factthat the key repeats, this cipher has no weakness. This means the One TimePad is completely invincible and can be mathematically proven so. It offersperfect secrecy and is the only such cipher. The reason it is not used moreis because of the difficulty in creating and securely transporting genuinelyrandom numbers.

19

Figure 2.2: Web usage per platform in the past four years. Image Credit:Global Stats

2.2.9 Steganography

Though not strictly cryptography, [4] gives a nice description of steganog-raphy - the practice of hiding messages inside other, seemingly innocuous,messages. Some classic examples include invisible ink, and the first letterof every sentence in a letter. Some modern examples include informationhidden in pixels in a photograph or hidden text files in silent parts of a song.

Even though it is not cryptography, it is included here because it is re-lated and can provide a nice, interesting tangent for teachers and schoolchil-dren. It could be used as a fun activity after the hard work of learning theciphers.

2.3 Modern Web Development

Web development has changed in recent years. The swift rise in mobilebrowsing has led to mainstream responsive design. Responsive Design isthe process of planning for and coping with the user changing devices and‘responding’ to this change. Instead of a dedicated mobile, desktop or tabletversion of the website, the design allows for the contraction, expansion andhiding of elements, depending on the device the site is being viewed on. Formore information, [10] is a good resource.

A few years ago a responsive website was progressive and cool, today it

20

is a requirement. This emphasis on the need for responsive design has led tocreation and distribution of many platforms and templates allowing for therapid development of responsive websites. Some of these include Bootsrap[11], Foundation [12] and Gumby [13]. Each of these, in their own way,include styles and javascript for building great looking, responsive websitesquickly.

2.4 Android Game Development

The Android platform is maintained by Google. A mass of documentationand help is provided by Google for designers, developers and distributors.The interested reader should start with [14]. For the sake of brevity, theinner workings of the Android platform will not be discussed here. Indeed,knowledge of the Android platform is not particularly required to understandthis project, other than a brief overview of an Activity, which will be givennow. An Activity is a class in the Android framework and is the notion ofa screen on a mobile device. An Activity is a distinct piece of work that anapplication does, every Activity must have at least one.

Games can be large, complex pieces of software that can have multiple,complicated interactions. Therefore it can be useful to use a frameworkto mitigate the negative effects this complexity can have and also expeditedevelopment. Again, there are a number of frameworks out there, includingAndEngine [15], Citrus Engine [16] and a framework proposed by Zechnerand Green in [17]. Knowledge of these frameworks is not a necessity tounderstanding this report as the components required are introduced whenneeded. These references are here merely for the interested reader to consultif they wish.

2.5 Other E-Learning Environments

There is a wide range of e-learning environments available. One of the goalsfor this project was to build a learning environment, so it was wise to do atleast a quick survey of some of these. Some of these include SAM Learning[18], BBC Bitesize [19], Codeacademy [20] and Udacity [21]. Table 2.6 showsa brief comparison of these environments and more detail is added below.

Some of the main points were taken and used in the project. Two mainthings were taken away from this. The first and most obvious is that eachenvironment allows the user to test their own knowledge. The second thing

21

Name Subject Audience Style Gamification

SAMLearning

Various KS3,KS4

Revision by ques-tions presented indifferent interactiveways

School offersprizes to stu-dents that usethe system alot

BBCBitesize

Various AllSchool-children

Present informa-tion as text andsometimes videos,also allows users totest themselves

None

Codea-cademy

Program-ming

Anyone Text based ma-terial, immediatepractical applica-tion

Badges, tro-phies andpoints

Udacity VariousSTEM

subjects

Anyone(assumes

16+)

Short lectures fol-lowed by course-work and an exam-ination

Progress bars,certification

Table 2.6: Comparison of the SAM Learning, BBC Bitesize, Udacity andCodeacademy e-learning environments.

taken away from the survey was the amount of ‘gamification’ 1 that wasused. Each environment (except BBC Bitesize) rewarded the user for theirprogress and successful application of their knowledge.

2.5.1 SAM Learning

SAM Learning is an e-learning environment built to be used by secondaryschools (KS3 and KS4, 11-16 years old) in the UK to help and encouragetheir students to revise. This environment focusses less on the teaching ofthe material, and more on the revision of it. Consequently, the environmentmainly asks questions of the user, to test their knowledge. These usuallytake the form of some kind of drag and drop interaction or drop down optionclicking over multiple screens. At the end of the question the student is toldhow how many they got correct and which ones were wrong.

1Using game-like elements in non-game environments.

22

Figure 2.3: Screenshot of the SAM Learning teaching environment. ImageCredit: SAM Learning

The system tracks usage and progress and this data is available to theschool. The idea is that the school rewards students for what they havedone. Possible prizes are for: time on the system, most questions answered,most tries taken, e.t.c.

2.5.2 BBC Bitesize

Bitesize is a service provided by the BBC for schoolchildren of any age.It is not associated in any school in any way, but does maintain materialcovering nearly every subject, exam board and key stage, including somehigher and further education material. There is no reward system, trackingor accounts of any kind but remains popular because of the multitude ofways the material is presented. There are pages of dry text and pictures,but there are also some videos and animations, as well as extensive test

23

Figure 2.4: Screenshot of the BBC Bitsize website. Image Credit: BBCBitesize

yourself capabilities. There is also a TV show produced by the BBC calledBitesize which does much the same thing.

2.5.3 Codeacademy

Codeacademy is an online learning environment that aims to teach anybodyto program. The teaching methodology used here is quite straight forward.Users are given access to multiple ‘tracks’ each of which aims to teach acertain language. Each of these is split into sections and the sections aresplit up into screens. Each screen presents a small piece of information andallows the user to immediately apply this information.

Codeacademy also tracks progress, but it is not affiliated with any otherentity. Instead there are no prizes, but achievements and badges are awardedfor completing actions. Each user has an account where these achievementscan be shown off.

2.5.4 Udacity

Udacity is another online environment. Udacity is like an online university,where anyone can enroll. Like a physical university, there are courses and

24

Figure 2.5: Screenshot of the Codeacademy learning environment. ImageCredit: Codeacademy

these courses have: lectures, resources, examples, coursework and even afinal exam. Each course can be pursued in the user’s own time and thelectures are very short (most less than five minutes long).

There is much less of a reward system here. Progress is tracked andthis is displayed to the user, but the real reward comes at the end, whenthe examination (which can be taken multiple times) is passed and theuser is granted a certificate. The certification process is accepted by somebusinesses as part of a CV, so the reward is very, very real.

25

Figure 2.6: Screenshot of the Udacity learning environment. Image Credit:Udacity

26

Chapter 3

Design

This chapter describes the design of the project. The project was not devel-oped under a waterfall development philosophy and therefore was not splitinto discrete design and implementation phases. Both design and implemen-tation were undertaken cyclically. That being said, this chapter focussessolely on the design. This should make the report easier to read.

This chapter begins by describing the syllabus that was created. Thenmoves on to some very general design points, covering why two separatetools were built, before the tools themselves are described. The sections oneach tool cover what particular platforms and frameworks were used andwhy and also explains how the main classes of each interact.

3.1 A Cryptographic Syllabus

The National Curriculum is broken down in key stages and each stage issplit into curricula for each subject area (Maths, English, Science, e.t.c.).Each curriculum has a purpose, some aims and a number of subject syllabi.An entire cryptographic curriculum would be infeasible in a project such asthis, so only a syllabus for cryptography has been created. This is syllabusis envisioned to occupy a space under the Maths or Computing curricula.

The syllabus is presented below, it follows the style of the syllabi pre-sented in the National Curriculum (see [3]). The aim of the syllabus is tointroduce the ideas of cryptography (secrecy, strength, substitution, anal-ysis, . . . ) by way of teaching a number of different concrete ciphers, witheach of them introducing a new layer of strength. The order of the ciphersin the syllabus is the suggested teaching order. Not only do they increasein strength, but they also follow chronologically.

27

Of the ciphers introduced in Section 2.2, the Hill Cipher has been leftout, as has Steganography. The reason for dropping the Hill Cipher is thefact that it is too complex, it relies on matrix multiplication, which is muchtoo advanced for the audience (11-16 years old). Moreover, its cryptanalysisrelies on linear analysis, again, far too advanced. Steganography has beenleft out, although the point made Subsection 2.2.9 still stands, it would makea nice, fun, non-curricula activity.

3.1.1 The Syllabus

Pupils should be taught to:

• know what cryptography is and why it is used

• know what a cipher is

• know what a key is

• know what a brute force attack is and when such an attack is appro-priate

• know what cryptanalysis and when its use is appropriate

• understand the following ciphers, including their key’s, how to encryptand decrypt messages with them, how strong they are and why:

– the Caesar Cipher

– the Playfair Cipher

– the Vigenere Cipher

– the One Time Pad.

This is short and fairly vague, but is in-keeping with they style set outin the National Curriculum. Appendix A provides some very basic teachingmaterial and serves as a more in depth syllabus.

3.2 General Design

In general terms, there are a few major requirements for the system as awhole. It has to allow the user to learn the content of the syllabus and hasto allow the user to test their knowledge of this syllabus. Moreover, it hasto be available to everyone, education cannot be allowed to discriminate.

28

As described in Section 2.5, one the things used consistently in othere-learning environments is gamification: the application of typical gameelements to other areas, in the hope of increasing user engagement [22].This project decided to take gamification one step further; instead of justbuilding a learning environment and shoe-horning a reward system in, afully fledged game was built along side the learning environment.

In order to make the teaching material open to as many people as possi-ble, a wesbite called CryptoLearn was built. The game, on the other hand,is difficult to make accessible to everyone. What can be done, however, ismake it open to as many people as possible. If more time was available, thegame would have been deployed on more platforms (including iOS, Windowsphones and on the web), as it is, the game is deployed on Android only.

3.3 CryptoLearn Design

This section describes the design of the website, CryptoLearn. It wasbuilt using many modern web technologies, including HTML5, CSS3 andJavascript/jQuery. Also, the scripting language PHP was used to decreasethe amount of mark up needed. PHP was chosen over other web program-ming languages like Ruby because of the its simplicity. The website wasnever going to be complex at a server side so only a small and simple setof server side functions were ever going to be needed, thus PHP was thepractical choice.

The rest of this section describes the requirements for the website, whyBootstrap was chosen as the framework to use, the architecture and thedesign of the website.

3.3.1 Requirements

The website must:

1. display the content of the learning objectives

2. allow the user to test their knowledge

3. be interactive

4. be responsive

5. be accessible.

29

These requirements are easily translatable into the pages required: apage to introduce the concepts, a page for each cipher, and pages to testknowledge of the concepts and ciphers. The third requirement ensures thepages are not just a dry wall of text. It ensures that diagrams and examplesare also included. This can be achieved with jQuery which was chosen be-cause of the amount of built in functionality, the quality of its documentationand its ease of use. The fourth and fifth requirements ensure the website isopen and available to all and help inform the choice of framework.

3.3.2 Architecture

The website requires pages for the presentation of the information for eachcipher and pages where the user can test their knowledge of each cipher.Each of these was given an individual page, keeping the pages short andthus shortening the attention span needed. This leads to nine pages intotal: an introduction page (one), a page for each cipher (five) and a pageto test each cipher (nine).

With the pages and the content decided upon (in the sense that thecontent is the presentation of the learning objectives), the next thing todescribe is the architecture the website. The website has been structuredmodularly, keeping .php files, .css files, .js files e.t.c. in separate foldersnamed appropriately.

The DRY (Do not Repeat Yourself) principle was taken into account inthe design. This meant common parts of the site were housed in one placeand included into each individual page using PHP or HTML headers. Thecommon parts include the header and the footer, most of the Javascript andjQuery and most of the CSS stylesheets.

Following on from this, the pages that present the information abouteach cipher are likely to be similar to each other. The same can be said forthe pages that allow the user to test themselves. It seems appropriate, then,to have one page for each (a cipher page and a test page) and dynamicallybuild them when requested. This means that the top level of the website hasan index page (the homepage) a cipher page and a test page which load theircontent dynamically from: a folder called php for the content, a folder calledjs for the Javascript files and a folder called css for the CSS stylesheets.

The architecture is shown in Figures 3.1, 3.2 and 3.3. Figure 3.4 holdsthe key. The index page shares no common elements with the cipher or thetest page, so it often looks isolated. This will be explained in more depthwith the reset of the implementation. The architecture of the Javascript filesdeserves more explanation. The ciphers.js file holds the implementation

30

Figure 3.1: The architecture of the .php files in CryptoLearn.

Figure 3.2: The architecture of the .js files in CryptoLearn.

31

Figure 3.3: The architecture of the .css files in CryptoLearn.

Figure 3.4: Key for the architecture diagrams.

of the ciphers, the main.js file holds the listeners for the onClick eventsthat run the diagrams and the cipher examples, the plugins.js file holdssome more general functions for listening to onClick and onKeyDownevents.

3.3.3 Framework Choice

In the end, Bootstrap was chosen as the framework for CryptoLearn. Boot-strap was first developed as a style guide at Twitter and was first and fore-most a method of developing a clean, good looking, consistently brandedwebsite. Over time it developed in to a mobile-first responsive and accessi-ble framework. Some of the reasons Gumby and Foundation were not chosen

32

Figure 3.5: Screenshots of CryptoLearn showing the difference on largeand small screens.

are described soon. The files for the framework are not including the figuresin the previous section for the sake of simplicity; each main file (index.php,cipher.php and test.php) includes each of the Javascript and CSS stylesheetfiles from the Bootstrap folder.

Gumby requires a lot of installation and a big set up time that Bootstrapsimply does not - just download and go. More importantly, the Javascriptfunctionality available in Gumby is very limited when compared to Boot-strap, as are the accessibility features. As for Foundation, it suffers fromthe opposite problem, it has many features and add ons, most of whichwould never be needed. The learning time is therefore greater than neces-sary. This also makes it bigger (slowing down page loads) than required. Inaddition, the accessible features are easier to use in Bootstrap, as are somethe Javascript components. Also, the base styling is subjectively nicer inBootstrap than in Gumby and Foundation.

3.3.4 Visual Design

This is not a graphic design project. Therefore, the visual design is not oneof the main areas. That said, a good, aesthetically pleasing design is one ofthe keys to a good user experience (UX) [23]. Because of this, some effortmust be made to make the website nice to look at, as well as easy to use.

There are a few key things that have been done in order to make thewebsite look good. The first thing is the use of Bootstrap styles. Theseare well balanced and built by professionals and take the onus away fromthe developer to make content look good. Second, the colour scheme is keptconsistent, both within itself and with the users expectations. Cryptographywill likely bring connotations of the Matrix films and hacker films in general.

33

These nearly all feature black screens with green text. The colour schemeused in the website matches this - with a modern twist. The final thing issplitting of content on a page. In order to make it look less daunting, thecontent is split into tabs. This makes the website look cleaner and easier toread and use. Figure 3.5 shows the how the website looks on large (desktop)screens and on mobile.

3.4 CrypTD Design

This section describes the design of the game, CrypTD. CrypTD was builtfor the Android platform and therefore is implemented in Java. Androidwas chosen because of its extensive documentation, examples and the easeof testing an Android project, i.e. on an Android device. It would havebeen very difficult to get evaluations if the project had been deployed onWindows Phone (because so few people own them) and very expensive totest, develop and get evaluations if the project was deployed on the iPhone.

The rest of this section describes the requirements for the game, whythe framework proposed by Zechner and Green in [17] was chosen as theframework to use, and the architecture of the game.

3.4.1 Requirements

The game must:

1. challenge the user’s knowledge of the learning objectives

2. introduce metaphors in the game for the learning objectives

3. use the terminology used in CryptoLearn

4. encourage the user to play multiple times.

These learning objectives do not translate into a design as easily as theCryptoLearn requirements did. The first three objectives just ensure thatthe game does indeed relate to cryptography and the learning objectives setin Section 3.1. The first and last ensures the game does indeed reinforcelearning and attempt to encourage users to play multiple times, allowingreinforcement to occur.

34

3.4.2 Game Genre

There are many types of game that could be legitimately used as a toolfor the reinforcement of a particular syllabus. The type eventually chosenwas tower defence. In this kind of game, the user takes the position of‘commander’, in control defensive structures called ‘towers’. There are manyvariants to this genre, the general aim is to defend your ‘base’ against anumber of enemies called ‘creeps’. This is done by building the towers,which shoot at the creeps.

The tower defence genre was chosen because of how easily it fit as ametaphor for cryptology. The creeps are ciphers, the towers are cryptologists/ decryptors that shoot at the ciphers to decrypt / destroy them. Moreover,it was easy to add challenges into the game. Tapping on a cipher as it ismoving brings up a decryption challenge and, if the user gets it right, thecipher is destroyed. Also, in this game, the towers can randomly breakdownand are fixed by the user tapping on them and answering a question aboutcryptography. Here, both theoretical questions and practical questions canbe asked of the user - fixing towers and destroying enemies, respectively.

3.4.3 Choice of Framework

The framework proposed in [17] (henceforth called the ZG framework) waschosen because the framework itself is presented as a tutorial for game de-velopment. This meant it had extensive documentation and could be easilyand endlessly customised. All the other frameworks simply did not have thedocumentation or power to make them worthwhile. The ZG framework issmall and easy to to add to a project. In fact installation is not requiredat all, instead the package is just copied into the project folder and theCrypTD classes extend them where necessary.

The ZG framework is effectively an interface, defining all the componentsneeded to make a game, along with an implementation. Not all of thecomponents defined were eventually required in the making of CrypTD,including the classes relating to audio. Figure 3.6 shows the framework’sinterface. To save space, the classes not used by CrypTD have been left out.The following subsection explains how the ZG framework was used.

3.4.4 Architecture

The ZG framework comes with an implementation to the interface, theclasses of which use the same names. To build a game using the ZG frame-work, the Screen and Game classes are extended. The other classes can be

35

Figure 3.6: Diagram of the ZG Framework.

Figure 3.7: Sequence of Screens in CrypTD.

extended, but this is not always necessary.The Game class is the main top level class for the entire application. The

entire game runs in one Activity (see [14]). The Game class is extended andthis new class acts as a wrapper for the Activity. The new Game class, calledCrypTDGame in this case, contains a number of Screen classes. These areextended to add the functionality of the particular game. This means thefirst thing to is define the number of screens in the game, their function andtheir order. This is shown in Figure 3.7.

The most important screen here is the GameScreen. The other screensare simple, and so they will not be discussed in length here, which allowsmore focus on the more complex, and more interesting GameScreen class.However, some small points will be made. The SplashScreen loads theresources used by the game, these are stored in a class called Assets, usedby all classes in CrypTD. The MainMenuScreen displays two buttons,both of which load the ChooseLevelScreen. The ChooseLevelScreen

36

Figure 3.8: Domain class diagram of CrypTD.

allows the user to pick a level to play / view the high scores for, once chosen,either the GameScreen or the HighScoresScreen is loaded, dependingon the button tapped on the MainMenuScreen.

The next step is to design the actual game itself. With the frameworkand the genre discussed, the main domain objects are already known. Figure3.8 shows the domain model of CrypTD. The new only new things here arethe HUD and Tutorial classes. The HUD (Head’s up Display) is a bar atthe bottom of the screen. They are common in this type of game. Theygive the user a consistent way to check their state (number of lives, amountof gold). The HUD is also the starting point for tower creation, as well asbeing where the pause button is held. Tutorials are a way of telling the userhow to play the game, allowing for progressive disclosure.

Moving swiftly on, the domain classes are refined into system classes.In order to maintain readability, these will be split up roughly by function.Many pure fabrication classes are added in this refinement, this is becausethe complexity is fairly high and many are required to try to remove stateand function from the GameScreen class. The GameScreen class is centralto whole game and deserves a small piece of explanation on its own.

There are three states the GameScreen can be in: playing, paused orended (game over). The GameScreen has two major methods that run thegame. The first is the paint method which draws the state of the game onthe screen. The map, towers, enemies and HUD are drawn and an indicatorof the state is drawn.

37

The second major method is the update method. This advances thegame and deals with input from the user. When paused or ended, the gamedoes not advance. The GameScreen can also display two types of ‘sub-screen’. These display the tutorials and the questions. These are kept ina queue, in case a question or a tutorial is being displayed and anothertutorial should be displayed. When in the playing state, before normalinput or advancement takes place, the GameScreen checks to see if there issub-screen to display. If there is a tutorial screen at the head of the queue,the game model pauses to let the user read the information, if there is aquestion at the head, then normal advancement takes place - the user mustbe challenged. Both types of screen are dismissed by a tap from the user.Taps on question have to be handled specially though - if they got it rightthey should be rewarded, and punished if they got it wrong, but also thequestion must be dismiss-able with no state change.

Normal game advancement involves three things:

• checking for and dealing with user input

• updating the game model (moving enemies, dealing damage from tow-ers e.t.c.)

• checking for game over events.

Tutorials

A good place to start is with the tutorials. These represent the simplestfunctionality of the game. Figure 3.9 shows the design of the classes involvedwith this functionality.

There are a number of possible tutorial pages and the exact one to showis chosen at creation by selecting the appropriate Page enum member. TheGameScreen class handles the addition of tutorials to the queue, but theEnemySpawner class, which abstracts the creation of enemies away fromthe GameScreen class (explained shortly), can tell the GameScreen toadd one, this is required when a new type of enemy is to be spawned andthe user should be told about it.

Questions

The questions are split into two types: practical and theoretical. To allow forsome consistency, all the theoretical questions are created to fix towers andall the practical questions are for damaging enemies. This is also in-keepingwith the metaphor that the enemies are ciphers and decryption hurts them.

38

Figure 3.9: System class diagram of CrypTD, displaying classes related toshowing tutorials.

39

Figure 3.10: System class diagram of CrypTD, displaying classes related toshowing questions.

Figure 3.10 shows how the questions relate to the GameScreen class. TheGameScreen class responds to taps on enemies and towers by creating theappropriate questions and adding them to the sub-screen queue.

Tower Construction

The HUD has three icons for the three towers. Towers can be built on themap by dragging from their icon in the HUD to the desired location on themap. A tower cannot be built on the path or on top of other towers. Inorder to remove some state from the GameScreen class, the constructionof towers has been moved into a new class called TowerConstructor.

Construction now works like this. When in the playing state, the GameScreenclass (as part of normal game advancement) checks for touch events in theHUD, if a tower icon has been touched, the a new instance of the Towerclass is constructed and TowerConstructor is given the Tower instance.Until there is a touch up event, touch drag events are fired. Touch dragevents move the tower around the map and the touch up is the signal tobuild the tower in the current location. If the tower can be placed in thecurrent location when a touch up occurs, the map is informed and the towerstored by the GameScreen class.

Enemy Spawning

As with tower construction, enemy spawning has been moved to a separateclass to increase the cohesion of the GameScreen class. The class that

40

Figure 3.11: System class diagram of CrypTD, displaying classes related totower construction.

contains this functionality is called EnemySpawner. Enemies are spawnedat the end of a countdown, which gets shorter and shorter as the gameprogresses. The enemies spawned also get progressively harder, the first feware only Caesar Ciphers, then Playfair and eventually Vigenere Ciphers areintroduced. The first time a type of cipher is spawned, the enemy spawnertells the game screen to show a tutorial for it. The time until the nextenemy spawning is displayed to the user by painting the enemy spawner tothe screen.

Combat

Combat involves three things: the towers, the enemies (ciphers) and theprojectiles. The projectiles are what the towers fire at the enemies. TheGameScreen updates all three as part of the normal game advancement.This involves checking if any of the towers are ready to fire and moving theprojectiles and enemies. If a tower can fire, it will return an Enemy instanceas part of its update method, the game screen will then create a projectile ofthe same type as the tower with the destination coordinates the same as theenemy returned by that tower. When a projectile reaches its destination,it returns true from its update method and the GameScreen damages theassociated enemy. When an enemy reaches its destination (the players base)it returns true and the game screen tells the HUD (not shown) to removea life from the player. When an enemy dies from damage, its doDamagemethod returns true and the GameScreen removes the enemy.

41

Figure 3.12: System class diagram of CrypTD, displaying classes related toenemy spawning.

Figure 3.13: System class diagram of CrypTD, displaying classes related tocombat.

42

And the Rest

There are some classes required in the design that have not, as yet, beenmentioned. This was to keep the descriptions and diagrams above as simpleas possible. They will, however, be mentioned here.

The first such class is the Assets class. This abstract and final classis used by practically all other classes, it holds the references for the imagefiles used for drawing the graphics. It also contains the constants relating totext size and colours. The images are loaded by the SplashScreen class.

The next such class is the Level class. The defining characteristic ofa level is the path the enemies follow when that level is being played. Hadthere been more time, more features could have been added such as specialtypes of enemy, multiple start and end points for ciphers, e.t.c., as it standsthe path is the only data held by a particular level.

As there are a number of levels, they have to be stored and loaded. Byputting this functionality into a class other than the GameScreen class,the cohesion and coupling of both are bettered. Also, the way the levelsare stored can be changed without affecting the GameScreen class (or anyother class). As it is, the levels contain hard coded paths. If the otherfeatures were added or if there was the option for user crafted levels, itwould have made sense to store the information in files and load it at runtime.

Another class that needs a description is the Ciphers class. The prac-tical questions are created dynamically and randomly - to offer the player agreater challenge; thus each of the ciphers portrayed in the game (the Cae-sar, Playfair and Vigenere Ciphers) require implementation. This is whatthe Ciphers class is for.

The final class that needs a mention is the Maths class. This has staticmethods for commonly used mathematical operations used in the game.These include checking if a point is inside a circle or a rectangle, and checkingif two circles or two rectangles intersect.

43

Chapter 4

Implementation

This chapter describes some of the the implementation of the project. Thishas been restricted to the interesting, important and difficult aspects. Thiswas to avoid this chapter being long, boring and tedious. The implemen-tation of the website, CryptoLearn, is discussed first. This is followed by adiscussion of the implementation of the game, CrypTD.

Both of these sections start with a short overview of the software, whatit does and how it is used. The classes and components introduced in theseoverviews are explained in more detail as the chapter progresses.

4.1 CryptoLearn Implementation

The website, CryptoLearn, was built using a wide variety of technologies.These include HTML, CSS, PHP, Javascript and jQuery and the Bootstrapframework. The work involved in creating the HTML and CSS mark up wasgreatly reduced through the use of Bootstrap. Thus, this part of the imple-mentation was quite easy and is not discussed further. PHP was used merelyto reduce the amount of HTML markup required and that was done throughsome very short inclusion scripts. Again, this part of the implementation isnot discussed further.

The work involving Javascript and jQuery, on the other hand, was muchmore difficult. These two technologies run the interactivity of the website.As this part of the work was important and difficult, it is discussed furtherin this section. But first, a short overview of the website, what it does andhow the user interacts with it.

44

4.1.1 Overview

Upon loading CryptoLearn in their browser, the user is greeted with thelanding (or cover) page. This page is more graphically intense than theothers and serves as a little bit of advertising, this is often done on modernwebsites. This page has a short introductory paragraph that explains whatCryptoLearn is and how to use it. There is also a large begin button thattakes the user to the basics page of the learn sector.

For users that have visited before, there are two dropdown links calledlearn and test. These split the website into two sectors. One for learningabout the ciphers and one for testing your own knowledge. The learn sectorhas five pages: one for each cipher and one introductory page; the test sectorhas four pages: one for each cipher. There is not a test page for the basicsbecause there is no specific knowledge introduced there.

Each page in the learn sector is broken down into small tabs. This wasdone for two reasons: (1) to reduce the vertical height of the website andalso to stop each page being a very long, dry wall of text and pictures thatmight scare the user. Each of the cipher pages have a key points tab, a tabexplaining the key, a tab explaining the function of the cipher and a tabexplaining the strengths and weaknesses of the cipher. The one time paddoes not have a page explaining the key (because it is just random) and theCaesar page has multiple pages of analysis (because the syllabus covers theCaesar Cipher’s analysis in more depth). The introduction page is split upinto an introduction tab and a vocabulary tab.

Each page in the test sector is also broken down in tabs. Each pageexcept the one time page has three tabs. One tab has a fill-in-the-blanksquestion about the theory of the cipher, another tab has a question thattests the user’s ability to encrypt using the cipher and the final tab has aquestion that tests the user’s ability for decryption. The one time pad pagedoes not have either an encryption or decryption practice question, this isbecause it works in the same way as the Vigenere Cipher does.

4.1.2 Sliders vs. Tabs

As mentioned in Section 3.3 and above, CryptoLearn is split into two sectorsand these sectors are split into pages and these pages are split up into tabs.This was done to stop the pages appearing daunting to users and make itmore likely that they will engage.

Tabs were used on the website, but the pages could have just as easilysplit up using a content slider. These are often used in websites to present

45

lots of information without taking up much vertical space. This is oftendone to keep important information ‘above the fold’ (or above the scroll)[24] which is often considered a priority for attracting customers and SearchEngine Optimisation (SEO) [25]. Content sliders are often animated, this ismeant to attract a customers attention. Tabs, however, are often much moresubtle and are more commonly used to present distinct pieces of informationin the same place, without taking up more room than necessary, i.e., exactlywhat was needed.

It follows that tabs were a better fit than sliders. Furthermore, tabs arebuilt into Bootstrap are used easily using the “nav-tabs” class. Slidersonly redeeming factor were the animations available which could possiblymore fun to interact with. This was felt patronizing and did not sway thechoice. A subtle fade animation was added to tab transitions to make thechange feel slightly more natural and improve the overall user experience.

4.1.3 Availability

Some of the important requirements of the website were that it had to be re-sponsive, cross-compatible and accessible. Software should not discriminateanybody from using it. This should be especially so in the case of education.This boils down to making sure:

• the website works just as well on mobile as on desktop (being respon-sive)

• the website works when viewed on any operating system or browser(cross-compatible)

• the website is screen reader friendly, .i.e., the website does not provideinformation via only colour or only images, i.e., all information is alsoavailable in text form (being accessible).

Being screen reader friendly is difficult to achieve with as much Javascriptrich content as is necessary, but possible as long as all buttons are givennames, contexts and full descriptions. Also, Bootstrap has a class called“sr-only” which hides the element on a visible screen, but allows screenreaders to access it, this is useful for drop-down navigation and for pro-viding textual information for icons such as ticks and crosses. Being cross-compatible is as simple as following standard to the letter, and mitigating forInternet Explorers quirks (luckily Bootstrap accounts for this in its styling).Being responsive requires only added the required classes to hide or showelements on particular devices.

46

Figure 4.1: Feedback for fill-in-the-blank questions is given in the form of atick or a cross on large screens, but comes with text on small questions.

An interesting quirk that came up in development merged the respon-sive and accessibility features. The test pages contain a fill-in-the-blanksdropdown question section. A paragraph is presented to the user with dropdowns in place of some of the words, the user has to pick the correct one.feedback is given in the form of a tick or a cross. For screen readers there isalso some attached text that reads either “correct, well done” or “incorrect,try again”.

When on a small screen, however, the drop downs take up the width ofthe screen - to allow easier use. This means the tick or the cross is pushedbelow the drop down. This would mean there is a lot of white space onthe right of the icon, which would not look so good. Instead of this, thescreen reader text is shown. This simultaneously provides better feedbackand looks better. This was achieved by creating CSS class “sr-only-lg”which is hides the text only on a large screen. The effect can be seen inFigure 4.1.

Listing 4.1: CSS code for a the sr-only-lg class.

1 @media (min-width: 768px) {2 .sr-only-lg {3 display: none;4 }5 }

47

Listing 4.2: Use of the sr-only-lg class.

1 <span class=’feedback positive-feedback hidden’>2 <span class=’glyphicon glyphicon-ok’></span>3 <span class=’sr-only-lg’>Correct, well done!</span>4 </span>5 <span class=’feedback negative-feedback hidden’>6 <span class=’glyphicon glyphicon-remove’></span>7 <span class=’sr-only-lg’>Incorrect, try again.</span>8 </span>

4.1.4 Ciphers

Javascript and jQuery were used extensively throughout CryptoLearn. Theyallow the website to be more interactive, more fun, more informative, andaltogether more useful. The implementation of the ciphers is separate fromthe HTML mark-up and from the Javascript and jQuery that runs the in-teractive diagrams, Figure 3.2 showed this.

The cipher implementation includes a map from letters to numbers andone from numbers to letters (this is just an implementation of a = 0, b =1, c = 2, . . . ). This is easier to understand and debug that a mathematicalconversion from ‘char’s to ‘int’s and back again.

The implementation also includes a number of utility functions includingshift which effectively does the core of the work of the Caesar Cipher. Itis shown in Listing 4.3. The Caesar Cipher, Vigenere Cipher, and One TimePad implementations are then just simple wrappers for this function usingfor loops; with the Vigenere implementation changing the key each timethrough the loop and the One Time Pad implementation just calling theVigenere implementation with a newly created random key.

The implementation of the shift function allows treatment of specialcharacters to be left upto the particular cipher using it. For instance, theCaesar Cipher throws all the characters at it, meaning special characters areleft in place. However, the Vigenere Cipher removes all special charactersbefore encrypting and decrypting in order to avoid any confusion with whichbit of the key to use (remember from Section 2.2 that the key is repeatedto fit the message, if special characters are included are they encrypted orskipped, if they are skipped, how long should the repeated key be?).

The Playfair Cipher is not like this, however. Instead, a completelydifferent set of functions is used. The first of which is the creation of the keysquare from a keyword. The key square is implemented, quite intuitively,

48

Listing 4.3: Implementation of the shift utility function.

1 var shift = function (k, char) {2 if (/[a-z]/g.test(char)) { // char is a lowercase letter3 var c = intFromChar(char);4 var temp = (c + k) % 26;5 // deal with negative numbers from mod6 var index = (temp >= 0) ? temp : temp + 26;7 return charFromInt(index);8 } // if9 else if (/[A-Z]/g.test(char)) { // char is an uppercase

letter10 var c = intFromChar(char.toLowerCase());11 var temp = (c + k) % 26;12 // deal with negative numbers from mod13 var index = (temp >= 0) ? temp : temp + 26;14 var shifted = charFromInt(index);15 return shifted.toUpperCase();16 } // else if17 else { // symbol, don’t change it18 return char;19 } // else20 } // shift

49

as a 5 × 5 matrix. The square is created using a clever trick. The keywordis pre-pended to a string containing the entire alphabet. Then duplicatesare removed, the trick is the way the duplicates are removed: the function(shown in Listing 4.4) reads the given string into another string, but ignoringcharacters that are already in the new string. This means the first characteris kept every time. When used by the key square creating function, thestring produced is the keyword followed by the rest of the characters in thealphabet, exactly as required. The (now 25 character long) string is thenread into the matrix left to right, top to bottom.

Listing 4.4: Implementation of the removeDuplicates utility function.

1 var removeDuplicates = function (string) {2 var result = ’’;3 for (var i = 0; i < string.length; i++)4 {5 if (result.indexOf(string.charAt(i)) == -1)6 result += string.charAt(i);7 } // for8 return result;9 }; // remove duplicates

From here the implementation of the Playfair Cipher is just a simpletranslation of the rules. Special characters are removed and odd-lengthmessages have an ‘X’ appended. Then there is a while loop, removing aletter, then looking at the next letter, removing it if it’s different and leavingit otherwise. Then the correct letters are pulled from the matrix.

4.1.5 Interactivity

Other than the Ciphers, Javascript and jQuery are used to bring interactivityto otherwise plain diagrams and text, they also run the test section. Thisis achieved through the use of HTML5 buttons and the onClick event.Any Javascript code can be placed in the onClick definition of a HTMLelement. However, in this project, the only thing written is a function call.This abstracts most of the Javascript to these functions, which are held ina separate file main.js, split into two parts. One part is dedicated tofunctions dealing with events triggered on the learn pages, the other dealswith events triggered on the test pages.

The functions in the first part of main.js mainly deal with encryptingor decrypting text and presenting it to the user. Because some of the ciphers

50

operate on special characters and some do not, the user may not understandfully how the output was achieved. To avoid this, all the functions that wrapencryption/decryption calls perform the same removal of special charactersthat the cipher function does and writes that back to the input. The otherfunctions in this file deal with creating and updating the key tables, theseare pretty simple examples of DOM (Document Object Model) manipulationand are not discussed further.

The functions in the second part deal with checking whether the user gota particular question in the test sector correct. The encryption / decryptionpractice questions are checked simply by performing the same operation theuser is asked to perform and checking the answer. If the user was told theiranswer was incorrect simply because there are capitals in one and not theother, it would annoy the user. To combat this, the strings are not compareddirectly. The whitespace is removed and the all letters converted to lowercase, then the strings are compared. To further reduce annoyance, the usercould have been given a correct answer if only one character was out, butin a subject like this, accuracy should be impressed on the user.

The fill-in-the-blanks questions are checked in an interesting, simple,quick, if slightly unsemantic way. The correct option in the select element isgiven the value ‘y’ and the other options are given the value ‘n’. This meantone function could deal with every page. The code is given in Listings 4.5and 4.6. There are two possible results: correct or incorrect, there is a spanclass for each and the necessary one has the hidden class removed. Theselect box is also highlighted. Some of the code in Listing 4.5 has beenshown before, as a an example of where the sr-only-lg class is used.

4.2 CrypTD Implementation

The application contains a number of screens the user moves through beforeand after playing the game. These were mentioned in Section 3.4. The onlyinteresting and difficult screen is the GameScreen class, which displaysand plays the actual game. Therefore, this is the only screen that will bediscussed here.

4.2.1 Overview

The first screen that loads is the SplashScreen, this just loads the re-sources the game requires. Once this is complete the MainMenuScreenloads, this presents two buttons to the user, allowing them to play the gameor view the high scores. Once a button is tapped, the ChooseLevelScreen

51

Listing 4.5: HTML mark-up of one of the fill-in-the-blanks questions.

1 <div class=’form-group blanks-question’>2 <select class=’form-control’>3 <option value=’n’> </option>4 <option value=’y’>secret. </option>5 <option value=’n’>on line.</option>6 <option value=’n’>on fire.</option>7 </select>8 <span class=’feedback positive-feedback hidden’>9 <span class=’glyphicon glyphicon-ok’></span>

10 <span class=’sr-only-lg’>Correct, well done!</span>11 </span>12 <span class=’feedback negative-feedback hidden’>13 <span class=’glyphicon glyphicon-remove’></span>14 <span class=’sr-only-lg’>Incorrect, try again.</span>15 </span>16 </div>

Listing 4.6: Function that checks the fill-in-the-blanks questions.

1 var checkBlanks = function () {2 // look up each question and check wether its3 // value is y or n4 $(’.blanks-question’).each( function (index) {5 if ($(this).children(’select’).val() === ’y’) {6 $(this).addClass(’has-success’);7 $(this).removeClass(’has-error’);8 $(this).children(’span.positive-feedback’)9 .removeClass(’hidden’);

10 $(this).children(’span.negative-feedback’)11 .addClass(’hidden’);12 } // if13 else {14 $(this).addClass(’has-error’);15 $(this).removeClass(’has-success’);16 $(this).children(’span.positive-feedback’)17 .addClass(’hidden’);18 $(this).children(’span.negative-feedback’)19 .removeClass(’hidden’);20 } // else21 }); // each22 }; // checkBlanks

52

loads, which displays all the levels of the game. Once one of these is tapped,either the game or the high scores screen loads, depending on which buttonthe user tapped at the main menu.

Once the GameScreen loads, the game starts. First, a few tutorialpages are displayed, these introduce the controls and the aim of the game(i.e. place towers to shoot creeps [ciphers] and try to survive for as long aspossible). Once the tutorials are read and dismissed, enemies start appearingand the player must build towers to destroy them. Towers can be sold andcan breakdown. Tapping towers and answering questions fixes broken ones,tapping enemies and answering a question destroys that enemy. Enemiesappear faster as the game progresses and eventually the enemies will getthrough the defences and the player will lose.

Once the player loses, they are shown their score and tapping movesthem to the high score screen. Tapping again from there moves them to themain menu where they can start again.

4.2.2 Implementation Description

Two functions are central to the running of the game: the update functionand the paint function. These two functions are repeatedly called by theAndroid operating system. The paint function is where drawing to thecanvas occurs. This is implemented quite easily with a switch statement anda number of for loops. More on this later. The update function is wherethe game model is updated. The implementation of this function is muchmore difficult and interesting. The core of this is still a switch statementand a number of for loops, but user input is also dealt with here, moreover,the interactions that occur inside the for loops are more interesting.

The game can be in one of three states, implemented as a private enuminside the Game class and stored in a variable called state. This variableis used to control the flow of the paint and update methods. This use isshown in Listing 4.7.

The states, then, define what the user can see or do at any one time.

• In the Playing state one of three things can happen:

– normal game play, towers shoot, enemies move, e.t.c.

– a tutorial screen is shown, normal game advancement does notoccur, but is current game play is shown in background

– a question is shown, normal game advancement (NGA) does oc-cur, and is shown in background.

53

Listing 4.7: The use of the state variable in the GameScreen class.

1 ...2

3 private static enum State {PLAYING, PAUSED, GAME_OVER};4

5 ...6

7 private State state;8

9 ...10

11 public void paint(float delta)12 {13 ...14 switch(state)15 {16 case PLAYING: paintPlayingState(); break;17 case PAUSED: paintPausedState(); break;18 case GAME_OVER: paintGameOverState(); break;19 } // switch20 } // paint21

22 public void update(float delta)23 {24 ...25 switch(state)26 {27 case PLAYING: updatePlayingState(); break;28 case PAUSED: updatePausedState(); break;29 case GAME_OVER: updateGameOverState(); break;30 } // switch31 } // update32

33 ...

54

• In the Paused state NGA does not occur and a ‘Paused’ screen isdisplayed. Eventually, the implementation changed to put the gameplay in the background - this was though to look slightly nicer.

• In the Game Over state, NGA can not occur because the game isover. The screen displays the user’s end score and when clicked takesthe user to the High Score screen. As with the Paused state, even-tually the implementation evolved to put the end game play in thebackground.

The game model is painted in each and every state (even though some-times it is only in the background). The paint method first paints all theobjects that required painting, then control enters then switch statement.The reader may wonder why there is a paintPlayingState if the gameis painted no matter what the state is. The reason is that whatever canbe delegated should be, and it turns out that the TowerConstructor(which deals with the user building towers) cannot be active in either thePaused or Game Over states, and so it cannot be painted in these states. Toprotect against variation and to reduce the code in the paint method, theupdatePlayingState was kept and all it does is call the TowerConstructor’spaint method.

In the update method two main things happen: user input is dealt with,then the NGA occurs. User input is dealt with by the handleUserInputfunction, which is shown in Listings 4.8 - 4.10. The code in Listing 4.8is concerned with whether or not a tower is under construction. This isdealt with first because touch events other than TOUCH DOWN are involvedand it makes it easier to read and understand, after it is dealt with onlyTOUCH DOWN events matter.

Once the drag and up events are dealt with, some more interesting thingsoccur. The TOUCH DOWN events are how the user interacts with:

• the items in the HUD - the tower icons and the pause button

• the items on the map - the towers and the enemies

• any sub-screens (tutorials or questions) that may be active

The interactions with HUD icons and enemies are simple, either the gamepauses, or new tower starts being constructed, or a new question is created.Dealing with the towers, however, is much more intriguing. Active towers(once a tower is tapped it becomes active - opening up the menu for fixingor selling the tower) are checked first. Active towers get precedence because

55

Listing 4.8: How user input is dealt with, part one - tower construction.

1 private void handleUserInput(List<TouchEvent> events)2 {3 for (int i = 0; i < events.size(); i++)4 {5 TouchEvent e = events.get(i);6

7 // if there is a tower under construction it must either8 // - be moved (TOUCH_DRAG)9 // - be constructed (TOUCH_UP)

10 if (towerConstructor.isBuilding())11 {12 if (e.type == TouchEvent.TOUCH_DRAG)13 // move tower14 towerConstructor.onDrag(e);15

16 if (e.type == TouchEvent.TOUCH_UP)17 // construct tower18 towerConstructor.onTouchUp(e);19 } // if20

21 ...

56

an active tower is more likely to be the center of the user’s focus (they arelikely to have just tapped it) and therefore subsequent taps are more likelyto be directed at them. If this was not done, it would be possible for asmall UI bug to occur. This bug is where two close towers continually swapactive states because each subsequent tap is assumed to be directed at theother tower. This can happen because towers react to taps close to them,not just directly on them. This is done because touching any object exactlyis difficult on a small touch device like a phone. By giving active towersprecedence, this bug is avoided.

The checkTap methods shown in Listings 4.9 and 4.10 return booleanvalues which may at first seem cryptic. Each tappable object in the gamehas a checkTap and they all return the same thing: whether or not thetap referred to that object. The value is used by the handleUserInputmethod to determine whether or not to return early - each tap should onlydo one thing.

The handleUserInput method is called at the beginning of the updatemethod. The rest of the method is concerned with with NGA, which isachieved by calling the update method of other objects. The code is shownin Listings 4.11 and 4.12. Again, some of the return values may appear cryp-tic, but it is not so. In order to reduce the complexity of some interactions,the classes associated with combat return an object relating to their role.Towers return the Enemy that it is targeting (shooting at) this update (ornull if it cannot fire at this time), Projectiles and Enemies return aboolean that refers to whether or not they have reached their target (anEnemy or the user’s base, respectively). In this way the GameScreen candeal with what should happen next, instead of over complicating the Tower,Enemy and Projectile classes.

The last things to discuss are the questions, in particular the practicalquestions. The theoretical questions are just randomly picked at run timefrom a list of hard coded questions and answers. The practical questions,on the other hand, are dynamically created at run time from a template.This involves choosing a random set of letters then picking a key at randomand encrypting or decrypting the chosen letters. For this, the ciphers (Cae-sar, Playfair and Vigenere) have to be implemented. This is done in theCiphers class. The ciphers implemented for the game are pretty simpleand are very similar to their Javascript counterparts explained in Section4.1. However the Playfair Cipher is implemented using a separate class forthe key called PlayfairSquare. This was to help with testing.

57

Listing 4.9: How user input is dealt with, part two - tower activation.

1 ...2

3 if (e.type == TouchEvent.TOUCH_DOWN)4 {5 // check active towers first - they should get

precedence6 // over inactive towers and everything else7 for (int j = 0; j < towers.size(); j++)8 {9 Tower tower = towers.get(j);

10 if (tower.isSelected() && tower.checkTap(e))11 {12 if (tower.isWorking())13 {14 // sell the tower15 towers.remove(tower);16 hud.setGold(hud.getGold() + tower.getCost() / 2);17 map.sellTower(map.getRow(tower.getY()),18 map.getColumn(tower.getX()));19 } // if20 else21 {22 // create a question that, when completed,23 // fixes this tower24 addSubScreen(new TheoreticalQuestion(this, g,

tower));25 } // else26 return;27 } // if28 } // for29

30 // now check the other towers - to activate them31 for (int j = 0; j < towers.size(); j++)32 {33 Tower tower = towers.get(j);34 if (!tower.isSelected() && tower.checkTap(e)) return;35 } // for36

37 ...

58

Listing 4.10: How user input is dealt with, part three - checking enemiesand HUD icon taps.

1 ...2

3 // check towers in HUD4 if (hud.withinGreenTowerBounds(e.x, e.y)5 && hud.getGold() >= Tower.CAESAR_TOWER_COST) {6 towerConstructor.startBuilding(new Tower(this, g,7 CipherType.CAESAR, e.x, e.y));8 return;9 } // if

10

11 if (hud.withinBlueTowerBounds(e.x, e.y)12 && hud.getGold() >= Tower.PLAYFAIR_TOWER_COST) {13 towerConstructor.startBuilding(new Tower(this, g,14 CipherType.PLAYFAIR, e.x, e.y));15 return;16 } // if17

18 if (hud.withinRedTowerBounds(e.x, e.y)19 && hud.getGold() >= Tower.VIGENERE_TOWER_COST) {20 towerConstructor.startBuilding(new Tower(this, g,21 CipherType.VIGENERE, e.x, e.y));22 return;23 } // if24

25 // check pause26 if (hud.withinPauseButtonBounds(e.x, e.y)) {27 pause();28 return;29 } // if30

31 // now check the enemies - so the player can attack32 for (int j = 0; j < enemies.size(); j++) {33 Enemy enemy = enemies.get(j);34 if (enemy.checkTap(e)) {35 // create a puzzle that, when completed, damages

this enemy36 addSubScreen(new PracticalQuestion(this, g, enemy))

;37 return;38 } // if39 } // for40 } // if41 } // for42 } // handleUserInput

59

Listing 4.11: The update method, part one - dealing with sub-screensand game over.

1 private void updatePlayingState(float delta,2 List<TouchEvent> events)3 {4 // handle touch events5 for (int i = 0; i < events.size(); i++)6 {7 if (isSubScreenQueueEmpty())8 handlePlayingTouchInput(events);9 else if (getFirstSubScreen().checkTap(events.get(i)))

10 removeFirstSubScreen();11 } // for12

13 // update any subscreen14 if (!isSubScreenQueueEmpty())15 getFirstSubScreen().update(delta);16

17 // if the subscreen is a tutorial screen, don’t18 // continue updating19 if (!isSubScreenQueueEmpty()20 && getFirstSubScreen() instanceof Tutorial)21 return;22

23 if (hud.getLives() == 0)24 state = State.GAME_OVER;25

26 ...

60

Listing 4.12: The update method, part two - NGA (normal game ad-vancement.

1 ...2 // add time3 Enemy enemyToSpawn = enemySpawner.update(delta);4 if (enemyToSpawn != null)5 enemies.add(enemyToSpawn);6 scoreKeeper.addTime(delta);7

8 // update towers9 for (int i = 0; i < towers.size(); i++)

10 {11 Tower tower = towers.get(i);12 Enemy enemyToTarget = tower.update(delta);13 if (enemyToTarget != null)14 projectiles.add(new Projectile(g, tower,15 enemyToTarget));16 } // for17

18 // move enemies19 for (int i = 0; i < enemies.size(); i++)20 {21 Enemy enemy = enemies.get(i);22 if (enemy.update(delta))23 damagePlayer(enemy);24 } // for25

26 // move projectiles27 for (int i = 0; i < projectiles.size(); i++)28 {29 Projectile projectile = projectiles.get(i);30 if (projectile.update(delta))31 damageEnemyByProjectile(projectile);32 } // for33 } // updatePlayingState

61

Chapter 5

Testing and Evaluation

This chapter describes the testing and evaluation of the project. Testingis about making sure the components of the website and the game workcorrectly and as expected. Evaluation is about measuring the effectivenessof the system at achieving its goal: aiding the teaching of cryptography toschoolchildren. This chapter is split in to two (uneven) sections: one fortesting and one for evaluation. The evaluation is more important and moredifficult than testing. Consequently, more time is devoted to that.

5.1 Testing

Testing a project like this is difficult. The main things to make sure arethat the website and the game are usable and that the game does not crash.Usability is subjective and requires many people using it and providing feed-back. Such time is not available, instead usability and stability must beassured in as little time as possible.

To achieve the best possible results in such a short time, both the gameand website went through a form of rapid development - where they wereboth used by external people throughout development to make sure thatthey were usable.

5.1.1 Testing CryptoLearn and CrypTD

When it comes to testing the website, two things must be assured: (1) thewebsite’s links and buttons must work and (2) the website must make sense,it must be usable. The first is easy to ensure, someone (not necessarilyexternal to development) can do that by clicking them all and checking that

62

Keyword What the test showed

Playfair Normal working.Jamjar ‘j’s are converted to ‘i’s.Poppakattepettle Duplicate letters in the keyword are dealt with.(Nothing) A square is still constructed when no letters are given.A, Jam-Jar! Special characters are removed.

Table 5.1: Test table for the PlayfairSqaure class.

they work.The second is much harder and much more subjective, it even borders

on evaluation, rather than testing. In order to make sure the website wasusable, people external to development were asked to use the website, thiswas mentioned above. These people were friends of the author - peoplewho close by whenever they were needed. The only necessity was that theywere external to development. The feedback from these people was used tomodify and improve the website so that it made sense to other people, i.e.,the target audience (who will also be external to development). By the timethe project got to evaluation and proxy testers were brought in (more onthis later) the website was very usable - the proxies even said so.

When it comes to testing the game, many things must be assured. Itbasically boils down to making sure that the game acts in an appropriatemanner to input from the user. The buttons and screens must play outcorrectly, the towers must be built correctly, the enemies must be createdand killed as appropriate, e.t.c. This can be done internally by the developer.Once this is done the game is evaluate by external people to see if it meetsits goals, this is discussed below.

5.1.2 Testing the Cipher Implementations

The whole point of the project is to teach cryptography - ciphers - toschoolchildren. For this reason there are examples of the ciphers in usethroughout both the website and the game. These are more often than notdynamically generated, this requires an implementation of the ciphers inquestion. These implementations really need to be correct. Because of thisneed to know that the ciphers are implemented correctly, their implementa-tions were unit tested. The implementations in the game were tested withjUnit, the implementations in the website were put through the same testscases, but without the help of the jUnit framework.

63

Cipher Word Key What the Test Showed

Caesar

hello 3 Normal workinghello 5 Changing the key has an effectxrayzebra 3 Letters wrap correctlyHeLLo 3 Case is preservedHello, World! 3 Special characters are preserved

Playfair

west playfair Normal workingwest cipher Changing the key has an effectcat playfair Odd words have an ‘x’ addedjamjar playfair ‘j’s are converted to ‘i’sPoppakatte playfair Duplicated pairs are dealt withHeLLo playfair Case is removed (made consistent)Hello, World! playfair Special characters are removed

Vigenere

hello lemon Normal workinghello cipher Changing the key has an effecthellohellohello lemon Key is repeated correctlyHeLLo lemon Case is removedHello, World! lemon Special characters are removed

Table 5.2: Test table for the Ciphers class.

The PlayfairSquare class was tested separately from the rest ofthe Playfair Cipher implementation to ensure its correct working. ThePlayfairSquare class (as stated in Section 4.2) is the implementationof the key of the Playfair Cipher. The correct working of the implementa-tion of the Playfair Cipher relies on this class working correctly. This wasdone so that any bugs in the implementation of the Playfair Cipher could betracked down more easily. If the PlayfairSquare class has been testedand known to be working and a bug is found in the implementation of thePlayfair Cipher, the bug cannot be in how the key works. This means thesearch space for bugs is narrowed. Table 5.1 displays the test cases used onthe PlayfairSqaure class and the reasons why. Table 5.2 shows the testcases used on the cipher implementations.

64

5.2 Evaluation

The project goal was to build something to help teach schoolchildren aboutcryptography. This means a proper evaluation would involve teaching thesyllabus to four, comparable, classes of schoolchildren. The first group wouldbe a control group, with no access to the website or the game. The secondgroup would have have access to just the website, the third would justhave access to the game and the final group would have access to both.After teaching had been completed the teachers and schoolchildren couldbe interviewed and the children tested. The results of the interviews andexams could be used to judge the usefulness and effectiveness of the websiteand game.

Given the time constraints and the lack of access to teachers, schoolchil-dren and the funds to do this, this true evaluation is not possible. Insteadthis has to be approximated using conversations and demonstrations withproxies and teachers.

5.2.1 What Proxies Said

Due to the lack of access to schoolchildren for evaluation, proxies were usedin their place. A proxy is a person who is not a member of the targetaudience, but who can either pretend to be or make a good replacement forthe target audience in some way.

For this project, the proxies used were gathered by asking friends andassociates of the author to help. These include the people that helped withtesting the website and the game for usability issues. These ranged fromcollege students (around 17 to 19 years old) to university students (around20 to 24 years old) to adults. Some proxies helped simply by commentson social networks such as Facebook, there were around 30 of these. Theircomments were in general rather vague and not very reliable, but were quitepositive and encouraging.

Others helped in a more in-depth manner. These proxies used the soft-ware, helped to test it and participated in short informal interviews called‘conversations with a purpose’. There were five of these in total.

The people who helped evaluate this project have been anonymised, butTable 5.3 shows some relevant data about these people. It is important tonote that these proxies were chosen for more in-depth help for two reasons:(a) they wanted to and (b) they could offer useful information for variousreasons, as stated in Table 5.3.

The process these proxies went through is described here. They were

65

Age Vocation Maths Knowledge Useful Because

Proxy 1 18 College Student(Law, Philoso-phy)

Top Level KS3 Close to targetaudience (ageand knowledge)

Proxy 2 19 UniversityStudent (Lan-guages)

Average KS3 Close to tar-get audience(knowledge)

Proxy 3 21 University Stu-dent (ComputerScience)

A Level Provide techno-logical feedback

Proxy 4 24 University Stu-dent (ComputerScience)

A Level Provide techno-logical feedback(different toProxy 3)

Proxy 5 20 Lab Assistant Average KS3 Interested in ci-phers, close totarget audience(knowledge)

Table 5.3: Relevant data for the proxies who helped with the in-depthevaluation, including the reasons why they would be helpful.

66

asked to use the software, with the author present. They were asked todescribes their thoughts and feelings as they progressed through the websiteand then the game. They were also asked to describe how they thought thesoftware would react to actions they took, before they actually took them.This was not done for every action, as this would likely annoy the proxy andthe emphasis was on keeping them feeling relaxed and safe - this allows formore honest and constructive feedback. After they had used the softwareand they felt as though they understood it, there was a ‘conversation with apurpose’. This is like an interview, but much more informal and much morenatural.

The general feedback was encouragingly positive. The website was saidto be very good looking and very useful. The game was said to be a goodmotivator for revision by the younger of the proxies, with the older onesfinding it less useful and much more difficult.

CryptoLearn Feedback

Specifically, the organisation and the clarity of the website was commentedon as this in particular aided the learning of the ciphers. The website wassaid to be easy to follow, with an obvious (if implicit) flow, which the proxiessaid they found encouraging and motivated them to move on. The testingareas was said to indeed help encourage users, with one proxy saying thatthey did so badly when testing themselves that they went back and re-readall the information before coming back. Overall, they said the website lookedgood and was easy to use and they could indeed envisage it being very usefulto schoolchildren learning this in school - that its interactivity made it farmore fun, far more useful and far better than a text book.

Some improvements were suggested, the most significant of which wasa more explicit and well defined flow through the website. This came fromthe discussions with the Computer Science students, it was felt that someform of tracking could help define a ‘journey’ that would have made theflow more concrete, and may help increase engagement. One small thingthat was mentioned was the use of ‘touch-points’ - parts of the website thatwere fun and quirky, such as the obviously wrong answers on the test pages- these were enjoyed but would have to be drastically improved to make noteof pop culture from today’s schoolchildren.

67

CrypTD Feedback

The game was also praised, but less so than the website. The proxies ingeneral found it challenging to say the least. It was said that it would helpencourage them to learn the ciphers more as knowing the ciphers helpedplay the game. It was also praised for its progressive disclosure - the cipherswere introduced slowly, one after another.

However there were several improvements that could be made. Firstof all would be to introduce achievements and score ratings - to encourageplayers to play again and again and to stop them from being demotivated ifthey do not do well at first. Also, The pause screen should become a pausemenu, with access to the tutorials, and quit and restart buttons. On thetopic of tutorials the screens should be numbered and the user should beable to stop them from appearing at all. Lastly, the questions seemed tofluster and panic players, for this reason, opening up the question shouldslow down the normal game advancement - giving the player more time andmore incentive to practice the learning objectives. If these improvementswere made, the proxies said the game would be more useful and engaging.

The conclusion that can be drawn from this is that the website is great, itachieves its goals and does so in an attractive and easy to use manner. Butit could still be even better. The game however could be made very usefulwith some additions and modifications, but is not fully achieving its goalsin its current state.

The main thing to do is include more gamification. The proxies foundthat the project would be better with the gamification of the website as wellas the fully fledged game. The game could even benefit from gamification,i.e. achievements and better high scores. Social sharing of high scores couldmake the the high score system that aimed to encourage players to try again,harder, even more powerful. The game also has some issues in the real world(like being too hard) which were not addressed due to time constraints.

5.2.2 What Teachers Said

Teachers could provide feedback about how the software could be used toimprove their teaching and its possible use in a classroom. They also haveexcellent knowledge of the target audience - school children - as they workwith them very closely on a day to day basis. For these reasons some thefriends of the author in the teaching profession were asked to provide feed-back for the project. Two teachers agreed, both maths teachers. One was a

68

newly qualified teacher (NQT) and the other was a more experienced headof department.

Teachers were asked to go through much the same process as proxieswhen evaluating the project, although they were not asked to go throughthe bug finding phase. Once the teachers had used the software, understoodits function and how schoolchildren were expected to use it and what forthere were more informal conversations with a purpose. The conversationcentred around how the software could be used to improve learning and howthe software could be made better.

The teachers were aware of the results of evaluation from the proxiesand this informed the conversation. It was said to be useful and easilyapplicable, much like SAM Learning or BBC Bitesize, where teachers couldaward prizes for children with the highest scores. The teachers agreed thatgreater tracking on the website would make it easier to incorporate intoclassrooms, because knowing where the children were upto and how theywere doing could help them give attention to the ones that were strugglingand give rewards to the ones doing well / trying hard.

The syllabus was also discussed with the teachers. They felt that iswas appropriate given the current social and political situation and thatits length was reasonable and it was challenging enough. They also feltSteganography (see Subsection 2.2.9) could reasonably be introduced.

What this means is that the website and the game (to some degree)achieve their goals and could indeed help to teach the new syllabus. Thereare improvements to be made, like allowing teachers to view the progress ofthe schoolchildren, but its an excellent and useful start.

69

Chapter 6

Summary and Outlook

This short chapter summarizes how well the project achieves the goals setout in Chapters 1 and 3. The chapter starts with a section about what hasbeen achieved, with a reiteration of the project goals. Then there is a sectionabout possible future work. Finally this chapter and the report close withsome final remarks.

6.1 Achievements

The goals of this project were twofold: (1) create a syllabus for cryptographythat could be taught to KS3 schoolchildren and (2) create some software tofacilitate the teaching of this syllabus. The syllabus was created and wassaid to be perfectly acceptable by teachers. The software created to facilitatethe teaching of this syllabus involved a website and game.

The purpose of the website was to help teach the syllabus and helpschoolchildren revise the syllabus. The syllabus was presented in text withthe aid of interactive diagrams and examples. The users could test them-selves with theoretical and practical questions. The website was made tobe as open and accessible as possible, it is fully responsive and completelyscreen reader friendly. Figures 6.1a to 6.2c show what the functions of thewebsite look like on a desktop and a mobile device.

The purpose of the game was to reinforce the learning provided in classand on the website. This was done by making a challenging game that hadhigh scores to promote self-betterment. Figures 6.3a to 6.3d show what thegame look like when its being played.

70

(a) Caesar learn page - method tab. (b) Playfair learn page - key tab.

(c) Vigenere test page - practicalquestion tab.

(d) Vigenere test page - theoreticalquestion tab.

Figure 6.1: Example pages from the website, viewed on a desktop device.

(a) Caesar learn page -key tab.

(b) Playfair test page -practical question tab.

(c) Caesar test page -theoretical question tab.

Figure 6.2: Example pages from the website, viewed on a mobile device.

71

(a) Example of combat. (b) Screenshot of the introduction.

(c) Example a question. (d) The choose level screen.

Figure 6.3: Example screenshots from the game.

6.2 Further Work

Although the software has done rather well in meeting its goals, with usersand teachers alike praising its usefulness, there were a few things that wouldalso have been done, time permitting. The first and foremost would be tomake the game available on more platforms and integrate sharing of highscores into it. This would have made it more applicable and more engaging.

The second major thing that would be done is to introduce accounts andallow tracking of progress and rewards. This could then be applied moregenerally to the wider curriculum. The use of gamification and the introduc-tion of ‘journeys’ or flow, as is used in Codeacademy and (to some extent)Udacity, to other online learning platforms could help improve engagementand consequently improve retention and performance.

6.3 Final Remarks

This project set out to create something that could help children learn.This has been achieved, and is, in some ways, better than what is currently

72

available. However, more could be done to improve engagement and fun inonline learning. It is hoped this project could be a stepping stone to greaterthings.

73

Bibliography

[1] The Government of the United Kingdom, (2013). National Curriculumin England: Computing Programmes of Study. Available: www.gov.uk/government/publications/national-curriculum-in-england-computing-programmes-of-study. Last ac-cessed 18/04/2014.

[2] Andy Park, (2013). Cryptoparties teach data privacy to the pub-lic. Available: www.sbs.com.au/news/article/2012/10/16/cryptoparties-teach-data-privacy-public. Last accessed18/04/2014.

[3] The Government of the United Kingdom, (2014). The NationalCurriculum. Available: www.gov.uk/government/collections/national-curriculum. Last accessed 01/04/2014.

[4] William Stallings. (2011). Classical Encryption Techniques. In: Cryp-tography and Network Security, 5th edition. Prentice Hall: Pearson.

[5] Count On, (2006). Caesar Cipher. Available: www.counton.org/explorer/codebreaking/caesar-cipher.php. Last accessed01/04/2014.

[6] Count On, (2006). The Vigenere Cipher. Available: www.counton.org/explorer/codebreaking/vigenere-cipher.php. Lastaccessed 01/04/2014.

[7] Count On, (2006). The One Time Pad. Available: www.counton.org/explorer/codebreaking/one-time-pad.php. Last ac-cessed 01/04/2014.

[8] Friedrich Kasiski, (1863). Secret Writing and the Art of Deciphering.Berlin: Mittler and Son.

74

[9] Dan Rodriguez-Clark, (2013). Kasiski Analysis: Breakingthe Code. Available: crypto.interactive-maths.com/kasiski-analysis-breaking-the-code.html. Last accessed01/04/2014.

[10] Ben Frain, (2012). Responsive Web Design with HTML5 and CSS3.Birmingham: Packt.

[11] Mark Otto, et. al., (2014). Bootstrap. Available: getbootstrap.com.Last accessed 01/04/2014.

[12] Zurb, (2014). Foundation. Available: foundation.zurb.com/index.html. Last accessed 01/04/2014.

[13] Digital Surgeons, (2014). Gumby Framework. Available:gumbyframework.com. Last accessed 01/04/2014.

[14] Google, (2014). Develop. Available: developer.android.com/develop/index.html. Last accessed 01/04/2014.

[15] Nicolas Gramlich, (2013). AndEngine - Android Game Engine. Avail-able: www.andengine.org. Last accessed 01/04/2014.

[16] Citrus Engine, (2012). Citrus. Available: citrusengine.com. Lastaccessed 01/04/2014.

[17] Mario Zechner, Robert Green, (1863). Beginning Android Games, 2ndedition. Stuttgart: Apress.

[18] SAM Learning, (2014). SAM Learning. Available: www.samlearning.com. Last accessed 02/04/2014.

[19] BBC Bitesize, (2014). BBC Bitesize. Available: www.bbc.co.uk/bitesize. Last accessed 19/04/2014.

[20] Codecademy, (2014). Codeacademy. Available: www.codeacademy.com. Last accessed 02/04/2014.

[21] Udacity Inc., (2014). SAM Learning. Available: www.udacity.com.Last accessed 02/04/2014.

[22] Oxford Dictionaries, (2014). Gamification. Available:www.oxforddictionaries.com/definition/english/gamification. Last accessed 15/04/2014.

75

[23] Norman, D. A., (2004). Emotional design: why we love (or hate) ev-eryday things. New York: Basic Books.

[24] Dmitry Fadeyev, (2009). 10 Useful Usability Findings and Guide-lines. Available: uxdesign.smashingmagazine.com/2009/09/24/10-useful-usability-findings-and-guidelines. Lastaccessed 10/04/2014.

[25] Stone Reuning, (2012). Keeping your Content Above the Foldand Easy to Find. Available: www.seo-e.com/forum-watch/keeping-your-content-above-the-fold-and-easy-to-find.htm. Last accessed 10/04/2014.

76

Appendices

77

Appendix A

Some Teaching Material

This appendix presents some very basic teaching material. This is effectivelyjust a very specific and in depth syllabus. This is the syllabus presented inSection 3.1 for reference.

Schoolchildren are expected to:

• know what cryptography is and why it is used

• know what a cipher is

• know what a key is

• know what a brute force attack is and when such an attack is appro-priate

• know what cryptanalysis and when its use is appropriate

• understand the following ciphers, including their key’s, how to encryptand decrypt messages with them, how strong they are and why:

– the Caesar Cipher

– the Playfair Cipher

– the Vigenere Cipher

– the One Time Pad.

A.1 The Basics

In more detail, the schoolchildren are expected to know that cryptographyis the study of ciphers and that ciphers are a mechanism by which messages

78

or, in general, data is kept secret. They need to know that the key for acipher is the lock that keeps the data secret, only people with the key shouldbe able to read the message. They also need to know that the data is onlya secret and as safe as they key is.

The children are also expected to know about cryptanalysis - the otherside of cryptology. Cryptanalysis is the study of breaking ciphers, the studyof trying to read messages without knowing the key. A strong cipher willbe difficult to break. The children need to know that a brute force attack istrying all the keys to see which one ‘fits’, they also need to know that this isstupid and slow. They are also expected to know that cryptanalysis attacksuse the statistical properties of the message, the key and the cipher to tryand work out the key and the message. They should also be taught thatcryptanalysis is used when a brute force attack is impractical.

A.2 The Ciphers

The working of the ciphers is explained in Section 2.2. That is reproducedhere in brief. The children are expected to know the ciphers to this extent.

A.2.1 The Caesar Cipher

The key is chosen to be a number between 1 and 25. Each letter is encryptedby a right circular shift of that letter by key places. This can also be doneas addition of the key and the letter modulo 26. Decryption is the opposite

There are only 25 keys, so the cipher is weak to a brute force attack.The number of keys can be increased without changing the cipher too much.Instead of replacing each letter by the letter so many places right in thealphabet, replace it with an arbitrarily chosen letter.

This new system has 26! keys, but is easy to break using a cryptanalysistechnique called single letter frequency analysis. Because each letter is re-placed by the same letter, the frequencies of the letters in the plaintext arepreserved in the ciphertext. By looking at these frequencies, the letter thatreplaces a given letter can be worked out or guess quite easily.

A.2.2 The Playfair Cipher

A keyword is chosen and that keyword is used to construct a keysquare.This keysquare is a 5 × 5 grid of every letter in the alphabet, minus ‘j’.The keysquare is filled top to bottom, left to right using the letters of the

79

1, 1 1, 2 1, 3 1, 4 1, 52, 1 2, 2 2, 3 2, 4 2, 53, 1 3, 2 3, 3 3, 4 3, 54, 1 4, 2 4, 3 4, 4 4, 55, 1 5, 2 5, 3 5, 4 5, 5

Table A.1: Naming the cells of the Playfair keysquare.

keyword (ignoring duplicates) and then using the rest of the letters of thealphabet, in order.

The message is encrypted in pairs, any duplicate pairs are split up andan ’x’ replaces the second letter of the pair. The for each plaintext pair thereis a ciphertext pair. The ciphertext pair is chosen by using the plaintextpair, the keysquare and three rules. For the sake of simplicity, let us namethe plaintext pair (a, b) and the ciphertext pair (A, B). Also, let the cellsof the keysquare be named as in Table A.1.

Now, the rules:

1. If a and b occupy the same row (e.g. 1, 1 and 1, 4), A is the letter inthe cell to the right of a and B is the letter in the cell to the right ofb (or on the left if a or b is in the rightmost column).

2. If a and b occupy the same column (e.g. 3, 4 and 4, 4), A is the letterin the cell underneath of a and B is the letter in the cell underneathb (or on top if a or b is in the bottom row).

3. If a and b are in different rows and columns (e.g. 1, 1 and 4, 4), A isthe letter in the cell in the same row as a and in the same column asb (e.g. 1, 4) and B is the letter in the same row as b but in the samecolumn as a (e.g. 4, 1).

The syllabus does not expect schoolchildren to be able to break thePlayfair Cipher. But the should know that it is broken using a techniquecalled double letter (or digraph) frequency analysis. They should also knowthat this is the same as single letter frequency analysis, except with pairsof letters. The more astute children will recognise that this is harder andwill be able to explain why (because there are so many more pairs of letters,so much more ciphertext is required to get the statistics the reach expectedlevels). But, again, this is not expected.

80

A.2.3 The Vigenere Cipher

The key for the Vigenere Cipher is a word. Encryption is exactly the sameas the Caesar Cipher, except that the key is changed per letter. The key foreach letter is selected from the keyword. The word is converted to numbersand this series is the series of keys to use for encryption. This series isrepeated as necessary. For example if the keyword was ‘lemon’ the series ofkeys would be 12 5 13 15 14. This means the first letter would be encryptedwith the key 12, the second letter would be encrypted with the key 5, . . . ,the sixth letter would be encrypted with the key 12, and so on.

The children are expected to know that this cipher was thought unbreak-able for a long time. They are not expected to break this cipher, or evenhow to do it, only that it involves finding the length of the keyword andthat one way to do this is by the Kasiski examination. A good challenge forthe more advanced students may be to find out how to do this and explainit to the class.

A.2.4 The One Time Pad

The one time pad is the world’s only unbreakable cipher. It is exactlythe same as the Vigenere Cipher, but the key is exactly as long as themessage to encrypt and is completely random. This two things togethermake it unbreakable. With a completely random key the ciphertext bearsno statistical resemblance to the plaintext, so no amount cryptanalysis canbreak it. Also, if the key is as long as the message (and never used again)the weakness of the Vigenere Cipher (repeating key) is done away with soit can never be broken.

Extra credit involves discussing why it is not used today to protect mes-sage if it cannot be broken. Also, possible ways of trying to get as close tothis as possible. Children could also be taught that wi-fi is protected usinga form of this, where is key is not completely random, but is generated bya key that two parties share. Again, this is not strictly part of the syllabus,but could help the children understand why they are learning about it.

81