Skip to content

Commit 8e909ef

Browse files
committed
Added Encryption and Decryption script
1 parent 5178537 commit 8e909ef

2 files changed

Lines changed: 75 additions & 0 deletions

File tree

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
<div align="center">
2+
3+
# File Encryption and Decryption
4+
5+
</div>
6+
7+
### Description:
8+
This Python script encrypts and decrypts a file using a simple Caesar cipher.
9+
10+
### How to Use:
11+
1. Run the script in a Python environment.
12+
2. Choose option '1' to encrypt a file or '2' to decrypt a file.
13+
3. Enter the path to the input file.
14+
4. Enter the path to save the output file.
15+
5. Enter the encryption/decryption key (shift value).
16+
6. The script will perform the encryption/decryption and save the result in the specified output file.
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
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

Comments
 (0)