text_plain_output_2.png application_vnd.jupyter.stderr_output_1.png
from numba import njit, prange

from tqdm.notebook import tnrange

import numpy as np

import numpy as np

import numpy as np
tracedata = np.load('/kaggle/input/sca-simple-xor-cipher-dataset/2023.04.08-14.10.20_0traces.npy')
textindata = np.load('/kaggle/input/sca-simple-xor-cipher-dataset/2023.04.08-14.10.20_0textin.npy')
textoutdata = np.load('/kaggle/input/sca-simple-xor-cipher-dataset/2023.04.08-14.10.20_0textin.npy')
key = np.load('/kaggle/input/sca-simple-xor-cipher-dataset/2023.04.08-14.10.20_0knownkey.npy', allow_pickle=True)

import numpy as np
from tqdm.notebook import tnrange
from numba import njit, prange
def mean(X):
    return np.sum(X, axis=0) / len(X)
def std_dev(X, X_bar):
    return np.sqrt(np.sum((X - X_bar) ** 2, axis=0))
def cov(X, X_bar, Y, Y_bar):
    return np.sum((X - X_bar) * (Y - Y_bar), axis=0)
def xor_internal(inputdata, key):
    return inputdata ^ key
HW = [bin(n).count('1') for n in range(0, 256)]
t_bar = np.sum(tracedata[:1000], axis=0) / len(tracedata[:1000])
o_t = np.sqrt(np.sum((tracedata[:1000] - t_bar) ** 2, axis=0))
cparefs = [0] * 16
bestguess = [0] * 16
for bnum in tnrange(0, 16):
    maxcpa = [0] * 256
    for kguess in prange(0, 256):
        hws = np.array([[HW[xor_internal(textin[bnum], kguess)] for textin in textindata]]).transpose()
        hws_bar = mean(hws)
        o_hws = std_dev(hws, hws_bar)
        correlation = cov(tracedata[:1000], t_bar, hws, hws_bar)
        cpaoutput = correlation / (o_t * o_hws)
        maxcpa[kguess] = max(abs(cpaoutput))
    bestguess[bnum] = np.argmax(maxcpa)
    cparefs[bnum] = max(maxcpa)
print('Best Key Guess: ', end='')
for b in bestguess:
    print('%02x ' % b, end='')
print('\n', cparefs)