def decode(cipher, k): col_length = int(len(cipher)/3) c = np.array([], dtype=int) for i in range(len(cipher)): c = np.append(c, c2i_table(cipher[i])) c = np.reshape(c,(3,col_length)) plain = np.matmul(u.inv_key(k),c) plain = np.mod(plain, 31) p_text = str() for i in plain.flat: p_text = p_text+i2c_table(i) return p_text
def find_key(plain, cipher): p_col_len = int(len(plain)/3) c_col_len = int(len(cipher)/3) p = np.fromstring(plain, dtype=int, sep=' ') for i in range(len(plain)): p = np.append(p, c2i_table(plain[i])) p = np.reshape(p,(3,p_col_len)) c = np.fromstring(cipher, dtype=int, sep=' ') for i in range(len(cipher)): c = np.append(c, c2i_table(cipher[i])) c = np.reshape(c,(3,c_col_len)) key = np.array(np.matmul(c,u.inv_key(p)), dtype=int) key = np.mod(key, 31) return key
def get_key(cipher_text, plain_text): ''' Input: cipher_text: str plain_text: str Return: key: str ''' cipher_matrix = convert_text_2_matrix(cipher_text) plain_matrix = convert_text_2_matrix(plain_text) key_matrix = np.dot(cipher_matrix, u.inv_key(plain_matrix)) key_matrix = np.mod(key_matrix, 31) key = "" for k in key_matrix.flatten(): key += str(k) + " " return key
def decode_stage(cipher_text, decode_matrix): ''' Input: cipher_text: str decode_matrix: numpy array Return: plain_text: str ''' cipher_matrix = convert_text_2_matrix(cipher_text) plain_matrix = np.dot(decode_matrix, cipher_matrix) plain_matrix = np.mod(plain_matrix, 31) plain_text = convert_matrix_2_text(plain_matrix) return plain_text if __name__ == "__main__": cipher_text = "WPK_FJEIIXZ.OQFPM_" key = "4 9 -2 3 5 7 1 -6 11" plain_text_ans = "THI S_I S_A N_A PPL E.." encode_matrix = np.fromstring(key, dtype=int, sep=" ").reshape(3, 3) decode_matrix = u.inv_key(encode_matrix) plain_text = decode_stage(cipher_text, decode_matrix) print(plain_text)