|
| 1 | +def caesar_cipher(text, shift, decrypt=False): |
| 2 | + if decrypt: |
| 3 | + shift = -shift |
| 4 | + encrypted_text = "" |
| 5 | + for char in text: |
| 6 | + if char.isalpha(): |
| 7 | + shifted = ord(char) + shift |
| 8 | + if char.islower(): |
| 9 | + if shifted > ord('z'): |
| 10 | + shifted -= 26 |
| 11 | + elif shifted < ord('a'): |
| 12 | + shifted += 26 |
| 13 | + elif char.isupper(): |
| 14 | + if shifted > ord('Z'): |
| 15 | + shifted -= 26 |
| 16 | + elif shifted < ord('A'): |
| 17 | + shifted += 26 |
| 18 | + encrypted_text += chr(shifted) |
| 19 | + else: |
| 20 | + encrypted_text += char |
| 21 | + return encrypted_text |
| 22 | + |
| 23 | + |
| 24 | +def encrypt_file(input_file, output_file, key): |
| 25 | + with open(input_file, 'r') as f: |
| 26 | + plaintext = f.read() |
| 27 | + encrypted_text = caesar_cipher(plaintext, key) |
| 28 | + with open(output_file, 'w') as f: |
| 29 | + f.write(encrypted_text) |
| 30 | + |
| 31 | + |
| 32 | +def decrypt_file(input_file, output_file, key): |
| 33 | + with open(input_file, 'r') as f: |
| 34 | + ciphertext = f.read() |
| 35 | + decrypted_text = caesar_cipher(ciphertext, key, decrypt=True) |
| 36 | + with open(output_file, 'w') as f: |
| 37 | + f.write(decrypted_text) |
| 38 | + |
| 39 | + |
| 40 | +def main(): |
| 41 | + choice = input("Enter '1' to encrypt a file or '2' to decrypt a file: ") |
| 42 | + if choice == '1': |
| 43 | + input_file = input("Enter the path to the file to encrypt: ") |
| 44 | + output_file = input("Enter the path to save the encrypted file: ") |
| 45 | + key = int(input("Enter the encryption key (shift value): ")) |
| 46 | + encrypt_file(input_file, output_file, key) |
| 47 | + print("File encrypted successfully.") |
| 48 | + elif choice == '2': |
| 49 | + input_file = input("Enter the path to the file to decrypt: ") |
| 50 | + output_file = input("Enter the path to save the decrypted file: ") |
| 51 | + key = int(input("Enter the decryption key (shift value): ")) |
| 52 | + decrypt_file(input_file, output_file, key) |
| 53 | + print("File decrypted successfully.") |
| 54 | + else: |
| 55 | + print("Invalid choice!") |
| 56 | + |
| 57 | + |
| 58 | +if __name__ == "__main__": |
| 59 | + main() |
0 commit comments