Implementing Text Encryption in
Python
Practical Cryptography for Medical Records
Prepared by Diana Barsasella, MKM, PhD
September 24, 2025
Diana Barsasella, MKM, PhD
[1]
Learning Objectives
• Implement simple ciphers (reverse, Caesar, ROT13, transposition) using
Python.
• Encrypt and decrypt sample texts, observing changes in data.
• Evaluate the strengths and weaknesses of each algorithm.
• Apply Python cryptography library (Fernet) for robust encryption.
• Discuss best practices for secure key management and data protection.
Diana Barsasella, MKM, PhD
[2]
Cryptography Basics Recap
Plaintext: readable data before encryption. Encrypt
Ciphertext: unreadable data produced by encryption.
Key
\Encryption: transforms plaintext into ciphertext to
ensure confidentiality. Decrypt
Decryption: restores the original plaintext from
ciphertext using a key.
Diana Barsasella, MKM, PhD
[3]
Python & Cryptography
Python is a versatile language for implementing cryptographic
concepts.
Why Python?
• Simple syntax makes algorithms easy to understand and
implement.
• Extensive standard library and third‑ party packages (e.g.,
cryptography).
• Dynamic data types ease handling of text and byte arrays.
Remember: Use well‑ tested libraries for real applications.
Rolling your own cryptography can introduce vulnerabilities.
Diana Barsasella, MKM, PhD
[4] [5]
Reverse Cipher
Description:
A reverse cipher simply reverses the order of
characters in the plaintext to create the
ciphertext. The same process is used for H E A L T H
encryption and decryption.
H T L A E H
Example:
Plaintext: "HEALTH" Encryption
Ciphertext: "HTLAEH" ↓
Decryption
Security:
Very weak; reversing again reveals the original
text.
Diana Barsasella, MKM, PhD
[6] [7]
Reverse Cipher: Python Demo
Observation:
def reverse_cipher(message): The reverse cipher simply flips
return message[::-1] characters. Applying it twice recovers
the original message.
# Test
message = "Sensitive data"
cipher = reverse_cipher(message) Security evaluation:
plain = reverse_cipher(cipher) - Easy to implement but trivial to
print(cipher) # atad evitisneS break.
print(plain) # Sensitive data - Not suitable for protecting medical
data.
Diana Barsasella, MKM, PhD
Caesar Cipher
Description:
A substitution cipher shifting each letter by a fixed
number of positions down the alphabet. A BD CE DF EG H
Example (shift = 3):
Plaintext: "ATTACK" → Ciphertext: "DWWDFN" Shift by 3
Security:
- Vulnerable to brute force because there are only
25 possible shifts.
Diana Barsasella, MKM, PhD
[8] [9] [10]
Caesar Cipher: Python Demo
def caesar_cipher(message, shift):
result = "" Observation:
for ch in message:
if [Link](): Letters shift by the specified key;
ord("a")
base = ord("A") if [Link]() else
reversing with negative shift
result += chr((ord(ch) - base + shift) % recovers plaintext.
26 + base)
else:
result += ch
return result
Security evaluation:
- Susceptible to brute force (26
# Test
plain = "Health Info" possible shifts).
cipher = caesar_cipher(plain, 3)
decoded = caesar_cipher(cipher, -3)
- Frequency analysis can reveal
print(cipher) # Khdowk Lqir patterns.
print(decoded) # Health Info
Diana Barsasella, MKM, PhD
ROT13 Cipher
Description:
A special case of the Caesar cipher where the shift
is always 13 positions. J
K
L
I
Example:
M
Plaintext: "MEDICAL" → Ciphertext: "ZRQVPNG" A
Security: B
- Just as weak as the Caesar cipher because the key
F
C
is fixed.
E
D
Shift by 13
- Easy to reverse by applying ROT13 again.
Diana Barsasella, MKM, PhD
[11] [12]
ROT13: Python Demo
import codecs
Observation:
def rot13(message): Python’s codecs module includes
return [Link](message, ROT13 encoding; applying it
"rot_13") twice returns the original.
# Test Security evaluation:
msg = "Records" - Not secure; easily reversed with
encrypted = rot13(msg) the same function.
decrypted = rot13(encrypted)
- Only shifts letters; patterns
print(encrypted) # Erpbqef
remain evident.
print(decrypted) # Records
Diana Barsasella, MKM, PhD
Transposition Cipher
Description:
Unlike substitution ciphers, transposition ciphers
Security:
rearrange the order of characters without changing
them. A common example is the columnar - More secure than simple
transposition. substitution ciphers.
- Can be improved by
Example (Key length = 4): performing multiple
transpositions.
P A T I
- Still vulnerable to frequency
Plaintext: "PATIENTDATA"
E
Arrange N 4 columns:
in T D analysis and known plaintext
attacks.
A T A
Ciphertext is read column by column.
Diana Barsasella, MKM, PhD
[13] [14]
Transposition Cipher: Python Demo
import math
def transpose_encrypt(message, key):
n_cols = key
n_rows = [Link](len(message) / n_cols)
padded = [Link](n_cols * n_rows)
Observation:
cipher = ""
for c in range(n_cols):
Characters are rearranged by
for r in range(n_rows): columns; repeated transposition
cipher += padded[r * n_cols + c]
return cipher improves security.
def transpose_decrypt(cipher, key):
n_cols = key
n_rows = [Link](len(cipher) / n_cols) Security evaluation:
padded = [Link](n_cols * n_rows)
message = ""
- Stronger than simple ciphers but
for r in range(n_rows):
for c in range(n_cols):
still breakable with analysis.
message += padded[c * n_rows + r] - Key length and number of
return [Link]()
transpositions increase strength.
# Test
msg = "PatientData"
cipher = transpose_encrypt(msg, 4)
plain = transpose_decrypt(cipher, 4)
print(cipher) # PtaaiDiatnt Diana Barsasella, MKM, PhD
print(plain) # PatientData
Comparison of Simple Ciphers
Cipher Type Key Space Security
Reverse Permutation N/A Very weak; trivial to
reverse
Caesar Substitution 25 possible shifts Weak; brute force &
frequency analysis
ROT13 Substitution 1 fixed shift Very weak; easily
reversed
Transposition Permutation Dependent on key Moderate; improved by
Key Space = number of possible keys (where applicable). length multiple passes
Diana Barsasella, MKM, PhD
Python cryptography Library
The cryptography package provides high-level recipes and low-
level primitives for secure encryption.
Fernet
• Implements authenticated symmetric encryption using AES in
CBC mode with a 128‑ bit key.
• Handles key generation, IV, padding and authentication
automatically.
• Outputs Base64‑ encoded ciphertext for easy storage.
Installation: pip install cryptography
Diana Barsasella, MKM, PhD
[15] [16]
Fernet: Python Demo
from [Link] import Fernet Observation:
Key generation and encryption
# Generate key
key = Fernet.generate_key()
handled automatically by the
cipher = Fernet(key) Fernet object.
# Encryption Security evaluation:
plain = b"Patient record"
token = [Link](plain)
- Uses AES‑ 128 with CBC and
HMAC authentication for robust
# Decryption security.
recovered = [Link](token) - Without the correct key,
print(token) # b'...'
decrypting the token raises an
print(recovered) # b'Patient record' InvalidToken exception.
Diana Barsasella, MKM, PhD
[17] [18]
Fernet: Security Considerations
• Never hard‑ code keys in your source code; store keys
securely (e.g., environment variables, key management
services).
• Rotate keys regularly and destroy old keys.
• Validate input and handle InvalidToken exceptions
gracefully.
• Use a secure random number generator to produce keys.
Diana Barsasella, MKM, PhD
Simple vs Secure Ciphers
Aspect Simple ciphers Fernet (AES)
Implementation Easy; manual code Use cryptography library
Key space Very small or none Large (128‑ bit)
Security Trivial to break Strong with authentication
Use cases Educational Real data protection
demonstration
Performance Fast, minimal overhead Moderate overhead due to
integrity check
Educational ciphers illustrate concepts but should not be used for sensitive data.
Diana Barsasella, MKM, PhD
Encryption Impact on Data
• Ciphertext often appears random and longer due to
encoding (e.g., Base64). Algorithm Plaintext
length
Ciphertex
t length
• Some algorithms preserve character set (simple ciphers), Reverse
Caesar
12
12
12
12
while others output binary data. Transposition 12 12
Fernet 12 44
(Base64)
• Encryption adds overhead; ensure storage and
transmission systems can handle increased size.
• Proper encoding (Base64) is necessary for storing binary
ciphertext in text‑ based formats.
Diana Barsasella, MKM, PhD
Relative Performance of Ciphers
Encryption Time (relative)
6 These values illustrate relative
5
complexity; actual performance
Milliseconds
4
3
2 depends on implementation and
1
0
hardware.
r
et
e
on
sa
T1
s
rn
er
iti
ae
Fe
O
os
ev
sp
R
an
Tr
Algorithm
Diana Barsasella, MKM, PhD
Key Management
• Generate keys using secure random functions
(Fernet.generate_key()).
• Store keys securely (environment variables, secret
management services).
• Rotate keys periodically to limit exposure.
• Never commit keys to version control or share them over
insecure channels.
Diana Barsasella, MKM, PhD
Evaluating Encryption Results
• Confirm that decrypting the ciphertext yields the original
plaintext exactly.
• Compare lengths and structure of plaintext vs ciphertext to
understand the algorithm’s characteristics.
• Attempt brute force or frequency analysis attacks on simple
ciphers to appreciate their weaknesses.
• Experiment by altering the ciphertext to see how errors
propagate during decryption (e.g., Fernet will raise InvalidToken).
Diana Barsasella, MKM, PhD
[19]
Data Integrity & Verification
• Use hashing (e.g., SHA‑ 256) to verify that data has not
been modified.
• Store hashes of critical fields to detect unauthorized
changes.
• Combine with digital signatures to ensure authenticity
and integrity.
• Implement audit logs and checksums for record
transmissions.
Diana Barsasella, MKM, PhD
[20]
Encrypting Medical Data
• Identify sensitive fields (patient names, diagnoses,
identifiers).
• Apply strong encryption (e.g., Fernet) to protect data
at rest and in transit.
• Ensure proper key management and access control.
• Comply with health information regulations (e.g.,
HIPAA).
Diana Barsasella, MKM, PhD
[21]
Encryption & Decryption Pipeline
Encryption
Plaintext Ciphertext Storage
Algorithm
Decryption
Plaintext Ciphertext
Algorithm
Diana Barsasella, MKM, PhD
[22]
Pitfalls & Best Practices
• Don’t reuse keys across different systems or for different
purposes.
• Beware of encoding issues—always handle byte strings
properly.
• Validate and sanitise all inputs to encryption functions.
• Use existing libraries; avoid home‑ grown algorithms
for real data.
• Keep your environment and dependencies up to date.
Diana Barsasella, MKM, PhD
Exercise 1: Implement Simple Ciphers
Task:
Write Python functions to implement reverse cipher, Caesar
cipher (with variable shift), and transposition cipher.
Steps:
• Accept input string from user.
• For Caesar cipher, prompt for shift value.
• Display encrypted text and then decrypt to verify correctness.
• Document your code and results. Diana Barsasella, MKM, PhD
Exercise 2: Secure Encryption with Fernet
Task:
Implement encryption and decryption of text using the cryptography
library’s Fernet class.
Steps:
• Install the library (pip install cryptography) if not already installed.
• Generate a key and save it securely.
• Encrypt user input and display the token.
• Decrypt the token and verify it matches the original input.
• Experiment with wrong keys to see error handling.
[23]
Diana Barsasella, MKM, PhD
Assessment Criteria
• Correctness of encryption and decryption
implementations.
• Code readability and documentation.
• Accuracy of security evaluation and discussion.
• Adherence to best practices (e.g., key handling).
• Participation in class discussion and demonstration.
Diana Barsasella, MKM, PhD
Implementation Challenges
• Integrating encryption into existing workflows or legacy
systems can be complex.
• Balancing security with performance, especially for large
datasets.
• Managing keys securely across distributed systems.
• Ensuring user awareness and avoiding human error.
Diana Barsasella, MKM, PhD
Future Directions
• Explore quantum‑ resistant algorithms as quantum
computing evolves.
• Investigate homomorphic encryption for processing
encrypted medical data.
• Adopt zero‑ trust architectures and
micro‑ segmentation in healthcare IT.
• Encourage interdisciplinary collaboration between
computer scientists and health professionals.
Diana Barsasella, MKM, PhD
Summary & Key Points
• Cryptography transforms data to protect confidentiality and integrity.
• Simple ciphers are educational but provide minimal security.
• Python’s cryptography library enables strong, authenticated encryption.
• Proper key management and hashing are vital for real‑ world
applications.
• Continue exploring advanced techniques and stay updated on security
practices.
Diana Barsasella, MKM, PhD
Class Discussion
What challenges do you foresee when implementing encryption in a
healthcare setting? How can we overcome these challenges?
Diana Barsasella, MKM, PhD
Key Takeaways
• Understand different types of encryption and their
security levels.
• Practice implementing and testing ciphers in Python.
• Recognise the importance of using strong, authenticated
encryption for sensitive data.
• Always manage keys securely and follow best practices.
Diana Barsasella, MKM, PhD
Questions?
Feel free to ask questions or discuss your experiences implementing
encryption.
Diana Barsasella, MKM, PhD
Thank You
Thank you for participating!
Let’s encrypt the future together.
Diana Barsasella, MKM, PhD