def parse_polynomial(px):
# Remove spaces and split the polynomial equation into individual terms
terms = px.replace(" ", "").split("+")
# Extract the degree of the polynomial
max_degree = int(terms[0].split("^")[1])
# Initialize a list to hold the coefficients of each term
coefficients = [0] * (max_degree + 1)
# Iterate through each term and extract the coefficient and degree
for term in terms:
coefficient_str, degree_str = term.split("^")
coefficient = int(coefficient_str[1:]) if coefficient_str[0] == "x" else int(coefficient_str)
degree = int(degree_str)
coefficients[degree] = coefficient
return coefficients
def lfsr_encryption(message, m, px, initial_vector):
# Convert message to binary
binary_message = ''.join(format(ord(char), '08b') for char in message)
# Generate LSFR sequence
sequence = [int(bit) for bit in initial_vector]
encrypted_sequence = []
# Parse the polynomial equation
coefficients = parse_polynomial(px)
for i in range(len(binary_message)):
xor_result = sequence[-m]
for j in range(len(coefficients)):
xor_result ^= sequence[j] * coefficients[j]
sequence.insert(0, xor_result)
encrypted_sequence.append(xor_result)
# Convert encrypted sequence to binary string
encrypted_binary = ''.join(str(bit) for bit in encrypted_sequence)
return encrypted_binary
def lfsr_decryption(encrypted_binary, m, px, initial_vector):
# Generate LSFR sequence
sequence = [int(bit) for bit in initial_vector]
decrypted_sequence = []
# Parse the polynomial equation
coefficients = parse_polynomial(px)
for i in range(len(encrypted_binary)):
xor_result = sequence[-m]
for j in range(len(coefficients)):
xor_result ^= sequence[j] * coefficients[j]
sequence.insert(0, xor_result)
decrypted_sequence.append(xor_result)
# Convert decrypted sequence to binary string
decrypted_binary = ''.join(str(bit) for bit in decrypted_sequence)
# Convert binary string to original message
decrypted_message = ""
for i in range(0, len(decrypted_binary), 8):
byte = decrypted_binary[i:i+8]
decrypted_message += chr(int(byte, 2))
return decrypted_message
def main():
message = input("Enter the message: ")
m = int(input("Enter the value of m: "))
px = input("Enter the p(x) equation: ")
initial_vector = input("Enter the initial vector (1/0): ")
encrypted_binary = lfsr_encryption(message, m, px, initial_vector)
print("Encrypted binary:", encrypted_binary)
decrypted_message = lfsr_decryption(encrypted_binary, m, px, initial_vector)
print("Decrypted message:", decrypted_message)
# Call the main function directly
main()
With this updated code, the polynomial equation for p(x) can be provided in the format you specified (e.g., x^4 + x^3 + x^2 + 1). The code will parse the equation and handle coefficients accordingly.