I have written a simple caesar cipher code to take a string and a positional shift argument i.e cipher to encrypt the string. However, I have realized some of the outputs won't decrypt correctly. For example:
python .\caesar_cipher.py 'fortuna' 6771 --encrypt
outputs ☼↑↔▲↨
python .\caesar_cipher.py '☼↑↔▲↨' 6771 --decrypt
outputs \`,/UC
( \ should be ` forgive my markdown skills)
I'm fairly certain there is some issue of encoding but I couldn't pinpoint it. Instead of printing and passing it as a command-line argument between two runs, if I were to just encrypt and decrypt in the same run output seems correct.
I'm using windows and I tried to run the above example (and a couple of others) both in cmd and PowerShell to test it.
Here is my code:
import argparse
# 127 number of chars in ascii
NO_OF_CHARS = 127
def encrypt(s: str) -> str:
return ''.join([chr((ord(c)+cipher) % NO_OF_CHARS) for c in s])
def decrypt(s: str) -> str:
return ''.join([chr((ord(c)-cipher) % NO_OF_CHARS) for c in s])
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("--encrypt", help="encrypt the string", action="store_true")
group.add_argument("--decrypt", help="decrypt the string", action="store_true")
parser.add_argument("string", type=str, help="string to encrypt/decrypt")
parser.add_argument("cipher", type=int,
help="positional shift amount for caesar cipher")
args = parser.parse_args()
string = args.string
encrypt_arg = args.encrypt
decrypt_arg = args.decrypt
cipher = args.cipher
if encrypt_arg:
result = encrypt(string)
else:
result = decrypt(string)
print(result)