How to Encrypt a Word in a Text File
Lets say you have a text file, and want to encrypt the word βSecret
β.
Steps
- Generate an encryption key
- open the file
- Search through each word
- If
word
equals target
than encrypt
word with key
- Save changes to file
Project Requirements
-
cryptography
- This package provides cryptographic recipes and primitives to Python developers.
Directory Structure
encryption/
βββ app/
β βββ cryptKey.key
β βββ decrypt_me.py
β βββ encrypted_text.txt
β βββ encrypt_me.py
β βββ generate_key.py
β βββ original_text.txt
Project Files
-
cryptKey
- this is your secret key which is used for encryption
-
decrypt_me.py
- this file decrypts a word in a file
-
encrypted.txt
- This will be the output file of the encrypted text
-
encrypt_me.py
- This file encrypts a word in a file
-
generate_key.py
- This file generates the secret key (cryptKey.key
)
-
original_text.txt
- This file is the original plain text file.
original_text.txt
This file contains a word that you want to encrypt; βSecret
.β

generate_key.py
First, lets generate a secret key, and save it to file.
# generate_key.py
from cryptography.fernet import Fernet
# generate encryption key:
key = Fernet.generate_key()
# Write key to file:
with open('crypt_key.key', 'wb') as filekey:
filekey.write(key)
Your key should look something like the screen shot below:

encrypt_me.py
Now, lets open the original_text file
, and encrypt the word Secret
:
# encrypt_me.py
from cryptography.fernet import Fernet
# Open cryptKey from file:
with open('cryptKey.key', 'rb') as filekey:
crypt_key = filekey.read()
# Using the encryption key
fernet = Fernet(crypt_key)
# Open File:
with open('original_text.txt', 'r') as file:
pageFile = file.read().split(' ')
# Print original file
print(pageFile)
# Iterate through file:
for i, word in enumerate(pageFile):
if word == 'Secret':
pageFile[i] = fernet.encrypt(word.encode())
# show encrypted word
print(pageFile)
result = ' '.join([word.decode() if isinstance(word, bytes) else word for word in pageFile])
# Save results as
with open('encrypted_text.txt', 'w') as file:
file.write(result)
Screen Shot
decrypt_me.py
Now lets decrypt the word in the file:
# decrypt_me.py
from cryptography.fernet import Fernet
# Write key to file:
with open('cryptKey.key', 'rb') as filekey:
crypt_key = filekey.read()
# Using the generated key
fernet = Fernet(crypt_key)
# Open File:
with open('encrypted_text.txt','r') as file:
pageFile = file.read().split(' ')
# Show encrypted file
print(pageFile)
# Decrypt secret word
secretWord = fernet.decrypt(bytes(pageFile[-1], 'utf8')).decode()
pageFile[-1] = secretWord
# Show results
print(pageFile)
Screen Shot
Conclusion
I hope this helps answer your question on βhow to encrypt only specific text inside the fileβ. If you have any questions or concerns, please donβt hesitate to ask. If anyone catches any bugs or errors please let me know!
Best regards,