-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdes.py
More file actions
41 lines (36 loc) · 1.35 KB
/
des.py
File metadata and controls
41 lines (36 loc) · 1.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
from Crypto.Cipher import DES # from the pycryptodome library
from Crypto.Random import get_random_bytes
import base64
class Padding:
@staticmethod
def pad(data, block_size):
# Add padding to make data a multiple of block size
padding_length = block_size - (len(data) % block_size)
padding = bytes([padding_length] * padding_length)
return data + padding
@staticmethod
def unpad(data, block_size):
# Remove the padding after decryption
padding_length = data[-1]
return data[:-padding_length]
def generate_keys():
# Generate a random 8-byte (64-bit) key for DES
key = get_random_bytes(8)
# In DES, the same key is used for encryption and decryption
return key, key
def encrypt(message, key):
# Encrypt the entire message
cipher = DES.new(key, DES.MODE_ECB)
message_bytes = message.encode('utf-8')
padded_message = Padding.pad(message_bytes, 8)
encrypted = cipher.encrypt(padded_message)
return base64.b64encode(encrypted).decode('utf-8')
def decrypt(message, key):
try:
cipher = DES.new(key, DES.MODE_ECB)
encrypted_bytes = base64.b64decode(message.strip())
decrypted_padded = cipher.decrypt(encrypted_bytes)
decrypted = Padding.unpad(decrypted_padded, 8)
return decrypted.decode('utf-8')
except:
return ""