def encrypt(pub_key_file, input_arr, block=False): pub_key = np.load(pub_key_file) mceliece = McElieceCipher(int(pub_key['m']), int(pub_key['n']), int(pub_key['t'])) mceliece.Gp = pub_key['Gp'] if not block: if mceliece.Gp.shape[0] < len(input_arr): raise Exception( f"Input is too large for current N. Should be {mceliece.Gp.shape[0]}" ) output = mceliece.encrypt(input_arr).to_numpy() else: input_arr = padding_encode(input_arr, mceliece.Gp.shape[0]) input_arr = input_arr.reshape((-1, mceliece.Gp.shape[0])) output = np.array([]) block_count = input_arr.shape[0] for i, b in enumerate(input_arr, start=1): log.info("Processing block {} out of {}".format(i, block_count)) next_output = mceliece.encrypt(b).to_numpy() if len(next_output) < mceliece.Gp.shape[1]: log.debug(f"Padding added in block {i}") next_output = np.pad( next_output, (0, mceliece.Gp.shape[1] - len(next_output)), 'constant') output = np.concatenate((output, next_output)) return np.array(output).flatten()
def generate(m, n, t, priv_key_file, pub_key_file): mceliece = McElieceCipher(m, n, t) mceliece.generate_random_keys() np.savez_compressed(priv_key_file, m=m, n=n, t=t, S=mceliece.S, S_inv=mceliece.S_inv, G=mceliece.G, H=mceliece.H, P=mceliece.P, P_inv=mceliece.P_inv, g_poly=mceliece.g_poly, irr_poly=mceliece.irr_poly) log.info(f'Private key saved to {priv_key_file} file') np.savez_compressed(pub_key_file, m=m, n=n, t=t, Gp=mceliece.Gp) log.info(f'Public key saved to {pub_key_file} file')
def decrypt(priv_key_file, input_arr, block=False): priv_key = np.load(priv_key_file) mceliece = McElieceCipher(int(priv_key['m']), int(priv_key['n']), int(priv_key['t'])) mceliece.S = priv_key['S'] mceliece.S_inv = priv_key['S_inv'] mceliece.H = priv_key['H'] mceliece.G = priv_key['G'] mceliece.P = priv_key['P'] mceliece.P_inv = priv_key['P_inv'] mceliece.g_poly = priv_key['g_poly'] mceliece.irr_poly = priv_key['irr_poly'] if not block: if len(input_arr) < mceliece.H.shape[1]: input_arr = np.pad(input_arr, (0, mceliece.H.shape[1] - len(input_arr)), 'constant') return mceliece.decrypt(input_arr) if len(input_arr) % mceliece.H.shape[1] > 0: input_arr = np.pad( input_arr, (0, mceliece.H.shape[1] - len(input_arr) % mceliece.H.shape[1]), 'constant') input_arr = input_arr.reshape((-1, mceliece.H.shape[1])) output = np.array([]) block_count = input_arr.shape[0] for i, b in enumerate(input_arr, start=1): log.info("Processing block {} out of {}".format(i, block_count)) log.debug(f"msg:{b}") next_output = mceliece.decrypt(b) if len(next_output) < mceliece.G.shape[0]: log.debug(f"Padding added in block {i}") next_output = np.pad(next_output, (0, mceliece.H.shape[1] - len(next_output)), 'constant') output = np.concatenate((output, next_output)) return padding_decode(output.flatten(), mceliece.G.shape[0])