In: Computer Science
We like to apply text encryption and decryption as follows. In text encryption, for each letter and numeric character in the plaintext (i.e., a-z, A-Z and 0-9), it is “shifted” a certain number of places down the alphabet or numbers. For example, assuming a shifted key offset of 3 is used, ‘A’ would be substituted by ‘D’, ‘B’ would become ‘E’, and so on. Similarly, ‘0’ would become ‘3’ and so on. Note that wrap-around will be applied at the end of the alphabet or number. The decryption process works in similar approach but in a reverse order.
Encrypt the text with key offset of 15. Display the encrypted text and save the output as “encrypted_text.txt”.
(Language: PySpark Python)
def encryption(_plaintext, _offset):
answer = ""
# Exploring each character and apply shift accordingly
for i in range(len(_plaintext)):
char = _plaintext[i]
# for uppercase
if char.isupper():
answer += chr((ord(char) + _offset - 65) % 26 + 65)
# for lowercase
elif char.islower():
answer += chr((ord(char) + _offset - 97) % 26 + 97)
# for numeric
elif char.isnumeric():
answer += str((int(char) + _offset) % 10)
return answer
plaintext = input("Enter Plain Text: ")
offset = 15
result = encryption(plaintext, offset)
#uncomment to see result in console
'''
print("Plain Text : " + plaintext)
print("Shift pattern : " + str(offset))
print("Cipher Text: " + result)
'''
# write result to file
f = open("encrypted_text.txt", "w")
f.write(result)
f.close()
#uncomment to open and read the file
"""
f = open("encrypted_text.txt", "r")
print(f.read())
""""