From e5c59599080875c90ae7585fb3e6d0d472ff1694 Mon Sep 17 00:00:00 2001
From: Manuel Thalmann <m@nuth.ch>
Date: Tue, 19 Dec 2023 19:13:24 +0100
Subject: [PATCH] Implement TRNG attack

---
 HWBTutorials.code-workspace   | 8 ++++++++
 TRNG_attack/attack_student.py | 6 +++---
 2 files changed, 11 insertions(+), 3 deletions(-)

diff --git a/HWBTutorials.code-workspace b/HWBTutorials.code-workspace
index b1a9d48..72a2a86 100644
--- a/HWBTutorials.code-workspace
+++ b/HWBTutorials.code-workspace
@@ -177,6 +177,14 @@
                 "args": [],
                 "cwd": "${workspaceFolder:AES Intrinsic}",
                 "preLaunchTask": "Build AES Intrinsic Project"
+            },
+            {
+                "type": "python",
+                "request": "launch",
+                "name": "Run TRNG Attack",
+                "program": "${workspaceFolder:TRNG Attack}/attack_student.py",
+                "args": [],
+                "cwd": "${workspaceFolder:TRNG Attack}"
             }
         ],
         "compounds": []
diff --git a/TRNG_attack/attack_student.py b/TRNG_attack/attack_student.py
index 318aea5..1b6bb33 100644
--- a/TRNG_attack/attack_student.py
+++ b/TRNG_attack/attack_student.py
@@ -14,14 +14,14 @@ if __name__ == '__main__':
     traces = np.reshape(traces, (traces.size//tracelen, tracelen)) # reshape of matrix, each row contains the trace for one RO
 
     traces_bin = traces > 128 # conversion of waveforms to rectangles - everything below threshold is 0, otherwise 1 (they are boolean values actually)
-    rising_edges = np.logical_not(traces[:,0:-2] & traces[:,1:-1]) & traces[:,2:] # finding rising edges, each rising edge is represented by True
+    rising_edges = np.logical_not(traces_bin[:,0:-2]) & np.logical_not(traces_bin[:,1:-1]) & traces_bin[:,2:] # finding rising edges, each rising edge is represented by True
 
     cnt = np.count_nonzero(rising_edges, axis=1) # count the number of rising edges in rows
     # cnt is now a 1D vector
     cnt = cnt.reshape(TRNG_PAIR_CNT,2).min(axis=1) # Reshape of the count array into matrix, where each row contains 2 values - the number of rising edges for two ROs in a pair. Then we select the smaller value.
 
-    #cnt_sel = cnt & ?x???? # select only the two least significant bits
+    cnt_sel = cnt & 0x03 # select only the two least significant bits
 
-    #estimate = ''.join([np.binary_repr(x, width=2) for x in cnt_sel]) # binary representation of the values (the last 2 bits) and joining them into one string
+    estimate = ''.join([np.binary_repr(x, width=2) for x in cnt_sel]) # binary representation of the values (the last 2 bits) and joining them into one string
     print('{0:0>32x}'.format(int(estimate, 2)))
     print(trng_val) # from data_info, output of the RNG in FPGA