-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary_pattern_test_FFPUF.py
169 lines (134 loc) · 6 KB
/
binary_pattern_test_FFPUF.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 2 10:57:24 2024
@author: Mieszko Ferens
Script to run an experiment for modelling an Feed-Forward PUF that uses shifted
binary patterns as CRPs (BSP CRPs) during authentication with the server.
"""
import argparse
import pandas as pd
from pathlib import Path
import numpy as np
from pypuf.simulation import FeedForwardArbiterPUF
import pypuf.attack
class ChallengeResponseSet():
def __init__(self, n, challenges, responses):
self.challenge_length = n
self.challenges = challenges
self.responses = np.expand_dims(
np.expand_dims(responses,axis=1),axis=1)
def create_binary_code_challenges(n, N, pattern_len):
assert ((2**(pattern_len))*(n-pattern_len+1) > N), (
"Pattern length is too low for the number of patterns")
max_bits = int(np.ceil(np.log2(N)))
bits = min(max_bits, pattern_len)
lsb = np.arange(2**bits, dtype=np.uint8).reshape(-1,1)
extra = 0
if(bits % 8):
extra = 1
msb = []
for i in range(1, int(bits/8) + extra):
msb.append(lsb.copy())
for j in range(2**8):
msb[i-1][(2**(8*(i+1)))*j:(2**(8*(i+1)))*(j+1)].sort(axis=0)
lsb = np.unpackbits(lsb, axis=1)[:,-8:].copy()
for i in range(len(msb)):
msb[i] = np.unpackbits(msb[i], axis=1)[:,-8:].copy()
msb.insert(0, lsb)
patterns = 2*np.concatenate(msb[::-1], axis=1, dtype=np.int8) - 1
if(bits % 8):
patterns = np.delete(
patterns[:N], slice(8 - (bits % 8)), axis=1)
else:
patterns = patterns[:N]
if(bits < pattern_len):
patterns = np.concatenate(
(-np.ones((N, pattern_len - bits), dtype=np.int8), patterns),
axis=1, dtype=np.int8)
challenges = -np.ones(((n-pattern_len+1)*len(patterns), n), dtype=np.int8)
for i in range(len(patterns)):
for j in range(n-pattern_len+1):
challenges[i*(n-pattern_len+1)+j, j:j+pattern_len] = patterns[i]
_ , idx = np.unique(challenges, return_index=True, axis=0)
challenges = challenges[np.sort(idx)]
assert N <= len(challenges), (
"Not enough unique CRPs exist due to duplicates. " +
"Tip: You might need to increase the number of patterns")
challenges = challenges[:N]
return challenges
def main():
# Set-up logging
import logging
logging.basicConfig(level=logging.DEBUG)
# Parse arguments
parser = argparse.ArgumentParser()
parser.add_argument("--outdir", type=str, default="./Results/")
parser.add_argument("--seed", type=int, default=0, help="Random seed.")
parser.add_argument("--n-bits", type=int, default=64,
help="Challenge length in bits.")
parser.add_argument("--ff-loops", type=list, default=[(16,48)],
help="The number and positions of feed-forward " +
"loops. This parameter takes a list of tuples " +
"(e.g., [(16,48)]).")
parser.add_argument("--n-CRPs", type=int, default=400000,
help="Minimum number of CRPs to be created.")
parser.add_argument("--pattern-len", type=int, default=25,
help="Binary coded pattern length in bits.")
parser.add_argument("--train-data", type=int, default=300000,
help="Number of training data samples for the model.")
parser.add_argument("--test-data", type=int, default=10000,
help="Number of testing data samples for the model.")
args = parser.parse_args()
# Check if enough CRPs are available to train and test the model
assert args.train_data + args.test_data <= args.n_CRPs, (
"Not enough CRPs. Tip: The number of CRPs must be greater or equal " +
"to the training and testing data")
# Generate the PUF
puf = FeedForwardArbiterPUF(args.n_bits, args.ff_loops, args.seed)
# Generate the challenge
challenges = create_binary_code_challenges(
n=args.n_bits, N=args.n_CRPs, pattern_len=args.pattern_len)
# Get responses
responses = puf.eval(challenges)
# Split the data into training and testing
train = args.train_data
test = train + args.test_data
# Prepare the data for training and testing
train_crps = ChallengeResponseSet(
args.n_bits, np.array(challenges[:train], dtype=np.int8),
np.array(responses[:train], dtype=np.float64))
test_x = challenges[train:test]
test_y = np.expand_dims(0.5 - 0.5*responses[train:test], axis=1)
# Use FF-PUF optimized MLP as a predictor
network = [args.n_bits, args.n_bits/2, args.n_bits/2, args.n_bits]
model = pypuf.attack.MLPAttack2021(
train_crps, seed=args.seed, net=network, epochs=30, lr=.001,
bs=1000, early_stop=.08)
# Train the model
model.fit()
# Test the model
pred_y = model._model.eval(test_x)
pred_y = pred_y.reshape(len(pred_y), 1)
# Calculate accuracy
accuracy = np.count_nonzero(((pred_y<0.5) + test_y)-1)/len(test_y)
print("---\n" +
"Accuracy in the testing data: " + str(accuracy*100) + "%")
# Log data into csv format
data = pd.DataFrame({"seed": [args.seed],
"n_bits": [args.n_bits],
"ff_loops": [args.ff_loops],
"n_CRPs": [args.n_CRPs],
"pattern_len": [args.pattern_len],
"train_data": [args.train_data],
"test_data": [args.test_data],
"ML_algorithm": ["MLP"],
"accuracy": [accuracy]})
filepath = Path(args.outdir + "out_binary_pattern_" +
str(len(args.ff_loops)) + "FF.csv")
if(filepath.is_file()):
data.to_csv(filepath, header=False, index=False, mode='a')
else:
filepath.parent.mkdir(parents=True, exist_ok=True)
data.to_csv(filepath, header=True, index=False, mode='a')
if(__name__ == "__main__"):
main()