Program:
def print_state(state): """ Print the state
matrix """ for row in state: print('
'.join(f'{hex(val)}' for val in row))
def xor_state(state1, state2):
""" XOR two 4x4 states """
return [[state1[i][j] ^ state2[i][j] for j in range(4)] for i in range(4)]
# S-box: A predefined substitution box for the SubBytes step
S_BOX = [
[0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5],
[0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76],
[0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0],
[0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA8, 0x51, 0xA3],
[0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6],
[0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2, 0xCD, 0x0C],
[0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7],
[0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73, 0x60, 0x81],
]
def sub_bytes(state):
""" Perform SubBytes step using S-box """
return [[S_BOX[i][j] for j in range(4)] for i in range(4)]
def shift_rows(state):
""" Perform ShiftRows step (cyclic shift of rows) """ return
[state[i][i:] + state[i][:i] for i in range(4)]
def add_round_key(state, round_key):
""" XOR the state with the round key """
return xor_state(state, round_key)
def key_expansion(key):
""" Generate round keys for a simplified AES (using same key for all
rounds) """
# Convert the 128-bit key (16 bytes) into a 4x4 matrix (2D array)
round_key = [[key[i * 4 + j] for j in range(4)] for i in range(4)]
return [round_key] # Only one round key for simplicity
def encrypt(plaintext, key):
""" Encrypt the plaintext with the provided key """ # Convert
the plaintext into a 4x4 matrix (2D array) state = [[plaintext[i
* 4 + j] for j in range(4)] for i in range(4)]
round_keys = key_expansion(key)
state = add_round_key(state, round_keys[0]) # Add Round Key
state = sub_bytes(state) # Substitution step (SubBytes) state =
shift_rows(state) # Shift Rows step
state = add_round_key(state, round_keys[0]) # Add Round Key again
return state
def hex_input(prompt):
""" Function to input a hexadecimal value as a list of integers """ hex_str
= input(prompt)
return [int(hex_str[i:i+2], 16) for i in range(0, len(hex_str), 2)]
# Main function to get user input and encrypt def
main():
print("Simplified AES (S-AES) Encryption")
# Take 128-bit key input (16 bytes)
key = hex_input("Enter a 128-bit key (16 bytes) in hexadecimal format: ")
# Take 128-bit plaintext input (16 bytes)
plaintext = hex_input("Enter a 128-bit plaintext (16 bytes) in hexadecimal
format: ")
# Encrypt the plaintext with the key
ciphertext = encrypt(plaintext, key)
# Print the result print("\
nEncrypted ciphertext:")
print_state(ciphertext)
if __name__ == "__main__":
main()
Output:
Simplified AES (S-AES) Encryption
Enter a 128-bit key (16 bytes) in hexadecimal format:
2b7e151628aed2a6abf7158809cf4f3c
Enter a 128-bit plaintext (16 bytes) in hexadecimal format:
3243f6a8885a308d313198a2e0370734
Encrypted ciphertext:
0x48 0x2 0x62 0x6d
0x29 0xc9 0xf9 0x96
0x62 0x8a 0xdf 0xa
0xa6 0x62 0x9b 0x9e