Avast ye, this be a machine-translated text an’ may contain errors, aye!
About the cryptography tasks
These tasks be structured a bit different than the other tasks on Piggy, I be wonderin’ what ye scallywags prefer! 😎
There be comin’ a good bit o’ information to start with about the topics, then there be comin’ some tasks after that!
The “levels” in this task ain’t quite like the levels before, here things be more divided into topics.
What be a “Cipher”?
Have ye ever had a hankerin’ to write a secret message to a mate, so no other scoundrel can understand it? Then ye need a Cipher, or cipher in the English tongue! A cipher be simply a method that turns plain text into “code” by swappin’ characters (often letters) with other characters. The result looks like gibberish to those who don’t know how the code works. The point be that only those who know the key (the rule for swappin’ the letters) can make the code understandable again. In other words: ciphers make secret messages possible, be it childhood games with secret languages or true spies sendin’ encrypted messages. 😄
Visste du?
Did ye know?
The word “cipher” actually hails from an Arabic word: the word sifr, which means “naught”. Perhaps ‘cause the secret code looked like summat else (naught to see here!) when the scallywags couldn’t crack it!
There be many a cipher – some use numbers, some use symbols, and modern data encryption uses right complicated algorithms. These complicated algorithms require right complicated maths, so we can be lookin’ at some simpler algorithms first!
Monoalphabetic Ciphers
Let us first examine some o’ the simplest (and oldest) code methods t’ be found: monoalphabetic ciphers.
Monoalphabetic sounds like a fearsome word, aye, but we can break it down: mono means “one”, and alphabetic be about the alphabet itself.
So, monoalphabetic ciphers be codes where ye use a single “encryption alphabet” for the whole message. That is t’ say, each letter in the original text always be swapped with the same letter throughout the encrypted message.
For example, if ye’ve decided that A shall be swapped with X, then all the A’s in the text be turned int’ X.
Caesar Cipher
The classic example o’ a monoalphabetic cipher be the Caesar cipher (named after Julius Caesar, aye). ‘Tis basically a rule t’ “shift” all the letters a certain number o’ places along the alphabet. ‘Tis said Caesar himself used a shift o’ 3 letters in his secret messages. It works such that A becomes D, B becomes E, C becomes F, and so on through the alphabet. (When ye pass Z, ye start back at A again.) A message like ABC would thus become DEF if we use Caesar’s method.
How the Caesar Cipher Works in Practice:
- Choose a key: Decide on a secret number (for example 3) that indicates how many places ye shall shift each letter.
- Replace each letter: For each letter in the original message, find the letter that lies so many places after it in the alphabet (for key 3, A becomes D, B becomes E, etc. – remember to wrap around to A again after Z if needed). Ye can also include Æ, Ø and Å, but this be a bit more complicated.
- Encrypted message: Replace the letters and write the new message with the “shifted” letters. Shiver me timbers – ye have an unreadable, secret text that only those with the key can understand!
- To decrypt (that is, to turn it back into readable text) one simply does the opposite shift back. If ye know the key (e.g. 3), it be as easy to read the message by moving the letters 3 back in the alphabet.
Sikkerhet?
These codes ain’t overly secure in the long run, savvy? ‘Cause the pattern (the substitution) be fixed, a scoundrel with enough patience or a few clever tricks can quickly reveal the secret. For instance, there be only a few possible shifts in the Caesar cipher, as many as the alphabet itself, so anyone can try ‘em all ‘til the message makes sense – or use letter frequencies to guess their way through. In other words, mayhaps don’t be usin’ the Caesar cipher for super-secret diary entries or state secrets 😉.
Single-alphabet ciphers be a wondrous way t’ learn the principle o’ encryption, aye. They be simple an’ show how we can use a single rule (a key, ye see) t’ turn a plain text inta somethin’ mysterious an’ unreadable – an’ back again! So next time ye wish t’ send a mate a secret message, ye can use the Caesar cipher! Perchance ye can create yer own variant o’ Caesar’s secret alphabet? 🔐✨
Tasks
Oppgave 1: Datainnsamling
For å komme i gang, må vi samle inn data om de forskjellige skipstypene. Dette inkluderer informasjon som lengde, bredde, dypgang, tonnasje og antall besetningsmedlemmer. Dataene skal samles inn fra offentlige kilder, som skipsregisteret og maritime databaser.
Task 1: Gatherin’ Booty (Data, that is!)
To get us started, we must gather data on the different ship types. This includes information such as length, width, draft, tonnage, and the number o’ crew. The data shall be gathered from public sources, like the ship registry and maritime databases.
Oppgave 2: Analyse av data
Når dataene er samlet inn, skal de analyseres for å finne mønstre og trender. Vi skal se på sammenhengen mellom skipstype og ytelse, samt faktorer som påvirker drivstofforbruket. Resultatene skal presenteres i form av grafer og tabeller.
Task 2: Analyzin’ the Spoils
Once the data be gathered, it shall be analyzed to find patterns and trends. We’ll be lookin’ at the connection between ship type and performance, as well as factors that affect fuel consumption. The results shall be presented in the form o’ charts and tables.
Oppgave 3: Utvikling av modell
Basert på analysen, skal vi utvikle en modell som kan forutsi ytelsen til et skip basert på dets egenskaper. Modellen skal ta hensyn til faktorer som skipets form, størrelse, vekt og motorkraft.
Task 3: Craftin’ a Model
Based on the analysis, we shall craft a model that can predict the performance o’ a ship based on its properties. The model shall take into account factors like the ship’s shape, size, weight, and engine power.
Programmerin’ languages, ye ask?
As afore, feel free t’ use any language ye be wantin’! The examples here be in Python, savvy?
Task 1.1 - Caesar Cipher Encryption
Now we be writin’ some code, aye! We shall start simple by craftin’ the encryption, based on the theory it should be quite straightforward.
Implement encryption with the Caesar Cipher by usin’ a function that takes in text and a number that be the “key”, that is how much the alphabet shall be rotated with.
Tips til framgangsmåte.
- Forge a function named
caesarthat takes in the text to be encrypted and a “shift”, that is, how many spots in the alphabet the text shall be shifted. - Go through the text letter by letter, ye scallywag.
- We won’t “shift” any signs other than letters: find out how ye check if a sign in the text be a letter.
- We shall “rotate” the letter by n spots, so we must add the rotation: find out how ye can turn the text into numbers so ye can add the shift. Hint: the
ord()function. - Avast! Here ye get different values based on whether ye have small or large letters. Refer to the ASCII Table.
- Once ye have a value, it be as easy as adding n to the value. But what happens if ye be at the end of the alphabet? We get naught but nonsense after the letter Z. How be this fixed? This requires some thinkin’.
Fikse enkrypteringen.
To fix the encryption fully requires some thinkin’.
- The first step to ponder is the use of the modulus operator,
%. - Since the alphabet (in English) consists of 26 letters, we can take the modulus with
26. - But this won’t work quite right, do ye see why?
- Try to
printout the value of a character withord(), what do ye get? - For
aye get 97. If ye take modulus 26 with this, ye get 19. Remember that modulus will always give an answer between 0 and the number. - This can be fixed by savin’ the start value for large and small letters, subtractin’ this from the letter, and then takin’ the modulus. Then it becomes:
(ord(bokstav) - ord('a')) % 26 - To get back the rightful letter, ye just add the start value back again.
- After all this, ye can finally turn the number back into a letter. Here ye can use the
chr()function. - Now ye can finally add the letter to a result and return the encrypted text!
Løsning:
def caesar_cipher(text, shift):
result = ""
for char in text:
if char.isalpha():
# find the startin' point based on big and small letters
start = ord('A') if char.isupper() else ord('a')
# The tricky shiftin' math
result += chr((ord(char) - start + shift) % 26 + start)
else:
result += char
return result
Task 1.2 - Caesar Cipher Decryption
Decryption be just doin’ the opposite reckonin’ to encryption, aye. Ye subtract the offset instead o’ addin’ it.
Tips til framgangsmåte.
Use the magic ye crafted in task 1 for this. Just take the same function, but in reverse. Ye can do this by changin’ the shift to 26 - shift.
Solution:
def caesar_decrypt(text, shift):
return caesar_cipher(text, 26 - shift)
Other Monoalphabetic Ciphers (ex. Atbash)
There be other monoalphabetic ciphers as well! One o’ the simpler ones be called the “Atbash” Cipher.
How Does Atbash Work?
This be a simple one, instead o’ a rotation, letters be mapped to the opposite alphabet. Here be a table showin’ the mappin’:
| a | b | c | d | e | f | g | h | i | j | k | l | m | n | o | p | q | r | s | t | u | v | w | x | y | z |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| z | y | x | w | v | u | t | s | r | q | p | o | n | m | l | k | j | i | h | g | f | e | d | c | b | a |
Task 1.3 - Atbash Cipher Encryption and Decryption
The beauty o’ the Atbash be that, seein’ as how the encryption be a one-to-one transformation, it works directly in reverse. Aye, if ye be havin’ crafted the encryption, ye’ve also, automatically crafted the decryption.
How can this be done in practice?
Ye can either subtract the letter in relation to Z, or create a “Look-up” table. Aye, that means a table or dictionary that contains all the letters from a to z and what they shall become. This can be a good solution if ye wish to create another type o’ encryption.
Lookup-table implementation.
letters = {
'a': 'z'
'b': 'y'
'c': 'x'
'd': 'w'
# ... add the rest o' the letters down below
}
Aye, with this here table ye can go through letter by letter, then fetch the value per letter from the lookup table, and write it out. What must ye do for capital and small letters, savvy?
Part 2 - Cryptoanalysis o’ Monoalphabetic Ciphers
In this here part, ye shall try to craft an algorithm to “crack” a Caesar cipher, that be takin’ a encrypted text, then gettin’ the original text without knowin’ the key.
This can be done somewhat manually, or ye can try to employ simple “cryptanalysis”. This be a concept we shall delve deeper into later, but for now we shall only look at one o’ the simplest ways: Frequency Analysis. Ye can read more about this concept here: Frequency Analysis or here Wikipedia - frequency analysis.
This method can be used in more than just Caesar ciphers, it can be used in more complicated algorithms as well, but Caesar ciphers be so simple that frequency analysis be trivial.
How works the frequency analysis, matey?
Frequency analysis be, as the name hints, a way to spy on the frequency of letters in a scroll. Why be this useful? Imagine ye have a long parchment, let’s say an English text, plucked from Wikipedia - frequency analysis:
In cryptanalysis, frequency analysis is the study of the frequency of letters or groups of letters in a ciphertext. The method is used as an aid to breaking classical ciphers.
Frequency analysis is based on the fact that, in any given stretch of written language, certain letters and combinations of letters occur with varying frequencies. Moreover, there is a characteristic distribution of letters that is roughly the same for almost all samples of that language. For instance, given a section of English language, E, T, A and O are the most common, while Z, Q, X and J are rare. Likewise, TH, ER, ON, and AN are the most common pairs of letters termed bigrams or digraphs), and SS, EE, TT, and FF are the most common repeats. The nonsense phrase ETAOIN SHRDLU represents the 12 most frequent letters in typical English language text.
In some ciphers, such properties of the natural language plaintext are preserved in the ciphertext, and these patterns have the potential to be exploited in a ciphertext-only attack.
If we take this text and transform it with a Caesar cipher (and toss overboard the commas, spaces, and other strange markings), we get this here cipher-text:
xcrgneipcpanhxhugtfjtcrnpcpanhxhxhiwthijsnduiwtugtfjtcrnduatiitghdgvgdjehduatiitghxcprxewtgitmiiwtbtiwdsxhjhtsphpcpxsidqgtpzxcvraphhxrparxewtghugtfjtcrnpcpanhxhxhqphtsdciwtupriiwpixcpcnvxktchigtirwdulgxiitcapcvjpvtrtgipxcatiitghpcsrdbqxcpixdchduatiitghdrrjglxiwkpgnxcvugtfjtcrxthbdgtdktgiwtgtxhprwpgpritgxhixrsxhigxqjixdcduatiitghiwpixhgdjvwaniwthpbtudgpabdhipaahpbeathduiwpiapcvjpvtudgxchipcrtvxktcphtrixdcdutcvaxhwapcvjpvttippcsdpgtiwtbdhirdbbdclwxatofmpcsypgtgpgtaxztlxhtiwtgdcpcspcpgtiwtbdhirdbbdcepxghduatiitghitgbtsqxvgpbhdgsxvgpewhpcshhttiipcsuupgtiwtbdhirdbbdcgtetpihiwtcdchtchtewgphttipdxchwgsajgtegthtcihiwtbdhiugtfjtciatiitghxcinexrpatcvaxhwapcvjpvtitmixchdbtrxewtghhjrwegdetgixthduiwtcpijgpaapcvjpvteapxcitmipgtegthtgktsxciwtrxewtgitmipcsiwthtepiitgchwpktiwteditcixpaidqttmeadxitsxcprxewtgitmidcanpiiprz
This text looks impossible to crack, aye? But with the help of “Frequency analysis,” it be not just possible, but easy.
This be a figure showin’ the distribution of letters in English. What we can see is that the letter E be the most frequent, followed by T, A, and O.
This can be turned into a table and used to count and analyze a given cipher-text to crack it wide open. In the tasks below, ye shall craft a program that can crack Caesar ciphers all on its own. ‘Tis true that the Caesar cipher be so simple that ye could just check all 26 possibilities by hand, but here we be findin’ the solution, fully automatic-like.
Task 2.1 - Craftin’ a Frequency Table
In a python file, create a frequency table o’ the letters in the English tongue. Ye can try and find this yerself, but if ye be not inclined to do so, we understand that, aye!
If ye truly wish to find it yerself, ye can do as in Task 2.2, but on a right large text.
English Letter Frequency (The Treasure)
english_letter_frequency = {
'E': 12.70,
'T': 9.06,
'A': 8.17,
'O': 7.51,
'I': 6.97,
'N': 6.75,
'S': 6.33,
'H': 6.09,
'R': 5.99,
'D': 4.25,
'L': 4.03,
'C': 2.78,
'U': 2.76,
'M': 2.41,
'W': 2.36,
'F': 2.23,
'G': 2.02,
'Y': 1.97,
'P': 1.93,
'B': 1.29,
'V': 0.98,
'K': 0.77,
'J': 0.15,
'X': 0.15,
'Q': 0.10,
'Z': 0.07
}
Task 2.2 - Countin’ the Frequency o’ Letters in a Text
Now, we be makin’ an algorithm t’ find the frequency o’ letters in a given text.
Tips til framgangsmåte
- Start with a function that takes in a scrap o’ text (can be anythin’).
- In the function, create a “dictionary” (Python Dictionaries), with entries for every letter in the alphabet, set to
0. ({'A' = 0, 'B' = 0, 'C' = 0, ..., 'Z' = 0}) - Scour the whole text and count every single letter (add 1 to the matchin’ entry in the dictionary). Ye should likely ignore signs that be not letters, and mind both big and small letters.
- Keep track o’ how many letters have been counted in total.
- When ye be done countin’, divide
/each value in the table by the length o’ the text and then multiply by 100, this will give ye a percent-frequency. (Ye can, o’ course, just let yer table stay between 0 and 1). - Now ye shall have a frequency table for the text.
Task 2.3 - Compare the frequency o’ a text with the true frequency
Once ye’ve found the frequency o’ all the letters in the text, ye can craft a function that finds the “distance”. Arrr? What be meant by that?!
Ye can picture the frequency o’ somethin’ like E in the text bein’ a number. Ye can find the “distance” this has with the actual frequency, which be 12.70. Example: The frequency be 9.63, what be the distance? The distance be the absolute value (negative numbers become positive) between these two values: \(12.70 - 9.63 = 3.07\).
Craft a function that goes through each o’ the letters and finds the distance. Then, add all the distances together to a “total” distance.
Math function?
If ye be wonderin’ how the math function for this be lookin’, ‘tis like so:
\(\sum_{n=0}^{N} \lvert a - b\rvert\)
Tips til framgangsmåte
- Use a
forloop to trek through the whole frequency table, matey. - For every letter in the frequency table, find the absolute value compared to the true frequency. Use the
abs()function in Python for this booty. - Add all the values together, and ye shall find the final treasure.
Task 2.4 - “Crack” the Caesar Cipher
Now we shall finally put together all we have done so far! Now we shall “crack” a Caesar cipher.
Create a program that “cracks” a Caesar cipher! Without user input, ye be able to toss in an encrypted text and retrieve the decrypted text without needin’ a key.
Test data
Here be some test data ye can use, what say ye to these?
| Test-data |
|---|
cqrbvnbbjpnrbjenahbnlancxwnqxynoduuhhxdjanjkuncxmnlxmnrclxvyuncnuhjwmqnanjanbxvnfxamboaxvxdaojexarcnsnmrqnuuxcqnanrcbxenajwjtrwrqjencqnqrpqpaxdwmhxdfnanarpqccqnwnpxcrjcrxwbfnanbqxac |
lsaizivxlmwqiwwekimwuymxiwlsvxwsmxqmklxrsxasvoewibtigxihlsaizivmjmxhsiwksshnsf |
bmtxymjwjsfdfsxbjwrjxyfsifsizsktqidtzwxjqkqtslqnajymjpnslgfwsfwitmjdtzhtrjrtxyhfwjkzqqdzutsdtzwmtzwynxstbxywzhpybjqajljyymjjytgjikwfshnxhtktwymnxwjqnjkrzhmymfspxynxgnyyjwhtqifsinfrxnhpfymjfwymfajdtzmfivznjylzfwistyfrtzxjxynwwnslbjqqlttisnlmynkdtzitrjjymtwfyntfsirfwhjqqzxymjwnafqxtkrdbfyhmgniymjrrfpjmfxyj |
zwkyvivrivrepzuzfkjzekyviffdnzcckyvpgcvrjvjkreulgjrzukyvjritrjkztkvrtyvirwkvircfexjzcvetvfevwivjydreifjvkfyzjwvvkefnkyvedzjkvinypufpfltfejzuvipflijvcwrezuzfkzehlzivukyvkvrtyvinzkyrjevvinvccrtklrccpzufekjrzukyvjkluvekslkzyrkvkfjvvpfljkreuzexlgkyvivrccsppflijvcw |
uwwilxchaniuffehiqhfuqmizupcuncihnbylycmhiqusuvyymbiofxvyuvfynizfscnmqchamulyniimguffniayncnmzunfcnnfyvixsizznbyaliohxnbyvyyizwiolmyzfcymuhsqusvywuomyvyymxihnwulyqbunboguhmnbchecmcgjimmcvfysyffiqvfuwesyffiqvfuwesyffiqvfuwesyffiqvfuweiibvfuweuhxsyffiqfynmmbueycnojufcnnfyvullsvlyuezumncmlyuxswigcha |
Tips til framgangsmåte
- Start by craftin’ a function that takes in some text.
- Use the decryption function for Caesar’s cipher with a rotation of N on the text, where N starts at 0.
- Make a frequency table o’ the result.
- Figure out the distance o’ the result compared to the true frequency table.
- Either: a) keep track o’ the distance in a list, or b) keep track o’ the smallest value and the rotation (this be the key).
- Increase the rotation by 1 and repeat steps 2 to 6 until N reaches 26 (a full rotation).
- Return the decrypted text, meanin’ the smallest distance be the right key.

