Skip to content

Commit 9d685cd

Browse files
authored
Merge pull request #86 from Sankalp75/add-encrypt-decrypt-tool
2 parents c695c56 + a36321c commit 9d685cd

4 files changed

Lines changed: 147 additions & 0 deletions

File tree

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,7 @@ python "file_name.py"
141141
- [Binary Converter](Tools/binary_converter)
142142
- [Expense Tracker](<Tools/Expense Tracker>)
143143
- [Encoding and decoding images](<Tools/Image encoding and decoding>)
144+
- [Encrypt and Decrypt Tool](Tools/encrypt_decrypt_tool)
144145

145146
<!--TOOLS_END-->
146147

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
<p align="center">
2+
<a href="https://github.com/AseanK/python-tools-and-games" target="_blank">
3+
<img src="../../images/tools_logo.png" width = "2560px" height = "200px">
4+
</a>
5+
</p>
6+
7+
# Encrypt and Decrypt Tool
8+
<!-- Tools features -->
9+
## Features
10+
1. Encrypt long text directly from the command line.
11+
2. Decrypt encrypted strings back to plain text.
12+
3. Encrypt entire files, like documents or images.
13+
4. Generates a secure, cryptographically strong key for safe AES-128 encryption (via Fernet).
14+
15+
## How to install and run
16+
1. Fork the repo by clicking the fork logo on the top right <img src="../../images/fork.png" width="300" height="60">
17+
2. Clone the repo `git clone git@github.com:AseanK/python-tools-and-games.git`
18+
3. Head to the `Tools/encrypt_decrypt_tool` folder
19+
4. Install the requirements using `pip install -r requirements.txt`
20+
5. Generate a new key by running: `python encrypt_decrypt.py keygen`
21+
6. Encrypt text: `python encrypt_decrypt.py encrypt --key YOUR_KEY --text "my secret"`
22+
7. Decrypt text: `python encrypt_decrypt.py decrypt --key YOUR_KEY --text "encrypted_string"`
23+
8. Encrypt a file: `python encrypt_decrypt.py encrypt --key YOUR_KEY --file document.pdf`
24+
9. Run `python encrypt_decrypt.py -h` to see all available commands.
Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
import argparse
2+
import sys
3+
import os
4+
5+
try:
6+
from cryptography.fernet import Fernet
7+
except ImportError:
8+
print("Please install the 'cryptography' library. Run: pip install -r requirements.txt")
9+
sys.exit(1)
10+
11+
def generate_key():
12+
key = Fernet.generate_key()
13+
print(f"Generated Key: {key.decode('utf-8')}")
14+
print("Please save this key in a secure location. You will need it to decrypt your data.")
15+
16+
def encrypt_data(data, key):
17+
f = Fernet(key)
18+
return f.encrypt(data)
19+
20+
def decrypt_data(data, key):
21+
f = Fernet(key)
22+
return f.decrypt(data)
23+
24+
def main():
25+
parser = argparse.ArgumentParser(description="Encrypt and decrypt files or text using symmetric encryption.")
26+
subparsers = parser.add_subparsers(dest="command", help="Available commands")
27+
28+
# Command: keygen
29+
parser_keygen = subparsers.add_parser("keygen", help="Generate a new encryption key")
30+
31+
# Command: encrypt
32+
parser_encrypt = subparsers.add_parser("encrypt", help="Encrypt a file or text")
33+
parser_encrypt.add_argument("-k", "--key", required=True, help="Encryption key (base64 encoded)")
34+
group_enc = parser_encrypt.add_mutually_exclusive_group(required=True)
35+
group_enc.add_argument("-t", "--text", help="Text to encrypt")
36+
group_enc.add_argument("-f", "--file", help="File to encrypt")
37+
parser_encrypt.add_argument("-o", "--out", help="Output file to save the encrypted data (optional)")
38+
39+
# Command: decrypt
40+
parser_decrypt = subparsers.add_parser("decrypt", help="Decrypt a file or text")
41+
parser_decrypt.add_argument("-k", "--key", required=True, help="Decryption key (base64 encoded)")
42+
group_dec = parser_decrypt.add_mutually_exclusive_group(required=True)
43+
group_dec.add_argument("-t", "--text", help="Text to decrypt")
44+
group_dec.add_argument("-f", "--file", help="File to decrypt")
45+
parser_decrypt.add_argument("-o", "--out", help="Output file to save the decrypted data (optional)")
46+
47+
args = parser.parse_args()
48+
49+
if args.command == "keygen":
50+
generate_key()
51+
52+
elif args.command == "encrypt":
53+
try:
54+
key = args.key.encode('utf-8')
55+
if args.text:
56+
encrypted = encrypt_data(args.text.encode('utf-8'), key)
57+
if args.out:
58+
with open(args.out, 'wb') as f:
59+
f.write(encrypted)
60+
print(f"Encrypted text saved to: {args.out}")
61+
else:
62+
print(f"Encrypted text: {encrypted.decode('utf-8')}")
63+
64+
elif args.file:
65+
if not os.path.isfile(args.file):
66+
print(f"Error: File '{args.file}' not found.")
67+
sys.exit(1)
68+
with open(args.file, 'rb') as f:
69+
data = f.read()
70+
encrypted = encrypt_data(data, key)
71+
72+
out_file = args.out if args.out else args.file + ".enc"
73+
with open(out_file, 'wb') as f:
74+
f.write(encrypted)
75+
print(f"Encrypted file saved to: {out_file}")
76+
77+
except Exception as e:
78+
print(f"Encryption failed: {e}")
79+
80+
elif args.command == "decrypt":
81+
try:
82+
key = args.key.encode('utf-8')
83+
if args.text:
84+
decrypted = decrypt_data(args.text.encode('utf-8'), key)
85+
if args.out:
86+
with open(args.out, 'wb') as f:
87+
f.write(decrypted)
88+
print(f"Decrypted text saved to: {args.out}")
89+
else:
90+
try:
91+
print(f"Decrypted text: {decrypted.decode('utf-8')}")
92+
except UnicodeDecodeError:
93+
print(f"Decrypted data is not valid UTF-8. Please save to a file using -o/--out.")
94+
95+
elif args.file:
96+
if not os.path.isfile(args.file):
97+
print(f"Error: File '{args.file}' not found.")
98+
sys.exit(1)
99+
with open(args.file, 'rb') as f:
100+
data = f.read()
101+
decrypted = decrypt_data(data, key)
102+
103+
out_file = args.out
104+
if not out_file:
105+
if args.file.endswith(".enc"):
106+
out_file = args.file[:-4]
107+
else:
108+
out_file = args.file + ".dec"
109+
110+
with open(out_file, 'wb') as f:
111+
f.write(decrypted)
112+
print(f"Decrypted file saved to: {out_file}")
113+
114+
except Exception as e:
115+
print(f"Decryption failed: {e}")
116+
print("Make sure you are using the correct key and valid encrypted data.")
117+
else:
118+
parser.print_help()
119+
120+
if __name__ == "__main__":
121+
main()
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
cryptography==42.0.5

0 commit comments

Comments
 (0)