Introduction to Cryptography for Beginners

Emmanuel Daniel - Sep 4 - - Dev Community

Part 1: A Beginner's Journey into the World of Secured Information

The Hidden Messages of the Ancient Mayans

Imagine you’re an archaeologist, standing in the dense jungles of Central America, gazing at the ruins of an ancient Mayan city. The stone walls are covered in hieroglyphs—complex symbols that hold the secrets of a civilization long gone. For centuries, these symbols were a mystery, a puzzle that only a select few could decode. The ancient Mayans were masters of secrecy, encoding their knowledge, history, and rituals into these intricate scripts to protect them from invaders and outsiders.

Just like the Mayans, humanity has always sought ways to protect information—whether it be the location of treasure, military strategies, or personal secrets. Over the centuries, the art and science of securing information evolved into what we now know as cryptography. From the enigmatic Mayan glyphs to the digital encryption methods that safeguard your online banking today, cryptography is all around us.

In this part, we will explore the fundamentals of cryptography, delve into its real-world applications, and even get our hands dirty with some JavaScript to see these principles in action. Whether you're a seasoned developer or just curious about the mysteries of code, this journey will illuminate the hidden world of secured communication.

1. The Art of Encryption: Locking Away Secrets

What is Encryption?

Encryption is like creating a secret language that only you and your trusted allies can understand. It involves transforming a readable message into a coded form that can only be deciphered by someone who has the key. Throughout history, encryption has played a crucial role in protecting sensitive information from prying eyes.

Historical Example: The Mayan Glyphs

The Mayans used a sophisticated system of hieroglyphs to record their knowledge. To the untrained eye, these symbols were incomprehensible, but to the Mayans, they were a powerful way to encode their understanding of the world. Deciphering these glyphs required not only knowledge of the symbols themselves but also an understanding of the cultural and historical context in which they were used.

JavaScript Example:

Let’s see a simple example of encryption using JavaScript. We’ll use the CryptoJS library, which allows us to encrypt a message with a key, much like locking it away with a secret code.

// Import CryptoJS
import * as CryptoJS from 'crypto-js';

// Encryption
const plaintext = "Hello World!";
const key = "secretkey123"; // Key for encryption

// Encrypt the plaintext
const ciphertext = CryptoJS.AES.encrypt(plaintext, key).toString();

console.log("Encrypted:", ciphertext);

Enter fullscreen mode Exit fullscreen mode

In this example, CryptoJS.AES.encrypt takes a plaintext message and a secret key, transforming the message into an encrypted string that appears as a jumble of characters to anyone without the key.

2. Hashing: Creating Unique Identifiers

What is Hashing?

Hashing is the process of taking an input and transforming it into a fixed-size string of characters, typically a hash code. Unlike encryption, which can be reversed with the correct key, hashing is a one-way street. Once a piece of data is hashed, you cannot retrieve the original input. Hashing is commonly used to verify data integrity and secure passwords.

Historical Example: The Stone Calendars

The Mayans also created elaborate stone calendars to track time and important events. These calendars were so precise and unique that no two were exactly alike. In a way, these calendars were like early hash functions—each one representing a unique output that couldn’t be easily replicated.

JavaScript Example:

Here’s how you can generate a hash of a message using the crypto module in Node.js:

import * as crypto from 'crypto';

// Hashing
const hash = crypto.createHash('sha256').update('Hello World!').digest('hex');

console.log("Hash:", hash);

Enter fullscreen mode Exit fullscreen mode

This creates a SHA-256 hash of the message "Hello World!", producing a unique, fixed-length string that represents the original input.

3. Encoding: Making Data Accessible

What is Encoding?

Encoding is a process used to transform data into a different format using specific rules. Unlike encryption, encoding isn’t meant to secure the data but to make it compatible with various systems. It’s like converting a Mayan glyph into a modern alphabet so that it can be easily read and understood by others.

Historical Example: The Rosetta Stone

The Rosetta Stone is a famous artifact that helped historians decode Egyptian hieroglyphs. The stone contained the same text written in three different scripts: Greek, Demotic, and Egyptian hieroglyphs. By comparing these scripts, scholars were able to crack the code of ancient Egyptian writing, making it accessible to the world.

4. Implementing Morse Code in JavaScript

To give you a practical example of encoding, let's implement Morse code in JavaScript. This simple encoding system was widely used in the 19th and early 20th centuries for telegraphy, allowing people to communicate over long distances.

Morse Code Basics

Morse code represents each letter of the alphabet and each numeral with a unique sequence of dots (.) and dashes (-). For example:

  • A is represented as .-
  • B is represented as -...
  • 1 is represented as .----

JavaScript Implementation

Here’s a JavaScript implementation of Morse code for encoding and decoding messages:

// Morse Code Dictionary
const morseCodeDict = {
 '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': '--..',
 '1': '.----',
 '2': '..---',
 '3': '...--',
 '4': '....-',
 '5': '.....',
 '6': '-....',
 '7': '--...',
 '8': '---..',
 '9': '----.',
 '0': '-----',
 ' ': ' / ',
};

// Encoding Function
function encodeToMorse(text) {
    return text.toUpperCase().split('').map(char => morseCodeDict[char] || '').join(' ');
}

// Decoding Function
function decodeFromMorse(morseCode) {
    const reverseDict = Object.fromEntries(Object.entries(morseCodeDict).map(([key, value]) => [value, key]));
    return morseCode.split(' ').map(code => reverseDict[code] || '').join('');
}

// Example Usage
const message = "Hello World";
const encodedMessage = encodeToMorse(message);
console.log("Encoded Message:", encodedMessage);

const decodedMessage = decodeFromMorse(encodedMessage);
console.log("Decoded Message:", decodedMessage);
Enter fullscreen mode Exit fullscreen mode

Simple steps:

  1. Morse Code Dictionary: A mapping of characters to their Morse code equivalents.
  2. Encoding Function: Converts a text string to Morse code.
  3. Decoding Function: Converts Morse code back to the original text.

5. Real-World Use Cases of Morse Code

  • Emergency Communication: Morse code is still used in emergencies where voice communication might not be possible, such as sending distress signals in remote areas.
  • Amateur Radio: Morse code is popular among ham radio operators, who use it to communicate over long distances.
  • Historical Context: Understanding Morse code gives us insight into early telecommunication systems and the evolution of digital communication.

Conclusion: The Art and Science of Cryptography

Cryptography is a fascinating field that blends the precision of mathematics with the creativity of code-breaking. From ancient scripts like the Mayan glyphs to modern encryption techniques, the need to secure and decode information has been a constant throughout human history.

In the next part of our journey, we’ll take a closer look at practical encoding and decoding implementations in JavaScript. We’ll explore how these concepts are used in everyday applications, providing you with the tools and knowledge to implement these techniques in your own projects.

. . .
Terabox Video Player