A Level Computer Science · Chapter 7 · Component 01: Computer systems
Data must often be made smaller, kept secret or checked for changes, and compression, encryption and hashing are the three tools that do these jobs.
This chapter teaches lossy and lossless compression, run-length encoding, dictionary coding and Huffman coding. It then teaches symmetric and asymmetric encryption, from the Caesar and Vernam ciphers to public keys, and how hashing is used to check data and store passwords safely.
In this chapter · jump to a section
Start here
Your route through this chapter
By the end of this chapter you will be able to:
- explain the difference between lossy and lossless compression, and calculate a compression ratio
- encode and decode data with run-length encoding, and explain when it fails
- compress text with a dictionary and with Huffman coding, and count the bits saved
- encrypt and decrypt with the Caesar and Vernam ciphers, and explain why the Vernam cipher can be perfectly secure
- explain symmetric and asymmetric encryption, and run a small example of public-key encryption
- describe hashing, calculate simple hash values and explain why passwords are stored as hashes
Time: three sessions, about 4 hours, plus the programming task.
You need first: binary and character codes from Number systems and binary arithmetic, and the MOD operator from Programming constructs.
The big picture
The big picture
Every day, huge amounts of data move between computers. Photos are uploaded, films are streamed, messages are sent and payments are made. Three problems come up again and again. Data takes space and time to store and send, so it should be as small as possible. Data may be read by people who should not see it, so it must be kept secret. And data may be changed, by accident or on purpose, so there must be a way to check it.
Compression makes data smaller. Lossless compression removes repetition, so the original can be rebuilt exactly. Lossy compression throws away detail that people will not notice, so it shrinks data much further but cannot be undone.
Encryption keeps data secret. It scrambles the data using a key, so that only someone with the right key can turn it back. Symmetric encryption uses the same key to lock and unlock. Asymmetric encryption uses a pair of keys, one public and one private, which solves the problem of sharing a key safely.
Hashing turns any amount of data into a short, fixed-size value. The same data always gives the same hash, but the hash cannot be turned back into the data. That makes hashing ideal for checking that a file has not changed, for storing passwords, and for finding records quickly in a hash table. Each use depends on a different property. Hashes are short, they cannot be reversed, and they can point straight to a place in memory.
The three tools are often used together. A message sent over the internet may be compressed to save time, encrypted to keep it private, and hashed so the receiver can check it arrived unchanged.
Take a photo sent from one phone to another. The photo is compressed so that it sends quickly over a mobile network. It is encrypted so that nobody between the two phones can see it. And the app checks a hash of the data on arrival, so that a photo damaged on the way is noticed and sent again. The user sees none of this, but each step depends on the ideas in this chapter.
Section 1
Lossy and lossless compression
Why compress?
Compressed files take less storage space, so more of them fit on a disk or a phone. They also take less time to send across a network, and less of a monthly data allowance. A web page whose images are compressed loads faster, and a video service can stream to more people at once with the same network capacity.
The cost is the work of compressing and decompressing. The sender's computer must run the encoder and the receiver's computer the decoder. For most files this takes far less time than sending the uncompressed data would.
Compression only works because most data contains patterns. Text repeats common words and letters, images have large areas of similar colour, and sound changes smoothly from one moment to the next. A compression method finds a shorter way to describe those patterns. Data that is already random, or already compressed, has no patterns left to exploit and barely shrinks at all.
Lossless compression
Lossless compression removes repetition and redundancy from the data, without losing anything. When the file is decompressed, every bit is exactly as it was. Lossless compression must be used for text, program files, spreadsheets and anything else where a single changed bit would matter. A program with one wrong bit may crash, and a bank balance with one wrong digit is useless.
Lossy compression
Lossy compression permanently removes data that people are unlikely to notice. An image may store colours less precisely in areas of fine detail, and a music file may drop sounds that are masked by louder sounds at the same moment. Lossy files can be many times smaller than the original, but the data that was removed can never be recovered.
Each kind of media has its own lossy tricks. Image compression stores colour less precisely than brightness, because human eyes are less sensitive to small colour changes. It also smooths away very fine detail, especially in busy areas of the picture. Audio compression removes very high and very low sounds, and quiet sounds that are hidden by louder ones. Video compression stores whole frames only now and then; in between, it stores only the parts of the picture that changed.
Most lossy formats let the user choose a quality setting. A high quality keeps more detail and gives a bigger file; a low quality gives a smaller file with visible flaws, such as blocky patches in an image. The right setting depends on how the file will be used: a photo for a small thumbnail can be compressed far more than one to be printed.
Lossy and lossless methods are often used together. A lossy image format first throws away detail that the eye will not miss, which leaves data that is smoother and more repetitive. It then compresses that data losslessly, squeezing out the repetition. The lossy step decides the quality; the lossless step makes the result as small as possible.
Common mistake: thinking lossy compression can be undone. Lossy compression throws data away for good. Decompressing a lossy file gives something close to the original, never the original itself, and compressing it again with a lossy method loses even more.
Compression ratio
The compression ratio compares the size of the original with the size of the compressed file. A ratio of 4 means the compressed file is a quarter of the original size.
Worked example 1: a compressed photo
A photo is 1,000 by 800 pixels with 24 bits per pixel. It is compressed to 600,000 bytes. Find the original size and the compression ratio.
| Working | Reason |
|---|---|
| Size = 1000 × 800 × 24 ÷ 8 bytes | Pixels times bits per pixel, then bits to bytes |
| Original size = 2,400,000 bytes | That is 2.4 MB of image data |
| Ratio = 2,400,000 ÷ 600,000 = 4 | Original divided by compressed |
| The compressed file is a quarter of the size | It sends in a quarter of the time |
Worked example 2: the time saved
The same photo is sent over a connection of 8,000,000 bits per second. How long does each version take to send?
| Working | Reason |
|---|---|
| Original: 2,400,000 × 8 ÷ 8,000,000 = 2.4 s | Convert bytes to bits, then divide by the speed |
| Compressed: 600,000 × 8 ÷ 8,000,000 = 0.6 s | The same calculation for the smaller file |
| Compression saves 1.8 seconds per photo | That is three quarters of the time |
| Over a hundred photos, it saves three minutes | Small savings add up quickly |
Check yourself. A school wants to compress its exam result spreadsheets before emailing them. Should it use lossy or lossless compression? Why?
Show the answer
It must use lossless compression. Every mark must be exactly right when the file is opened, and lossy compression could change the data in ways that cannot be undone.
Section 2
Run-length encoding and dictionary coding
Run-length encoding
Run-length encoding, or RLE, replaces a run of the same value with one copy of the value and a count. The text AAAABBBCCD has a run of four As, three Bs, two Cs and one D, so it can be stored as 4A3B2C1D. A decoder reads each count and writes out that many copies of the symbol. Nothing is lost, so RLE is a lossless method: decoding always gives back exactly the data that was encoded, however long the runs were.
RLE works well for data with long runs, such as simple images with large areas of one colour, or a fax of a mostly white page. Each row of a black and white image can be stored as alternating runs of white and black pixels.
If a count is stored in one byte, the longest run it can describe is 255. A longer run is simply split into two or more runs of the same symbol. Some versions of RLE store single symbols without a count, and use a special marker byte to show where a run begins. This avoids doubling the size of data that has few runs.
Worked example 3: encoding text
Encode AAAABBBCCD with RLE, using one byte for each count and one for each symbol. Is the result smaller?
| Working | Reason |
|---|---|
| Runs: 4 As, 3 Bs, 2 Cs, 1 D | Group neighbouring symbols that are the same |
| Encoded: 4A3B2C1D | Each run becomes a count and a symbol |
| Size: 4 runs × 2 bytes = 8 bytes | Every run needs a count byte and a symbol byte |
| 8 bytes against 10 bytes, so it is smaller | The runs are long enough to save space |
Worked example 4: an image row
A row of a black and white image is WWWWWWBBBWWW, where W is white and B is black. Encode it.
| Working | Reason |
|---|---|
| Runs: 6 white, 3 black, 3 white | Group neighbouring pixels of the same colour |
| Encoded: 6W3B3W | A count and a colour for each run |
| Size: 3 runs × 2 bytes = 6 bytes | Half of the original 12 bytes |
| Decoding writes 6 Ws, 3 Bs, 3 Ws | The original row is rebuilt exactly |
When RLE makes things worse
RLE only helps when runs are long. Text such as ABCD has no repeats at all, so every run has length 1, and the encoding 1A1B1C1D is twice the size of the original. Ordinary English text has very few runs, so RLE is a poor choice for it.
The same is true of photographs. Neighbouring pixels in a photo are similar but rarely identical, so runs are short. RLE suits computer-drawn images instead: icons, diagrams, cartoons and scanned documents, where large areas really are exactly one colour. It is also used inside other methods, after an earlier step has created long runs on purpose.
Figure 7.1 builds data from four runs of the same length. Move the length of each run and compare the original and encoded sizes. Then switch on the wrong model.
Run-length encoding
- Original
- 12 bytes
- Runs
- 4
- Encoded
- 8 bytes
Common mistake: forgetting that each run's count must be stored too. A decoder cannot rebuild AAAAB from just AB: it must know how many of each symbol to write. So every run costs a count as well as a symbol, and runs of length 1 double the size of the data.
Worked example 5: data with no runs
Encode ABCD with RLE, and compare the sizes.
| Working | Reason |
|---|---|
| Runs: 1 A, 1 B, 1 C, 1 D | No symbol repeats its neighbour |
| Encoded: 1A1B1C1D | Each run still needs a count |
| Size: 4 runs × 2 bytes = 8 bytes | Twice the original 4 bytes |
| RLE has made the data bigger | Runs of length 1 cost two bytes each |
Dictionary coding
Dictionary coding finds repeated words or patterns and stores each one only once, in a dictionary. The text is then stored as a list of positions in the dictionary. A long word that appears many times is replaced each time by a short number.
Worked example 6: a dictionary
Compress the text "the cat sat on the mat and the cat ran" with a dictionary of whole words.
| Working | Reason |
|---|---|
| The text has 10 words but only 7 different ones | the appears three times and cat twice |
| Dictionary: the, cat, sat, on, mat, and, ran | Each new word gets the next position |
| Text: 0 1 2 3 0 4 5 0 1 6 | Each word is replaced by its position |
| Repeated words are now stored once each | The saving grows as the text gets longer |
Many common compressed file formats use dictionary methods. They build the dictionary as they go, adding each new pattern the first time it appears. So the dictionary need not be stored at all: the decoder rebuilds it in exactly the same way.
Suppose the encoder meets the word "the" for the first time. It writes "the" in full and gives it a number in the dictionary. The next time "the" appears, the encoder writes only the number. The decoder reads "the" in full the first time, gives it the same number, and so knows what that number means when it appears later.
Check yourself. How many bytes does RLE need for WWWWWWWWBBBBWWWWBBBBBBBB, at two bytes per run?
Show the answer
The runs are 8W, 4B, 4W and 8B, so there are 4 runs and the encoding needs 8 bytes, against 24 for the original.
Section 3
Huffman coding
Short codes for common symbols
ASCII gives every character 8 bits, however often it appears. But in most text some characters are far more common than others. Huffman coding gives the commonest characters the shortest codes and the rarest the longest, so the total number of bits is as small as possible.
The codes have a special property: no code is the start of another. So a stream of bits can be decoded without any separators, by reading bits until they match a code, writing that character, and starting again.
Building a Huffman tree
Count how often each character appears. Then repeat: take the two items with the smallest counts, and join them under a new node whose count is their sum. Continue until a single tree remains. Label each left branch 0 and each right branch 1. A character's code is the path from the root down to it.
For ABRACADABRA the counts are A 5, B 2, R 2, C 1 and D 1. The two smallest, C and D, are joined first into a node of 2. The next two smallest are B and R, each 2, which join into a node of 4. Then the C and D node joins the B and R node, making 6. Finally that node of 6 joins A, giving the root of 11. A hangs one step from the root, and every other letter three steps down.
Worked example 7: coding BANANA
Build Huffman codes for BANANA and find the total number of bits.
| Working | Reason |
|---|---|
| Counts: A 3, N 2, B 1 | Count how often each letter appears |
| Join B (1) and N (2) into a node of 3 | The two smallest counts are joined |
| Join A (3) with that node to make the root, 6 | Only two items remain |
| Codes: A = 0, B = 10, N = 11 | Follow the branches from the root |
| Bits: 3 × 1 + 1 × 2 + 2 × 2 = 9 | Each letter's count times its code length |
So BANANA is encoded as 100110110, only 9 bits. ASCII would need 6 × 8 = 48 bits, and even a fixed two-bit code for three letters would need 12.
Worked example 8: ABRACADABRA
Using the tree above, find the number of bits for ABRACADABRA and compare it with ASCII and a fixed-length code.
| Working | Reason |
|---|---|
| A: 5 × 1 = 5 bits | Five As with a one-bit code |
| B, R: 2 × 3 + 2 × 3 = 12 bits; C, D: 1 × 3 + 1 × 3 = 6 bits | The rest have three-bit codes |
| Total: 5 + 12 + 6 = 23 bits | Add the bits for every letter |
| ASCII: 11 × 8 = 88 bits; fixed 3-bit code: 11 × 3 = 33 bits | Huffman coding beats both of them |
Worked example 9: decoding
Decode 100110110 using the codes A = 0, B = 10 and N = 11.
| Working | Reason |
|---|---|
| Read 1, then 10: that is B | No code is just 1, so read another bit |
| Read 0: A; then 11: N | Each match is written out at once |
| Read 0: A; then 11: N; then 0: A | Carry on until the bits run out |
| The text is BANANA | No separators were needed |
Figure 7.2 changes how many As the text contains. Watch how the codes and the total change as A becomes more common. Then switch on the wrong model.
Huffman coding
- Huffman
- 16 bits
- ASCII
- 80 bits
- Saving against ASCII
- 80%
Common mistake: thinking every character needs a code of the same length. A fixed-length code wastes bits on common characters. Huffman coding gives frequent characters short codes and rare ones long codes, so the total is smaller. The decoder still works, because no code is the start of another.
Derivation: the bits saved by Huffman coding
Suppose a text has n characters, made from k different symbols, and symbol i appears f(i) times with a code of l(i) bits. The total length of the Huffman-coded text is
A fixed-length code must give every symbol the same number of bits, enough to tell all k symbols apart, so
For ABRACADABRA, n = 11 and k = 5, so the fixed code needs 11 × 3 = 33 bits, while Huffman needs 23. The more uneven the counts, the bigger the saving.
The tree, or the table of codes, must be stored with the compressed data, so that the decoder knows the codes. For a short text the table can cost more than it saves, so Huffman coding pays off on longer files.
Huffman coding is optimal among codes that give each symbol its own whole number of bits: no such code can give a shorter total for the same counts. Several different trees can give the same total, because ties can be broken in different ways, but every one of them uses the same number of bits overall.
Huffman coding is often combined with other methods. A file might first be compressed with a dictionary method, which replaces repeated patterns with numbers. Those numbers are then Huffman coded, because some appear far more often than others. Many everyday compressed file formats use exactly this two-step approach.
Check yourself. With codes A = 0, B = 10, C = 110 and D = 111, how many bits does AAAABBCD need?
Show the answer
The As need 4 × 1 = 4 bits and the Bs 2 × 2 = 4 bits. C and D need 3 bits each, so the total is 4 + 4 + 3 + 3 = 14 bits.
Section 4
Symmetric encryption
Keys and ciphers
Encryption turns readable plaintext into unreadable ciphertext, using an algorithm called a cipher and a secret value called a key. Decryption turns the ciphertext back into plaintext. In symmetric encryption the same key is used for both, so the sender and the receiver must both have it and keep it secret.
The Caesar cipher
The Caesar cipher shifts every letter a fixed number of places along the alphabet, wrapping round from Z to A. With a shift of 3, A becomes D, B becomes E and Z becomes C. The key is the size of the shift. To decrypt, the receiver shifts back by the same amount.
Worked example 10: a Caesar shift
Encrypt HELLO with a shift of 3, then decrypt the result.
| Working | Reason |
|---|---|
| H → K, E → H, L → O, L → O, O → R | Each letter moves three places on |
| Ciphertext: KHOOR | The shifted letters in order |
| Decrypt: shift back by 3, or on by 23 | Moving on 23 places equals back 3 |
| KHOOR → HELLO | The same key unlocks the message |
The Caesar cipher is easy to break. There are only 25 useful shifts, so an attacker can try them all in seconds. Even without trying keys, the most common letter in the ciphertext probably stands for E, the most common letter in English. This is called frequency analysis.
Frequency analysis works against any cipher that always replaces the same letter with the same symbol, even if the replacements are scrambled rather than shifted. In a long enough message, the commonest symbols stand for E, T and A, and common short words such as THE soon appear. Breaking such ciphers was the daily work of codebreakers for centuries.
The Vernam cipher
The Vernam cipher, or one-time pad, combines each bit of the plaintext with a bit of the key using exclusive OR. A key bit of 1 flips the plaintext bit, and a key bit of 0 leaves it alone. Applying the same key again flips the same bits back, so XOR with the key both encrypts and decrypts.
Worked example 11: XOR encryption
Encrypt the byte 01001000 with the key 10110110, then decrypt the result.
| Working | Reason |
|---|---|
| 0 XOR 1 = 1, 1 XOR 0 = 1, 0 XOR 1 = 1 … | XOR gives 1 when the bits differ |
| Ciphertext: 11111110 | All eight pairs combined |
| 11111110 XOR 10110110 = 01001000 | XOR with the same key again |
| The plaintext is recovered exactly | XOR with the key undoes itself |
The Vernam cipher is perfectly secure, in the sense that the ciphertext gives no information at all about the plaintext, provided three rules are kept. The key must be truly random, at least as long as the message, and used only once. Every possible plaintext of the right length is then equally likely, so even an attacker with unlimited computing power cannot break it.
Common mistake: thinking a Vernam key can be short or used again. The perfect security only holds if the key is random, as long as the message and never reused. A short key that repeats, or a key used for two messages, leaves patterns that an attacker can exploit.
Keys this long are hard to share safely, which is why the one-time pad is used only for the most secret messages. Most symmetric encryption uses modern ciphers with keys of 128 or 256 bits, which cannot be broken by trying every key.
The weakness of every symmetric cipher is the key itself. Both people need the same key, and they must agree it without anyone else learning it. Meeting in person works for two people, but not for a website with millions of customers who have never met it. The next section shows how asymmetric encryption solves this.
Modern symmetric ciphers work on blocks of data, often 128 bits at a time. Each block passes through many rounds of substituting, shuffling and mixing its bits with parts of the key. In the end, every bit of the ciphertext depends on every bit of the plaintext and the key. They are very fast, so they are used for almost all bulk encryption, from files on a laptop to video calls.
Derivation: how long a brute-force attack takes
A key of n bits can take 2ⁿ values. An attacker who tries keys at random finds the right one, on average, half way through.
At r keys per second, the average time is
Each extra bit doubles the time. A 40-bit key at a billion keys per second falls in about 550 seconds, but a 128-bit key would take far longer than the age of the universe.
Check yourself. At a billion keys per second, about how long does a brute-force attack on a 56-bit key take on average?
Show the answer
The average is 2⁵⁵ ÷ 10⁹, about 36,000,000 seconds. That is roughly 417 days, so a 56-bit key is no longer considered safe against a determined attacker.
Section 5
Asymmetric encryption
The key exchange problem
Symmetric encryption has a weakness: the sender and receiver must share the key before they can talk securely. Sending the key over the internet would let anyone listening copy it. Asymmetric encryption solves this with a pair of keys that are mathematically linked.
Public and private keys
Each person has a public key, which they share with everyone, and a private key, which they keep secret. Data encrypted with someone's public key can only be decrypted with their private key. So to send Bob a secret message, Alice encrypts it with Bob's public key, and only Bob, holding his private key, can read it.
Common mistake: thinking the public key decrypts messages sent to its owner. The public key only locks. A message encrypted with Bob's public key can be unlocked only by Bob's private key, which never leaves him, so knowing the public key does not help an eavesdropper.
How RSA works, in miniature
RSA, the best-known asymmetric method, chooses two large primes, p and q, and multiplies them to give n. A public exponent e and a private exponent d are then chosen. Raising a number to the power e, then to the power d, all modulo n, gives back the original. The public key is the pair e and n; the private key is d.
Its security rests on factorising. Multiplying two primes is quick, but finding the primes from their product is extremely slow when n has hundreds of digits. Without p and q, an attacker cannot work out d.
To see why, try factorising 55: a few divisions soon find 5 × 11. But a real key's n has more than 600 decimal digits. Even trying the fastest known methods on the world's fastest computers would take far longer than a human lifetime. Multiplying the primes, by contrast, takes a computer a tiny fraction of a second.
Worked example 12: toy RSA
Take p = 5, q = 11 and e = 3. Find n and the private key d, then encrypt the message 9 and decrypt it again.
| Working | Reason |
|---|---|
| n = 5 × 11 = 55; (p − 1)(q − 1) = 4 × 10 = 40 | Both are needed to make the keys |
| d = 27, since 3 × 27 = 81 = 2 × 40 + 1 | d undoes e when working modulo 40 |
| Encrypt: 9³ MOD 55 = 729 MOD 55 = 14 | Raise to the public exponent, take the remainder |
| Decrypt: 14²⁷ MOD 55 = 9 | The private exponent gives back the message |
Real RSA keys use primes hundreds of digits long, so n cannot be factorised in any reasonable time. The arithmetic is exactly the same as in the toy example, only with far larger numbers, which computers handle using special routines for very long integers. Asymmetric encryption is much slower than symmetric encryption. So in practice it is used only to share a symmetric key safely, and that key then encrypts the rest of the conversation.
Digital signatures
The keys can also be used the other way round. If Alice encrypts a hash of her message with her own private key, anyone can decrypt it with her public key. If the result matches the hash of the message they received, they know it came from Alice and was not changed. This is a digital signature.
A signature proves two things at once. It proves who sent the message, because only the sender's private key could have made it. And it proves the message was not changed, because any change would give a different hash. It does not keep the message secret: anyone with the public key can check it, so a secret message must also be encrypted.
A secure web connection uses all of these ideas together. The browser checks the website's certificate and uses the site's public key to agree a fresh symmetric key for the session. From then on, every page and form is encrypted with the fast symmetric cipher. Hashes check that nothing was changed on the way, so the browser can show that the connection is secure.
A digital certificate, issued by a trusted organisation called a certificate authority, links a public key to its owner. When a browser connects to a bank's website, it checks the bank's certificate, so it knows the public key really belongs to the bank and not to an impostor.
Without certificates, an attacker could sit between the user and the bank and hand over the attacker's own public key. The user would encrypt everything for the attacker, who could read it and pass it on. A certificate, signed with the certificate authority's private key, lets the browser check that the key it was given is the bank's real one.
Check yourself. Alice wants to prove a message came from her. Which key does she use to sign it, and which key does Bob use to check it?
Show the answer
Alice signs with her own private key, which only she has. Bob checks the signature with Alice's public key, which anyone can get.
Section 6
Hashing
What a hash function does
A hash function takes data of any size and produces a fixed-size value, called a hash. The same input always gives the same hash. With a good hash function, even a tiny change to the input gives a completely different hash. It is also practically impossible to find an input that gives a particular hash.
Hashing is one-way. Unlike encryption, there is no key that turns a hash back into the data. Many different inputs share each hash, because there are far more possible inputs than hashes, so the original data simply is not stored in the hash.
Compare that with encryption. Encrypted data can always be decrypted by someone with the right key, because encryption is designed to be reversed. A hash is designed never to be reversed. So the two tools answer different questions: encryption asks who may read this data, while hashing asks whether this is the same data as before.
Common mistake: thinking a hash can be reversed to get the original data. A hash is not encrypted data. It keeps only a short summary of the input, and many inputs give the same hash, so there is nothing to decrypt. That is exactly why hashes are safe to store.
Storing passwords
A website should never store its users' passwords. Instead, it stores the hash of each password. When a user logs in, the site hashes what they type and compares it with the stored hash. If the database is stolen, the attacker gets only hashes, not passwords.
Sites also add a salt, a random value stored with each user, to the password before hashing. Two users with the same password then have different hashes, and an attacker cannot use a ready-made table of the hashes of common passwords.
Simple hash functions
Hash tables use simple hash functions to decide where to store each record. The remainder method takes the key MOD the table size. The folding method splits the key's digits into groups, adds the groups, and takes the remainder. A string can be hashed by adding its character codes and taking the remainder.
Worked example 13: three hash functions
Hash the key 123456 by folding into pairs with a table of 97 slots. Then hash the string CAT by adding its ASCII codes, with 10 slots.
| Working | Reason |
|---|---|
| Pairs: 12 + 34 + 56 = 102 | Split the digits into pairs and add them |
| 102 MOD 97 = 5 | Take the remainder for the table size |
| CAT: 67 + 65 + 84 = 216 | Add the character codes |
| 216 MOD 10 = 6 | The string goes in slot 6 |
The string ACT also hashes to 6, because it has the same letters. Two keys with the same hash are a collision. A hash table deals with collisions by linear probing, trying the next slot along, or by chaining, keeping a list in each slot.
A hash table is fast because the hash says exactly where to look. Finding a record takes about the same time whether the table holds ten records or ten million, as long as there are few collisions. That is why databases and programming languages use hash tables to look up records by their key.
The hash functions used in hash tables are chosen for speed and for spreading keys evenly across the slots. They do not need to be secure. The hash functions used for passwords and file checks are chosen for security instead. Password hashes are often made deliberately slow, so that an attacker trying millions of guesses is held back.
Checking data with hashes
A hash also works as a fingerprint for a file. A download site publishes the hash of each file. After downloading, the user hashes their copy; if the two hashes match, the file arrived complete and unchanged. A single flipped bit would give a completely different hash.
The hash functions used for security, such as those in the SHA family, produce long hashes, often 256 bits. With so many possible values, the chance of two different files sharing a hash by accident is negligible. They are also designed so that nobody can deliberately make two files with the same hash, a property called collision resistance.
Check yourself. Why does a password system hash the password rather than encrypt it?
Show the answer
An encrypted password could be decrypted by anyone who stole the key. A hash cannot be reversed at all, so even someone with the whole database cannot get the passwords back from it.
Reference
Key algorithms and definitions
| Term or algorithm | What it means | Example | Cost or rule to learn |
|---|---|---|---|
| Lossless compression | Original rebuilt exactly | Text, code | Removes repetition only |
| Lossy compression | Detail removed for good | Photos, music | Cannot be undone |
| Compression ratio | Original size ÷ compressed size | 2.4 MB to 0.6 MB is 4 | Bigger is better |
| Run-length encoding | Count and symbol for each run | 4A3B2C1D | 2 bytes per run |
| Dictionary coding | Repeated patterns stored once | 0 1 2 3 0 4 … | Saves on repeated words |
| Huffman coding | Short codes for common symbols | A = 0, B = 10, N = 11 | Total = Σ count × length |
| Caesar cipher | Shift every letter by the key | HELLO → KHOOR | Only 25 keys |
| Vernam cipher | XOR with a one-time random key | 01001000 → 11111110 | Key random, as long, used once |
| Asymmetric encryption | Public key locks, private key unlocks | Toy RSA, n = 55 | Rests on factorising n |
| Hashing | Fixed-size, one-way summary | 123456 → 5 | Collisions are possible |
Programming task
Programming task: a Huffman encoder
Aim
Write a Python program that builds Huffman codes for a piece of text and encodes the text as a string of bits. It must decode the bits again, and report the saving compared with ASCII and with a fixed-length code.
Design
The program counts each character. It keeps a list of nodes, each with a count, and repeatedly removes the two with the smallest counts, joining them under a new node. Ties are broken by taking the node made first, so the codes are always the same. When one node remains, a recursive walk gives each leaf its code, adding 0 for a left branch and 1 for a right branch.
Encoding joins the codes of the characters in order. Decoding reads bits one at a time into a buffer and, as soon as the buffer matches a code, writes that character and empties the buffer.
Code
from collections import Counter
from math import ceil, log2
def huffman(text):
counts = Counter(text)
order = 0
nodes = []
for ch, n in counts.items():
nodes.append((n, order, ch, None, None)); order += 1
while len(nodes) > 1:
nodes.sort(key=lambda node: (node[0], node[1]))
a, b = nodes.pop(0), nodes.pop(0)
nodes.append((a[0] + b[0], order, None, a, b)); order += 1
codes = {}
def walk(node, code):
n, _, ch, left, right = node
if ch is not None:
codes[ch] = code or "0"
else:
walk(left, code + "0"); walk(right, code + "1")
walk(nodes[0], "")
return codes
def encode(text, codes):
return "".join(codes[ch] for ch in text)
def decode(bits, codes):
back = {c: ch for ch, c in codes.items()}
out, buffer = "", ""
for b in bits:
buffer += b
if buffer in back:
out += back[buffer]; buffer = ""
return out
text = "ABRACADABRA"
codes = huffman(text)
bits = encode(text, codes)
print(codes, len(bits), "bits")
print("ASCII:", 8 * len(text), "fixed:", len(text) * max(1, ceil(log2(len(set(text))))))
print(decode(bits, codes))
Each node is a tuple of its count, the order it was made, its character and its two children. Sorting by count and then by order makes the tie-breaking rule exact, so the program always gives the codes shown in this chapter.
Testing
| Test | Input | Expected output | Why this test |
|---|---|---|---|
| 1 | BANANA | A = 0, B = 10, N = 11; 9 bits | Matches worked example 7 |
| 2 | BANANA | decodes to BANANA | Decoding reverses encoding |
| 3 | ABRACADABRA | 23 bits; ASCII 88, fixed 33 | Matches worked example 8 |
| 4 | AAAABBCD | 14 bits | Matches the check yourself question |
| 5 | MISSISSIPPI | 21 bits | Four symbols with uneven counts |
| 6 | AAAA | A = 0; 4 bits | A single symbol still needs one bit |
| 7 | ABCD | 8 bits, the same as a fixed 2-bit code | Equal counts give no saving |
Evaluation
The encoder gives the expected codes and totals for every test, and decoding always returns the original text. Test 6 shows the special case of one symbol, which still needs a one-bit code. Test 7 shows that Huffman coding saves nothing when every symbol is equally common.
The program does not store the table of codes with the encoded bits, so a real decoder could not use its output. An improvement would write the counts at the start of the file, so the decoder could rebuild the same tree, and would pack the bits into bytes.
Practice
Practice ladder
Rung 1: Recall and fluency
Q1. State two reasons for compressing a file before sending it.
Worked solution to Q1
A compressed file takes less time to send across a network, and it uses less storage space and less of a data allowance. A web page with compressed images also loads faster for its visitors.
Q2. Describe the difference between symmetric and asymmetric encryption.
Worked solution to Q2
Symmetric encryption uses the same secret key to encrypt and to decrypt, so both people need it. Asymmetric encryption uses a public key to encrypt and a matching private key to decrypt, so the private key never has to be shared.
Q3. State two properties of a good hash function.
Worked solution to Q3
The same input must always give the same hash, and a tiny change to the input should give a completely different hash. It should also be practically impossible to find an input that gives a chosen hash.
Rung 2: Application
Q4. Encode the image row BBBBBWWWWWWWWBBB with RLE and give the size at two bytes per run.
Worked solution to Q4
The runs are 5 black, 8 white and 3 black, so the encoding is 5B8W3B. That is 3 runs at two bytes each, giving 6 bytes instead of the original 16.
Q5. A 5,000,000-byte sound file is compressed to 1,250,000 bytes. Find the compression ratio.
Worked solution to Q5
The compression ratio is the original size divided by the compressed size: 5,000,000 ÷ 1,250,000 = 4. So the compressed file is a quarter of the size of the original.
Q6. Encrypt ATTACK AT DAWN with a Caesar shift of 5.
Worked solution to Q6
Each letter moves five places along the alphabet, wrapping from Z to A, and the spaces are left alone. The ciphertext is FYYFHP FY IFBS, and shifting back by 5 recovers the message.
Q7. Find the Huffman codes and the total bits for the text AABBBBBBCCCD.
Worked solution to Q7
The counts are B 6, C 3, A 2 and D 1. Joining D and A, then that node and C, then B gives B = 0, C = 10, D = 110 and A = 111. The total is 6 × 1 + 3 × 2 + 1 × 3 + 2 × 3 = 21 bits.
Rung 3: Analysis
Q8. Explain why RLE is a poor choice for compressing an English essay.
Worked solution to Q8
English text has very few runs of the same character, so most runs have length 1. Each one then costs a count as well as a character, so the encoded essay would be close to twice its original size.
Q9. XOR the byte 01000001 with the key 10011011, and explain how the receiver recovers the plaintext.
Worked solution to Q9
Comparing the bits pair by pair, XOR gives 11011010, a 1 wherever the bits differ. The receiver XORs this with the same key, 10011011, which flips the same bits back and gives 01000001 again.
Q10. With p = 3, q = 11 and e = 7, find n and the private key d, and encrypt the message 4.
Worked solution to Q10
First, n = 3 × 11 = 33 and (p − 1)(q − 1) = 2 × 10 = 20. Since 7 × 3 = 21 = 20 + 1, the private key is d = 3. Encrypting gives 4⁷ MOD 33 = 16384 MOD 33 = 16.
Q11. Hash the key 984512 by folding into pairs, with a table of 50 slots.
Worked solution to Q11
The pairs are 98, 45 and 12, which add to 155. Taking the remainder for the table size gives 155 MOD 50 = 5, so the key goes in slot 5.
Rung 4: Stretch
Q12. Explain why a Vernam cipher is unbreakable when used correctly, but a Caesar cipher is not.
Worked solution to Q12
With a truly random one-time key as long as the message, every possible plaintext is equally likely, so the ciphertext reveals nothing. A Caesar cipher has only 25 keys, so trying them all, or using letter frequencies, breaks it at once.
Q13. A 40-bit key is tested at a billion keys per second. Find the average time to find it by brute force, and the effect of adding one more bit.
Worked solution to Q13
The average is 2³⁹ ÷ 10⁹, which is about 550 seconds, a little over nine minutes. Adding one bit doubles the number of keys, so it doubles the time to about 1,100 seconds.
Q14. Explain why websites add a salt to each password before hashing it.
Worked solution to Q14
Without a salt, everyone with the same password has the same hash, and attackers can look hashes up in a ready-made table. A random salt makes every user's hash different, so the table is useless and each password must be attacked separately.
Exam practice
Exam technique and worked answer workshop
For compression, say what kind it is and why it suits the data. "Lossless, because every digit of the spreadsheet must be kept exactly" earns more than "lossless is better". When calculating, show the size before and after and the ratio.
For Huffman coding, show the counts, the order in which nodes are joined, the tree and the codes. Then give the total as the sum of count times code length for each character.
For encryption, name the key used at each step. Most marks are lost by saying "the public key decrypts" or by confusing encryption with hashing.
Exam question 1 (4 marks · Paper 01 · about 5 minutes)
(a) Compare lossy and lossless compression. [2]
(b) Give one example of data that must use lossless compression, and explain why. [2]
Mark scheme for exam question 1
- B1 lossless compression allows the original data to be rebuilt exactly
- B1 lossy compression permanently removes some data, so the original cannot be rebuilt
- B1 text, program code or a spreadsheet
- B1 a single changed character or digit would make it wrong or unusable
Exam question 2 (5 marks · Paper 01 · about 7 minutes)
A row of a black and white image is WWWWWWBBBWWW.
(a) Encode the row using run-length encoding. [2]
(b) Calculate the size of the encoded row, at one byte per count and one per colour, and compare it with the original. [2]
(c) Explain why RLE would not suit a photograph. [1]
Mark scheme for exam question 2
- M1 runs identified as 6 white, 3 black, 3 white
- A1 6W3B3W
- M1 3 runs × 2 bytes
- A1 6 bytes against 12 bytes, half the size
- B1 neighbouring pixels in a photo are rarely exactly the same colour, so runs are short and RLE may make the file bigger
Exam question 3 (6 marks · Paper 01 · about 9 minutes)
(a) Construct a Huffman tree for the text BANANA. [3]
(b) Give the code for each letter and the total number of bits. [2]
(c) State how many bits ASCII would need. [1]
Mark scheme for exam question 3
- B1 counts A 3, N 2, B 1
- B1 B and N joined first into a node of 3
- B1 that node joined with A to make the root of 6
- B1 A = 0, B = 10, N = 11, or an equivalent set of codes
- B1 9 bits
- B1 48 bits
Exam question 4 (5 marks · Paper 01 · about 7 minutes)
(a) Describe how the Vernam cipher encrypts a message. [2]
(b) State three conditions for the Vernam cipher to be perfectly secure. [3]
Mark scheme for exam question 4
- B1 each bit of the plaintext is combined with a bit of the key
- B1 using XOR, and the same XOR with the key decrypts it
- B1 the key is truly random
- B1 the key is at least as long as the message
- B1 the key is used only once
Exam question 5 (6 marks · Paper 01 · about 9 minutes)
An online shop needs to keep customers' card details secret while they are sent, and to store customers' passwords. Discuss how the shop should use encryption and hashing.
Mark scheme for exam question 5
Level 3 (5–6 marks): a clear explanation of asymmetric and symmetric encryption for sending data and of hashing for passwords, with reasons for each choice. The answer reaches a justified conclusion. It is well organised and uses technical terms accurately.
Level 2 (3–4 marks): a correct description of encryption and hashing with some link to the shop. The reasons are limited.
Level 1 (1–2 marks): some relevant points, such as that data should be encrypted, with little application. The answer may lack structure.
0 marks: no response or no response worthy of credit.
Indicative content:
- card details must be read by the shop, so they must be encrypted, not hashed
- the browser can encrypt with the shop's public key, which only the shop's private key unlocks
- a digital certificate shows that the public key really belongs to the shop
- asymmetric encryption is slow, so it is used to share a symmetric key for the rest of the session
- passwords never need to be read back, only checked
- so the shop stores a hash of each password, never the password itself
- at log-in the typed password is hashed and compared with the stored hash
- a salt for each user stops identical passwords giving identical hashes
- a stolen database then reveals neither the passwords nor any key to decrypt them
Annotated model answer: exam question 5
"Card details must be read by the shop, so they must be encrypted, not hashed. The customer's browser encrypts them with the shop's public key, so only the shop's private key can decrypt them." (Asymmetric encryption, correctly keyed.)
"A certificate from a certificate authority proves the public key belongs to the shop. Because asymmetric encryption is slow, it is used to agree a symmetric key, which then encrypts the rest of the session." (Certificates and the symmetric session key.)
"Passwords only ever need to be checked, never read, so the shop should store a salted hash of each one. At log-in, the typed password is salted and hashed and compared with the stored hash." (Hashing for passwords, with salt.)
"So if the database were stolen, the attacker would get only salted hashes, which cannot be reversed. The shop should encrypt data that must be read later, and hash data that only needs to be checked." (A justified conclusion.)
This answer reaches Level 3 and scores 6 marks. It matches each tool to the job it does best and explains why.
Exam question 6 (4 marks · Paper 01 · about 5 minutes)
Alice wants to send Bob a secret message using asymmetric encryption.
(a) State which key Alice uses to encrypt the message, and which key Bob uses to decrypt it. [2]
(b) Explain why an eavesdropper who knows Bob's public key cannot read the message. [2]
Mark scheme for exam question 6
- B1 Alice encrypts with Bob's public key
- B1 Bob decrypts with his own private key
- B1 only the private key can decrypt data encrypted with the public key
- B1 the private key is never shared, and cannot practically be worked out from the public key
Exam question 7 (4 marks · Paper 01 · about 5 minutes)
(a) Hash the key 123456 using folding into pairs and a table of 97 slots. [2]
(b) Explain why a website stores the hash of a password rather than the password. [2]
Mark scheme for exam question 7
- M1 12 + 34 + 56 = 102
- A1 102 MOD 97 = 5
- B1 if the database is stolen, the attacker gets only hashes
- B1 a hash cannot be reversed to find the password, but a typed password can still be checked by hashing it
Exam question 8 (6 marks · Paper 02 · about 9 minutes)
Write a function rleEncode(text) that returns the run-length encoding of a string, as each run's count followed by its character. State what it returns for AAAABBBCCD.
Mark scheme for exam question 8
- B1 a function header taking the string
- B1 an empty result and a count starting at 1
- B1 a loop through the string comparing each character with the next
- B1 the count increases while the characters match
- M1 when they differ, or at the end, the count and character are added to the result and the count is reset
- A1 the result is returned, and AAAABBBCCD gives 4A3B2C1D
Annotated model answer: exam question 8
function rleEncode(text)
result = ""
count = 1
for i = 0 to text.length - 1
if i < text.length - 1 AND text[i] == text[i + 1] then
count = count + 1
else
result = result + str(count) + text[i]
count = 1
endif
next i
return result
endfunction
The header earns the first mark, and the empty result with the count at 1 earns the second. Comparing each character with the next earns the third, and counting matches the fourth. Writing out each run and resetting the count earns the method mark, and returning 4A3B2C1D earns the last.
Connections
Synoptic link
Huffman codes are built with a priority queue and a binary tree. These structures are taught in Arrays, records, stacks and queues and in Linked lists, hash tables, graphs and trees. Hash tables, with their collisions and probing, are taught fully in the second of those chapters.
The Vernam cipher uses the XOR operation from Boolean algebra and logic circuits. Encryption is the core of network security, covered in Network security and threats, and the law on protecting personal data appears in Legal, moral, ethical and cultural issues.
Synoptic question 1. A message is compressed and encrypted before sending. Why should it be compressed first?
Answer to synoptic question 1
Good encryption makes the ciphertext look like random data, with no repeats or patterns. Compression relies on patterns, so it would barely shrink the encrypted data. Compressing first removes the patterns while they still exist.
Recap
Recap and next step
- Lossless compression rebuilds data exactly; lossy compression removes detail for good. Ratio = original size ÷ compressed size.
- RLE stores a count and a symbol for each run, so it suits long runs and fails on data without them. Dictionary coding stores repeated patterns once.
- Huffman coding gives frequent symbols short codes; the total is the sum of count × code length, and no code starts another.
- Symmetric encryption uses one shared key. Caesar has only 25 keys; Vernam, with XOR and a random one-time key, is perfectly secure.
- Asymmetric encryption encrypts with the receiver's public key and decrypts with their private key; signatures use the sender's private key.
- Hashing gives a fixed-size, one-way summary. Passwords are stored as salted hashes, and hash tables handle collisions.
Next chapter: Databases and normalisation looks at how data is organised into related tables, so it can be stored without repetition and searched quickly.
For your exam board
OCR A Level Computer Science (H446): this chapter covers section 1.3.1, Compression, Encryption and Hashing, in Component 01: lossy and lossless compression, run-length encoding and dictionary coding, symmetric and asymmetric encryption, and the uses of hashing.
AQA A Level Computer Science (7517): compression, including run-length encoding and dictionary-based methods, and encryption, including the Caesar and Vernam ciphers, appear in the fundamentals of data representation section, assessed on Paper 2. Huffman coding is a useful extension.