Practical Microcontroller Cryptography (Extract)

Page 1


Practical Microcontroller Cryptography

From Simple Ciphers to Secure Systems

Dogan Ibrahim & Ahmet Ibrahim

Practical Microcontroller Cryptography

From Simple Ciphers to Secure Systems

Dogan Ibrahim
Ahmet Ibrahim

● This is an Elektor Publication. Elektor is the media brand of Elektor International Media B.V. PO Box 11, NL-6114-ZG Susteren, The Netherlands Phone: +31 46 4389444

● All rights reserved. No part of this book may be reproduced in any material form, including photocopying, or storing in any medium by electronic means and whether or not transiently or incidentally to some other use of this publication, without the written permission of the copyright holder except in accordance with the provisions of the Copyright Designs and Patents Act 1988 or under the terms of a licence issued by the Copyright Licencing Agency Ltd., 90 Tottenham Court Road, London, England W1P 9HE. Applications for the copyright holder's permission to reproduce any part of the publication should be addressed to the publishers.

● Declaration

The author and publisher have made every effort to ensure the accuracy of the information contained in this book. They do not assume, or hereby disclaim, any liability to any party for any loss or damage caused by errors or omissions in this book, whether such errors or omissions result from negligence, accident, or any other cause.

● ISBN 978-3-89576-716-6 Print

ISBN 978-3-89576-717-3 eBook

● © Copyright 2026 Elektor International Media www.elektor.com

Editor: Clemens Valens

Prepress Production: D-Vision, Julian van den Berg

Printers: Ipskamp, Enschede, The Netherlands

Elektor is the world's leading source of essential technical information and electronics products for pro engineers, electronics designers, and the companies seeking to engage them. Each day, our international team develops and delivers high-quality content - via a variety of media channels (including magazines, video, digital media, and social media) in several languages - relating to electronics design and DIY electronics. www.elektormagazine.com

2.2.6

5.6.4

5.6.5

5.7

5.7.1

6.2.1

6.2.2

6.2.3 Project

6.2.4 Project

6.3

Preface

Cryptography is no longer confined to high-performance super computers or specialized hardware. In today's interconnected world, even the smallest devices, such as door locks, smart phones, smart heaters, and many other devices must be secure and they must be designed to protect the data they hold. At the heart of almost all of these systems we find microcontrollers or single board computers. A microcontroller is a fast digital processor which sits at the heart of a computer. Understanding how to apply cryptography using present day microcontrollers is very important for anyone who wishes to build secure, reliable and trustworthy systems.

This book describes and analyzes cryptography in the context of microcontrollers, from simple ciphers that illustrate the main principles to modern techniques such as the AES that enable practical and highly secure applications. By using the latest mathematical theory and the developed cryptography algorithms in real-world hardware, readers will discover not only how cryptography works, but also how to make it work in microcontroller based systems with limited processing powers and limited memories.

Why focus on Arduino, ESP32, Raspberry Pi Pico and similar platforms? These microcontrollers represent the spectrum of what is both easily accessible and practical. Arduino boards offer low-cost, simplicity and approachability, making them excellent tools for demonstrating fundamental ideas. ESP32, Raspberry Pi Pico and related devices, equipped with wireless connectivity (Pico W version) and dedicated security features, make it possible to deploy cryptography in modern IoT systems. Highly popular Raspberry Pi 5 is also used in some projects in the book where high performance cryptography is a requirement. Together, they all create a learning path that is both hands-on and directly relevant to today's embedded applications.

The aims of this book can be divided into three parts:

1. To introduce cryptographic concepts in a way that is intuitive and grounded in practical experimentation.

2. To demonstrate how these concepts can be implemented efficiently on popular microcontroller development systems and single board computers, with attention to real-world limitations and trade-offs.

3. To equip readers with the knowledge and skills necessary to design and build secure embedded systems, moving from classroom exercises or hobby projects toward professional applications.

The book is intended for a wide audience: students beginning their exploration of cryptography, hobbyists wanting to secure their personal projects, and engineers seeking a structured guide to embedded security. By the end of this book, readers will be able to move confidently from simple ciphers to the design of modern secure systems (e.g. the

AES), and gaining not only theoretical insight but also the practical experience of making cryptography work on the smallest of microcontroller development systems and single board computers.

Ahmet Ibrahim London, 2026

Chapter 1 • Foundations of Cryptography

1.1 Overview

The word cryptography derives from the Greek kryptos ("hidden") and graphein ("to write"), literally meaning "hidden writing." While secret communication likely existed long before recorded history, the earliest known examples date back over 2,500 years, emerging independently in several ancient civilizations. It is the practice and study of techniques for secure communication in the presence of adversaries.

Early cryptography was not the mathematical science in any way. It was created as a result of military necessity, political secrecy, power management, and ritual secrecy. Its purpose was very simple: to conceal information from enemies, rivals, general public, or the uninitiated.

Cryptography involves integrity, authentication, and non-repudiation of data. Explaining in more detail:

Confidentiality ensures that the sensitive information (encrypted information) is accessible only to authorized parties. Non-authorized parties may receive the information but depending on the complexity of the method used such parties may or may not decrypt the information. Confidentiality is very important especially in military and government related organizations that may need to keep the information secret from enemies. Confidentiality is also important for businesses who may want to keep certain products as trade secrets from their competitors. If the sensitive information is kept on computers, then proper software and hardware protection mechanisms must be in place to stop unauthorized access to the information over the Internet.

Integrity the integrity guarantees that the encrypted information has not been altered or tampered with and reaches the authorized recipient exactly as sent by the sender. This is important especially in military environments since the enemy may have access and alter the sensitive information. There are several software methods to ensure that information integrity is achieved when the information is stored on a computer.

Authentication verifies the identity of senders. This is to make sure that the information is received from the expected sender and not from an unknown sender. Imagine what may happen if the identity of the information received from an enemy is not identified and thought to be genuine. Luckily, there are software methods used to identify the senders of information.

Non-repudiation prevents from denying having sent a message. This could be important since with non-repudiation the sender cannot deny to be the originator of the message. Non-repudiation mainly finds importance in legal work and finance since the information sending party for example cannot deny sending a message after the message is sent.

Cryptography nowadays can be symmetric-key, asymmetric-key type, or using hash functions. All three methods have advantages and disadvantages:

Symmetric-key cryptography:

• Same secret key is used for encryption and decryption

• It is fast and efficient

• Key distribution requires a secure method

Asymmetric-key cryptography (also known as Public-key):

• Public key (shared openly) and private key (secret) are used

• Solves the key distribution problems

• Computationally much slower than symmetric encryption

• Most top-secret institutions (e.g. military) use this method (e.g. RSA, ECC, etc)

Hash functions:

• Data is mapped to a fixed-size output (hash)

• Used mainly in password storage, data integrity verification, digital signatures etc.

• Examples are SHA-256, SHA-3 etc.

In this chapter we will briefly look at mathematical foundations of cryptography and learn how the classical ciphers were used throughout the history. We will write code for the Arduino in C using its IDE, and also for the Raspberry Pi Pico using the MicroPython to encrypt and decrypt messages using these simple ciphers. It is important to mention here that almost all of the classical ciphers have been cracked nowadays using computer software.

1.2 Mathematical foundations of cryptography

One may think of cryptography as merely scrambling messages. But modern cryptography is much more than that and it relies heavily on mathematical theories. Without mathematics, cryptography would be guesswork,

Mathematics provides:

• Universality: mathematical algorithms work the same way everywhere in the world, whether on a smart phone, on a laptop, or on a supercomputer.

• Precision: mathematical algorithms are exact and can be modelled securely with no possible errors.

• Verifiability: mathematical algorithms can be tested and verified by many methods. This is very easy nowadays with the help of computers.

• Innovation: new cryptographic methods are in development all the time to make them even harder to crack. Mathematical theories are used all the time in new cryptographic innovations.

1.2.1

Number theory

Number theory provides the mathematical backbone for modern cryptography since many cryptographic algorithms depend on the properties of integer numbers, prime numbers, modular arithmetic, and finite fields.

For example, multiplying two large prime numbers is easy, but given the product, finding the original primes is very hard especially when large numbers are used, and this is the fundamental algorithm of the RSA cryptosystems.

1.2.2 Modular arithmetic

Modular arithmetic is done modulo a number which gives the remainder. For example, 5 mod 2 gives 1. Modulo arithmetic ensures that the results are within a fixed range which makes the computations efficient as well as predictable. Cryptosystems use numbers having hundreds or thousands of digits, using modular arithmetic numbers stay within manageable ranges.

Some rules of modular arithmetic are:

Addition: (a + b) mod n = [(a mod n) + (b mod n)] mod n

Multiplication: (a x b) mod n = [(a mod n) x (b mod n)] mod n

Power: ab mod n = [(a mod n)b] mod n

For example, 73 mod 5 can be calculated as: 7 mod 5 = 2. Then, 23 = 8 and 8 mod 5 = 3. As you can see the computation is easier as we didn't have to take the cube of 7.

Modular inverse is also an important concept, and it is defined as:

The modular inverse of a modulo n is a number p such that a × p = 1 (mod n)

For example, the modulo inverse of 3 mod 11 is 4 because 3 × 4 = 1 (mod 11).

1.2.3

Prime numbers

Prime numbers are integer numbers greater than 1 having no divisors other than 1 and themselves. For example, 5, 7, 13, 17 and so on. Prime numbers are fundamental to publickey cryptography (e.g. RSA). Large prime numbers appear randomly among integers, making them ideal for generating keys that are hard to guess. Modern cryptosystems require primes hundreds or even thousands of digits long. Without prime numbers, publickey cryptography would not have existed. Random large prime numbers also play an important role in cryptography. Such numbers can easily be generated using computer software and hardware.

1.2.4 Finite fields

A Finite field, also called a Galois Field is a set of numbers with a finite number of elements where you can do addition, subtraction, multiplication, and division and the results of these operations are within the field. The important point is that the results always stay inside the field. Many advanced cryptographic systems use finite fields. For example, symmetrickey cryptography where the same key is used for encryption and decryption relies on finite fields. The highly popular AES cryptography algorithm involves substitutions, permutations, mixings, all of which are performed within a finite field which ensures security as well as efficiency.

1.3 History of Cryptography

Egyptians

One of the earliest forms of encryption was found in ancient Egyptian hieroglyphs (1900 BCE). This was in the form of distorting the writings, particularly in religious and political inscriptions, to conceal scared and sensitive knowledge from the general public. This form of cryptography was not used in any type of communication.

1.3.1 Transposition Ciphers

1.3.1.1 Spartan Scytale

This was probably the first form of cryptography used mainly in military communication, around 500 BCE, based on a primitive Transposition Cipher method where the positions of the letters in the plaintext are systematically shuffled to create a ciphertext.

It consisted of a wooden rod with a known diameter around which a strip of leather was tightly wound. The message was written across the wrapped strip. When the strip was unwound, the letters appeared scrambled and meaningless. Only someone with a rod of exactly the same diameter could rewrap the strip and read the message. This method, although primitive introduced very basic form of key-based encryption, the key being the staff's diameter.

Figure 1.1 shows an example scytale where the letters are written across the strip. For example, assuming there are 4 columns of the strip, the text "this is a simple example to show how it works" becomes "tiiemtowohsmepowiriapxlshtksslaehows" when the strip is unwound.

Figure 1.1 Spartan Scytale (https://www.cachesleuth.com/scytale.html)

Nowadays there are many online tools for creating Transposition Ciphers by shuffling the positions of the letters in a sentence.

1.3.2 Substitution Ciphers

1.3.2.1 Hebrew Atbash Cipher

One of the earliest substitution ciphers was probably the Hebrew Bible. The Atbash Cipher is a simple substitution where each letter is replaced by its opposite in the alphabet (see Figure 1.2), i.e. the first with the last, the second with the second-to-last and so on. For example, letter A substituted with letter Z, B with Y and so on.

Encryption uses the formula: E(x) = (n – 1) – x

Decryption uses the formula: D(x) = (n – 1) – x where,

First letter (A) has index 0 E(x) is the encryption index x is the index of the plaintext letter

Example 1 – Arduino Uno

Assuming that we are using the English alphabet, write a program using the Arduino Uno that will implement the Hebrew Atbash cipher. Read the plaintext from the keyboard and display the encrypted text on the screen. Also, write an encrypted text and convert into plain text. Use only upper-case letters.

Note: The Hebrew Atbash algorithm is symmetric, so the same program will work to encrypt or decrypt.

Solution 1 – Arduino Uno

Figure 1.3 shows the program listing (Program: Atbash_Arduino). The user is requested to enter the text to encrypted or decrypted or to quit the progarm. Then function Atbash is called from the main program which implements the encryption/decryption algorithm. A for loop is formed inside this function which takes each letter, finds its mirror image in the alphabet and saves in variable out. The main program uses this variable to display the plaintext or the encrypted text on the screen. Space characters are also included in the output result.

Figure 1.2 Hebrew Atbash cipher

HEBREW ATBASH CIPHER - ENCRYPT / DESCRYPT TEXT

This program accepts plain text and converts into encrypted text. It also accepts encrypted text and converts into plain text

File: Atbash_Arduino ====================================================================*/

char c, encdec; String input, out; int i;

void Atbash(String text) { out = ""; for (i = 0; i < text.length(); i++) { c = text[i]; if (isUpperCase(c)) // A- Z letter { encdec = 'Z' - (c - 'A'); out = out + encdec; } else if (c == ' ') // A space { out = out + ' '; } } return; } void setup() { Serial.begin(9600); delay(1500); Serial.println("Enter text (A-Z) and press Enter to encrypt/decrypt: "); } void loop() { if (Serial.available() > 0) { input = Serial.readStringUntil('\n');

input.trim(); if(input == "Q")

{ Serial.println("End of program"); delay(1000); exit(0); } else { Atbash(input);

Serial.print("You entered: ");

Serial.println(input);

Serial.print("Output= ");

Serial.println(out);

Serial.println("Enter another text to encrypt/decrypt or Q to quit:"); } } }

Figure 1.3 Program: Atbash_arduino

Testing 1: The steps are (use the same steps for other Arduino programs):

• Start your Arduino IDE

• Select board Arduino Uno

• Write (or copy) the program in Figure 1.3

• Select Sketch → Verify/Compile to compile the program

• Click Tools → Port and select the port assigned to your Arduino Uno

• Click Sketch → Upload to upload your program to the Arduino Uno (assuming there are no compilation errors)

• Click at the top right-hand side of the screen to open the Serial Monitor

• Enter a plaintext. The encrypted text will be displayed on the screen. Since the Atbash cipher is symmetric, the program works if you enter the encrypted text to display the plaintext

• A sample output from the program is shown in Figure 1.4.

Figure 1.4 Sample program output

The program in Figure 1.3 will also compile and work on the ESP32 (ESP32 Dev Module).

Example 2 – Raspberry Pi Pico (MicroPython )

Write the same program for the Raspberry Pi Pico using the MicroPython programming language.

Solution 2 – Raspberry Pi Pico (MicroPython )

Figure 1.5 shows the program listing (Program: Atbash_Pico). The operation of the program is very similar to the Arduino program.

#==========================================================

# Raspberry Pi Pico Hebrew Atbash Cipher in microPython #

# File: Atbash_Pico

#===========================================================

def Atbash(text): out = "" for c in text: if c.isalpha() and c.isupper(): encdec = chr(ord('Z') - (ord(c) - ord('A'))) out = out + encdec elif c == ' ': out = out + ' ' return (out)

print("Enter uppercase text (A-Z), or Type Q to quit.\n")

while True: user_input = input("Enter text: ") if user_input == "Q": print("End of program") break out = Atbash(user_input)

print("Result: ", out) print()

Testing 2: The steps are (use the same steps for other Raspberry Pi Pico programs):

• Connect the Raspberry Pi Pico to your computer

• Start the Thonny program on your computer

• Write (or copy) the program in Figure 1.5

• Click File → Save As to save the program on your Raspberry Pi Pico (e.g. on RP2040 device)

• Click the Run button (green arrow at the top menu)

• Enter a plaintext. The encrypted text will be displayed on the screen. Since the Atbash cipher is symmetric, the program works if you enter the encrypted text to display the plaintext

• An sample output from the program is shown in Figure 1.6.

Figure 1.6 Sample program output

1.3.2.2 Caesar Cipher

This is another substitution cipher used by Julius Caesar (circa 50 BCE) for military use. This cipher shifts each letter in the alphabet by a fixed number (commonly 3). e.g. A becomes D, B becomes E and so on (Figure 1.7). The Caesar cipher's strength lay not in its complexity but in its novelty. To untrained interceptors, the message appeared indecipherable. However, the method is easily broken by brute-force analysis (testing all 25 possible shifts), a limitation that would drive future cryptographers to invent more sophisticated schemes.

Figure 1.5 Program: Atbash_Pico.py

Figure 1.7 Caesar cipher with 3 shifts

Encryption formula: E(x) = (x + k) mod n

Decryption formula: D(x) = (x – k) mod n

where,

x is the index (numeric position) of the plaintext letter in the alphabet n is 26 for the English alphabet k is the shift amount

Example 3 – Arduino Uno

Assuming that we are using the English alphabet (A to Z), write a program using the Arduino Uno that will implement the Caesar cipher. Read the plaintext from the keyboard and display the encrypted text on the screen. Also, write an encrypted text and convert into plain text. Use only upper-case letters only.

Solution 3 – Arduino Uno

Figure 1.8 shows the program listing (Program: Caesar_Arduino). The user is requested to decide whether to encrypt (E), decrypt (D) or quit (Q). Then in both cases the text (plain or encrypted) is read from the user, and the amount of shift is requested and read as an integer from the keyboard. The program encrypts or decrypts the entered text and then displays on the serial monitor. The program terminates when the user enters Q. Function EncryptDecrypt uses a for loop to go through each character in the entered text and shift it by the required amount. The resultant text is stored in variable trans which is displayed at the end of the program.

CAESAR CIPHER ON ARDUINO UNO

Encrypt or descrypt Caesar cipher. Enter the shift amount. ==========================================================================*/ char c; int shift, num; unsigned int i, j, alphabetlength; String line, text, encdec, trans; String letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // Alphabet

void setup()

{ Serial.begin(9600); // BAud rate Serial.println("\nCAESAR CIPHER PROGRAM"); // Heading alphabetlength = letters.length();

// // Function to encrypt/decrypt // void EncryptDecrypt() { j = text.length(); // Extract the length trans = "";

for (i = 0; i < j; i++) // for all chars { c = text[i]; // Gret a char num = letters.indexOf(c); // Find in the alphabet

if(num >= 0) // If found { if(encdec == "E") num = (num + shift) %alphabetlength; else if(encdec == "D") num = (num - shift);

if(num < 0)num = alphabetlength + num;

c = letters[num]; trans = trans + c; } else trans = trans + ' '; }

Serial.print("Text: "); // Display heading Serial.println(trans); // Display text encdec=readLine(); } // // Function to read a line from Serial Monitor // String readLine() { while (!Serial.available()); // Wait for Serial line = Serial.readStringUntil('\n'); // Read string until CR line.trim(); // Remove CR etc return line; // Return line }

Chapter 1 • Foundations of Cryptography

// // Function to read an integer from Serial Monitor // int readInt()

{ num = 0; while (!Serial.available()); // Wait for Serial num = Serial.parseInt(); // Read integer return num; // Return integer } // // Main program loop. Encrypt or Descrypt // void loop()

{

Serial.print("\nCaesar Cipher. Enter E to Encrypt, D to Decrypt, Q to exit: "); encdec = readLine(); Serial.println(encdec); if(encdec == "Q")

{ Serial.println("End of program.."); delay(1000); exit(0);

}

Serial.print("Enter text to encrypt/decrypt (A-Z): "); text = readLine(); // Get text Serial.println(text);

Serial.print("Enter shift value (1-25):"); // Ask for shift value shift = readInt(); // Get shift value Serial.println(shift);

EncryptDecrypt();                                        // Encrypy/descrypt }

Testing 3: A sample output from the program is shown in Figure 1.9.

Figure 1.8 Program: Caesar_Arduino

1.9 Sample program output

The program in Figure 1.8 will also compile and work on the ESP32 (ESP32 Dev Module).

Example 4 – Raspberry Pi Pico (MicroPython )

Write the same program for the Raspberry Pi Pico using the MicroPython programming language.

Solution 4 – Raspberry Pi Pico (MicroPython )

The program is very similar to the Arduino program, and its listing is shown in Figure 1.10 (Program: Caesar_Pico.py).

# Caesar Cipher on Raspberry Pi Pico (MicroPython) #

# Use upper case letters only. Both Encryption and Decryption #==================================================================

Letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" alphabetlength = len(Letters)

while True: mode = input("\nCaesar Cipher. Enter E to Encrypt, D to Decrypt, or Q to Quit: ") if mode == 'Q': print("End of program...") break

text = input("Enter text (A–Z): ")

shift = int(input("Enter shift value (1–25): ")) res = ""

for chars in text: if chars in Letters: numbr = Letters.find(chars) if mode == "E":

Figure

numbr = (numbr + shift)%alphabetlength elif mode == "D":

numbr = numbr - shift if numbr < 0:

numbr = alphabetlength + numbr res = res + Letters[numbr] else: res = res + chars

print("Text: %s" %(res))

Figure 1.10 Program: Caesar_Pico.py

Testing 4: A sample output from the program is shown in Figure 1.11.

Figure 1.11 Sample program output

Note that we have used the alphabet letters A to Z in the Arduino and Raspberry Pi Pico programs. You can if you wish include numbers and other characters as well in the alphabet if you wish.

1.3.2.3 ROT13 Cipher

ROT13 stands for rotate by 13 places

ROT13 stands for rotate by 13 places. It is actually a special case of the Caesar cipher where each letter of the alphabet is shifted by 13 positions. Since there are 26 letters in the English alphabet, applying ROT13 twice returns to the original text.

The programs given in Figure 1.8 and Figure 1.10 can be used for the ROT13 cipher by making the shift value equal to 13.

The formula for both encryption and decryption are the same and:

E(x) = D(x) = (x + 13) mod n

where,

n is 26 for the English alphabet x is the position of the plaintext letter in the alphabet (A is 0, B is 1 and so on)

Practical Microcontroller Cryptography

From Simple Ciphers to Secure Systems

Understanding how to apply cryptography on modern microcontrollers is essential for building secure, reliable, and trustworthy systems. This book explains cryptography in the context of embedded hardware, from classical ciphers that illustrate core principles to modern techniques such as AES for practical high-security applications. By combining mathematical theory with real-world microcontroller implementations, readers learn not only how cryptography works, but also how to implement it e ectively on systems with limited processing power and memory. The book is intended for students starting out in cryptography, hobbyists securing personal projects, and engineers looking for a structured guide to embedded security.

The book covers these key topics in applied cryptography:

> Classical ciphers on Arduino Uno and Raspberry Pi Pico, with full programs: Spartan Scytale, Hebrew Atbash, Caesar, ROT13, Alberti Disk, Vigenère, A ine, Polybius, Playfair, Beaufort, Ottoman Codebook, and One-Time Pad.

> Hacking classical ciphers using microcontrollers, with examples.

> Pseudo-random (PRNG) and true random number generation (TRNG) on microcontrollers.

> Symmetric-key cryptography with full programs: DES and AES-128/256.

> Memory and speed constraints of cryptography on microcontrollers.

> Asymmetric cryptography: public/private keys, digital signatures, key distribution and derivation (KDF), RSA, and SHA-256 implementations.

> A complete secure communication program using RSA and AES-256.

> A glossary of commonly used cryptography terms.

Prof. Dr. Dogan Ibrahim holds a BSc in Electronic Engineering, an MSc in Automatic Control Engineering, and a PhD in Digital Signal Processing. He has authored over 120 technical books and more than 200 technical articles.

Ahmet Ibrahim holds BSc (Hons) and MSc degrees in computing, software, and networking, and has worked in several industries involved in enterprise computing. He is an experienced electronics engineer and an amateur radio operator.

Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.