Skip to content
Snippets Groups Projects
Commit 2858f2cb authored by Dominik Fuhrmann's avatar Dominik Fuhrmann Committed by Dominik Fuhrmann
Browse files

new try

parent 73e012ae
No related branches found
No related tags found
No related merge requests found
Showing
with 398 additions and 0 deletions
import socket
import json
import logging
from colorlog import ColoredFormatter
from Crypto.Cipher import DES, Blowfish, ARC4, PKCS1_OAEP
from Crypto.PublicKey import RSA
from Crypto.Util.Padding import pad
from Crypto.Random import get_random_bytes
import base64
# Add USER INPUT logging to system
USER_INPUT = 25
logging.addLevelName(USER_INPUT, "USER INPUT")
def user_input(msg, *args, **kwargs):
logging.log(USER_INPUT, msg, *args, **kwargs)
# Configure colored logging
log_formatter = ColoredFormatter(
"%(asctime)s - %(log_color)s%(levelname)-12s%(reset)s - %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
log_colors={
'DEBUG': 'cyan',
'INFO': 'green',
'WARNING': 'yellow',
'ERROR': 'red',
'CRITICAL': 'magenta',
'USER INPUT': 'blue',
}
)
# Show logs on terminal
console_handler = logging.StreamHandler()
console_handler.setFormatter(log_formatter)
logging.basicConfig(level=logging.DEBUG, handlers=[console_handler])
# Send data to server
def send_message_to_server(host, port, algorithm, key, key_length, encrypted_message, encrypted_key):
data = {
'algorithm': algorithm,
'key_length': key_length,
'encrypted_key': encrypted_key,
'encrypted_message': encrypted_message
}
# Start connection to server and send data
logging.info("Connecting to server...")
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
try:
s.connect((host, port))
logging.info(f"Connected to server at {host}:{port}")
s.sendall(json.dumps(data).encode())
logging.info("Data sent to server.")
except Exception as e:
logging.error(f"Connection error: {e}")
# Encrypt user message according to selected algorithm and key length
def encrypt_message(algorithm, key, message):
logging.info(f"Starting encryption with algorithm: {algorithm}")
if algorithm == 'DES':
cipher = DES.new(key, DES.MODE_CBC)
ciphertext = cipher.encrypt(pad(message.encode(), DES.block_size))
encrypted_message = base64.b64encode(cipher.iv + ciphertext).decode()
logging.info("DES encryption successful.")
return encrypted_message
elif algorithm == 'Blowfish':
cipher = Blowfish.new(key, Blowfish.MODE_CBC)
ciphertext = cipher.encrypt(pad(message.encode(), Blowfish.block_size))
encrypted_message = base64.b64encode(cipher.iv + ciphertext).decode()
logging.info("Blowfish encryption successful.")
return encrypted_message
elif algorithm == 'RC4':
cipher = ARC4.new(key)
ciphertext = cipher.encrypt(message.encode())
encrypted_message = base64.b64encode(ciphertext).decode()
logging.info("RC4 encryption successful.")
return encrypted_message
else:
logging.error("Unsupported encryption algorithm.")
raise ValueError("Unsupported encryption algorithm")
# Encrypt the key using RSA public key
def encrypt_key_with_rsa(public_key, key):
cipher = PKCS1_OAEP.new(public_key)
encrypted_key = cipher.encrypt(key)
return base64.b64encode(encrypted_key).decode()
# Load the RSA public key (for encrypting the symmetric key)
def load_public_key():
with open('public.pem', 'rb') as public_file:
public_key = RSA.import_key(public_file.read())
return public_key
def main():
host = 'localhost'
port = 12345
# Load the public RSA key (for encrypting the symmetric key)
public_key = load_public_key()
while True:
# User input for encryption settings
logging.info("Starting the client...")
print("Choose encryption algorithm:")
print("1. DES")
print("2. Blowfish")
print("3. RC4")
encryption_choice = int(input("Select: "))
if encryption_choice == 1:
algorithm = 'DES'
key = get_random_bytes(8)
key_length = 64
elif encryption_choice == 2:
algorithm = 'Blowfish'
print("Choose key length:")
print("1. 64-bit")
print("2. 128-bit")
key_length_choice = int(input("Select: "))
if key_length_choice == 1:
key = get_random_bytes(8)
key_length = 64
elif key_length_choice == 2:
key = get_random_bytes(16)
key_length = 128
else:
logging.error("Invalid choice for key length.")
print("Invalid choice!")
continue
elif encryption_choice == 3:
algorithm = 'RC4'
print("Choose key length:")
print("1. 64-bit")
print("2. 128-bit")
key_length_choice = int(input("Select: "))
if key_length_choice == 1:
key = get_random_bytes(8)
key_length = 64
elif key_length_choice == 2:
key = get_random_bytes(16)
key_length = 128
else:
logging.error("Invalid choice for key length.")
print("Invalid choice!")
continue
else:
logging.error("Invalid choice for encryption algorithm.")
print("Invalid choice!")
continue
# Get user message
message = input("Message: ")
logging.info(f"Selected: {algorithm}, Key length: {key_length}")
encrypted_message = encrypt_message(algorithm, key, message)
# Encrypt the key with the RSA public key
encrypted_key = encrypt_key_with_rsa(public_key, key)
# Send the data to the server
send_message_to_server(host, port, algorithm, key, key_length, encrypted_message, encrypted_key)
# Connection open or closed
again = input("Do you want to send another message? (y/n): ").strip().lower()
if again != 'y':
logging.info("Exiting client...")
break
if __name__ == '__main__':
main()
\ No newline at end of file
from Crypto.PublicKey import RSA
from Crypto.Random import get_random_bytes
# Generiere RSA-Schlüssel und speichere sie
def main():
private_key = RSA.generate(2048)
public_key = private_key.publickey()
# Speichern der privaten und öffentlichen Schlüssel
with open('private.pem', 'wb') as private_file:
private_file.write(private_key.export_key())
with open('public.pem', 'wb') as public_file:
public_file.write(public_key.export_key())
print("RSA-Schlüssel wurden generiert und gespeichert.")
if __name__ == '__main__':
main()
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEA3rQBwcolop8zkonx/+JsyvWtMGBxdXBNRufBnc5nIF+pKjpc
BTLTdlZx2K85Xj1Rz1waGOdf78oBECfeOb6ckeLm86JliQlKS9vkEROuxfagO5jz
2qW/BHuYIbxS0O9vdrShoC8tw+qci1pMsVu7IBLHMO+mJ3NLVCv9HL+fAYRntrpE
yx+j9HdZqmyJRriWrHCjN1/dnJoUt5dABGXTIny0BlUQJE5CrfP7oGb0fCvzO5Ms
Sy5/W9rl2O8bZLbbNXJxDoWzsM87YLL7SqUwq2SDZpy6DPO+NW9S3tqplwoI+Cqj
tId5t9FbZ/eQJXSm2bCUAl8MMToUQp9385ew3wIDAQABAoIBABUoIKqaW6zxVuLq
+/SFPDSj1kosP1sayhycU8Z8H0vyCo4acTeFNpWdbL9bFiYfyS/b3hbTlEehdyxj
vTbbJuCtH6exm9fC7C38u9PrfMUNwvcmdrQk3tq8Kx25WFzFAl/SlTA0izJ7jVen
wnVu833+irHZcn149IUQkME0axSnpBPzlz/fqhqNRh29W3ktwj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Y-----
\ No newline at end of file
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3rQBwcolop8zkonx/+Js
yvWtMGBxdXBNRufBnc5nIF+pKjpcBTLTdlZx2K85Xj1Rz1waGOdf78oBECfeOb6c
keLm86JliQlKS9vkEROuxfagO5jz2qW/BHuYIbxS0O9vdrShoC8tw+qci1pMsVu7
IBLHMO+mJ3NLVCv9HL+fAYRntrpEyx+j9HdZqmyJRriWrHCjN1/dnJoUt5dABGXT
Iny0BlUQJE5CrfP7oGb0fCvzO5MsSy5/W9rl2O8bZLbbNXJxDoWzsM87YLL7SqUw
q2SDZpy6DPO+NW9S3tqplwoI+CqjtId5t9FbZ/eQJXSm2bCUAl8MMToUQp9385ew
3wIDAQAB
-----END PUBLIC KEY-----
\ No newline at end of file
import socket
import json
import logging
from colorlog import ColoredFormatter
from Crypto.Cipher import DES, Blowfish, ARC4, PKCS1_OAEP
from Crypto.PublicKey import RSA
from Crypto.Util.Padding import unpad
import base64
# Add USER INPUT logging to system
USER_INPUT = 25
logging.addLevelName(USER_INPUT, "USER INPUT")
def user_input(msg, *args, **kwargs):
logging.log(USER_INPUT, msg, *args, **kwargs)
# Configure colored logging
log_formatter = ColoredFormatter(
"%(asctime)s - %(log_color)s%(levelname)-12s%(reset)s - %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
log_colors={
'DEBUG': 'cyan',
'INFO': 'green',
'WARNING': 'yellow',
'ERROR': 'red',
'CRITICAL': 'magenta',
'USER INPUT': 'blue',
}
)
# Show logs on terminal
console_handler = logging.StreamHandler()
console_handler.setFormatter(log_formatter)
logging.basicConfig(level=logging.DEBUG, handlers=[console_handler])
# Load RSA private key (for decrypting the symmetric key)
def load_private_key():
with open('private.pem', 'rb') as private_file:
private_key = RSA.import_key(private_file.read())
return private_key
# Load RSA public key (for encrypting the symmetric key)
def load_public_key():
with open('public.pem', 'rb') as public_file:
public_key = RSA.import_key(public_file.read())
return public_key
# Manage client connection
def handle_client(conn, addr, private_key):
logging.info(f"Handling client {addr}")
# Receive up to 1024 Bytes data from client
data = conn.recv(1024).decode()
logging.info(f"Received data from client {addr}.")
# Manage received JSON data and extract information
try:
data = json.loads(data)
algorithm = data['algorithm']
key_length = data['key_length']
encrypted_key = base64.b64decode(data['encrypted_key'])
encrypted_message = data['encrypted_message']
logging.info(f"Algorithm: {algorithm}, Key Length: {key_length}")
user_input(f"Received data from client {addr}: Algorithm: {algorithm}, Key Length: {key_length}, Encrypted message: {encrypted_message}")
except json.JSONDecodeError as e:
logging.error(f"Error decoding data: {e}")
conn.close()
return
# Decrypt the symmetric key using RSA
key = decrypt_symmetric_key(private_key, encrypted_key)
logging.info(f"Decrypted symmetric key from client {addr}.")
# Decrypt the message using the symmetric key
decrypted_message = decrypt_message(algorithm, key, encrypted_message)
logging.info(f"Decrypted message from client {addr}: {decrypted_message}")
# Respond to the client
response = {
"status": "success",
"decrypted_message": decrypted_message
}
conn.sendall(json.dumps(response).encode())
logging.info(f"Sent response to client {addr}")
# Decrypt the symmetric key using RSA private key
def decrypt_symmetric_key(private_key, encrypted_key):
cipher = PKCS1_OAEP.new(private_key)
key = cipher.decrypt(encrypted_key)
logging.info(f"Decrypted symmetric key: {key.hex()}")
return key
# Decrypt received message using the symmetric key
def decrypt_message(algorithm, key, encrypted_message):
logging.info(f"Starting decryption with algorithm: {algorithm}")
# Transform received message into binaries
encrypted_message = base64.b64decode(encrypted_message)
logging.info(f"Encrypted message: {encrypted_message.hex()}")
if algorithm == 'DES':
iv = encrypted_message[:8]
ciphertext = encrypted_message[8:]
logging.info(f"IV: {iv.hex()}, Ciphertext: {ciphertext.hex()}")
cipher = DES.new(key, DES.MODE_CBC, iv)
decrypted_message = unpad(cipher.decrypt(ciphertext), DES.block_size).decode()
logging.info("DES decryption successful.")
return decrypted_message
elif algorithm == 'Blowfish':
iv = encrypted_message[:8]
ciphertext = encrypted_message[8:]
cipher = Blowfish.new(key, Blowfish.MODE_CBC, iv)
decrypted_message = unpad(cipher.decrypt(ciphertext), Blowfish.block_size).decode()
logging.info("Blowfish decryption successful.")
return decrypted_message
elif algorithm == 'RC4':
cipher = ARC4.new(key)
decrypted_message = cipher.decrypt(encrypted_message).decode()
logging.info("RC4 decryption successful.")
return decrypted_message
else:
logging.error("Unsupported algorithm.")
raise ValueError("Unsupported decryption algorithm")
# Define server configuration
def main():
host = 'localhost'
port = 12345
# Load RSA private key
private_key = load_private_key()
# Wait for incoming connections
logging.info("Starting server...")
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
try:
s.bind((host, port))
s.listen()
logging.info(f"Listening on {host}:{port}...")
except Exception as e:
logging.error(f"Server error: {e}")
return
# Accept and close connection to client
while True:
try:
conn, addr = s.accept()
logging.info(f"Connection from {addr}")
handle_client(conn, addr, private_key)
conn.close()
except Exception as e:
logging.error(f"Error handling connection: {e}")
continue
if __name__ == '__main__':
main()
File moved
File moved
File moved
File moved
File moved
File moved
File moved
File moved
File moved
File moved
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment