create a product cipher that encrypts and decrypts data in a file using python
- User
create a product cipher that encrypts and decrypts data in a file using python
- Assistant
Here is an example code that implements a product cipher to encrypt and decrypt data in a file using Python:
import random # Function to generate a random key for encryption def generate_key(length): key = '' for i in range(length): key += chr(random.randint(32, 126)) return key # Function to encrypt a file using a product cipher def encrypt_file(input_file, output_file): key1 = generate_key(5) key2 = generate_key(5) with open(input_file, 'r') as file: data = file.read() encrypted_data = '' for char in data: encrypted_data += chr(ord(char) ^ ord(key1)) + key2 with open(output_file, 'w') as file: file.write(encrypted_data) print('File encrypted successfully.') # Function to decrypt a file using a product cipher def decrypt_file(input_file, output_file): with open(input_file, 'r') as file: data = file.read() decrypted_data = '' for i in range(0, len(data), 6): decrypted_data += chr(ord(data[i]) ^ ord(data[i+1])) with open(output_file, 'w') as file: file.write(decrypted_data) print('File decrypted successfully.') # Encrypt a file encrypt_file('input.txt', 'encrypted.txt') # Decrypt a file decrypt_file('encrypted.txt', 'decrypted.txt') - User
create a product cipher in python
- Assistant
Here is an example of a product cipher implementation in Python:
import random # Function to generate a random key for encryption def generate_key(length): key = '' for i in range(length): key += chr(random.randint(32, 126)) return key # Function to encrypt data using a product cipher def encrypt(text, key1, key2): encrypted_text = '' for char in text: encrypted_text += chr((ord(char) ^ ord(key1)) * ord(key2)) return encrypted_text # Function to decrypt data using a product cipher def decrypt(encrypted_text, key1, key2): decrypted_text = '' for char in encrypted_text: decrypted_text += chr((ord(char) // ord(key2)) ^ ord(key1)) return decrypted_text # Generate random keys key1 = generate_key(1) key2 = generate_key(1) # Sample text to encrypt text = "Hello, world!" # Encrypt the text encrypted_text = encrypt(text, key1, key2) print("Encrypted text:", encrypted_text) # Decrypt the encrypted text decrypted_text = decrypt(encrypted_text, key1, key2) print("Decrypted text:", decrypted_text)