├── .gitattributes
├── .gitignore
├── AttackAesSbox.ipynb
├── AttackDesRoundXor.ipynb
├── LICENSE
├── README.md
├── Trace.py
├── aes.py
├── attackaessbox.py
├── attackdesroundxor.py
├── compareperformance.py
├── condaveraes.py
├── condaverdes.py
├── cpavisualdemo.py
├── data
├── aesinvsbox.npy
├── aessbox.npy
└── bytehammingweight.npy
├── desutils.py
├── howto
├── HOWTO.md
├── howto-notebook-des-result.png
├── howto-notebook-des-settings.png
├── howto-notebook-des.png
├── howto-notebooks.png
└── howto-script-aes-result.png
├── lracpa.py
├── results
├── attackaessbox_test.png
├── attackaessbox_test.txt
├── performance_logs.txt
└── performance_logs_bis.txt
├── traces
├── hwdes_card8_power.npz
└── swaes_atmega_power.trs
└── trs2npz.py
/.gitattributes:
--------------------------------------------------------------------------------
1 | # configuration for git-lfs
2 | traces/*.trs filter=lfs diff=lfs merge=lfs -text
3 | traces/*.npz filter=lfs diff=lfs merge=lfs -text
4 | howto/*.png filter=lfs diff=lfs merge=lfs -text
5 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | traces/*
2 | results/*
3 | misc/*
4 | .ipynb_checkpoints/*
5 | *.pyc
6 | leakage-modelling-tutorial/*
7 |
--------------------------------------------------------------------------------
/AttackAesSbox.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# CPA and LRA on the AES S-box"
8 | ]
9 | },
10 | {
11 | "cell_type": "markdown",
12 | "metadata": {},
13 | "source": [
14 | "This file is part of pysca toolbox, license is GPLv3, see https://www.gnu.org/licenses/gpl-3.0.en.html\n",
15 | "\n",
16 | "Author: Ilya Kizhvatov\n",
17 | "\n",
18 | "Version: 1.0, 2017-05-14\n",
19 | "\n",
20 | "The code should be self-explanatory (especially if you look into lracpa.py module).\n",
21 | "\n",
22 | "In the plots:\n",
23 | "- red trace is for known correct candidate\n",
24 | "- blue trace is for the winning candidate (e.g. the one with maximum peak)\n",
25 | "- grey traces are for all other candidates"
26 | ]
27 | },
28 | {
29 | "cell_type": "markdown",
30 | "metadata": {},
31 | "source": [
32 | "## 1. Configure the environment"
33 | ]
34 | },
35 | {
36 | "cell_type": "code",
37 | "execution_count": null,
38 | "metadata": {
39 | "collapsed": true
40 | },
41 | "outputs": [],
42 | "source": [
43 | "# we will be plotting figures right here and not in a separate window\n",
44 | "%matplotlib inline \n",
45 | "\n",
46 | "# generic python stuff\n",
47 | "import matplotlib\n",
48 | "import matplotlib.pyplot as plt\n",
49 | "import numpy as np # make sure you use numpy-MKL build for adequate performance!\n",
50 | "import time\n",
51 | "\n",
52 | "# configure figure size\n",
53 | "matplotlib.rcParams['figure.figsize'] = (15.0, 10.0)\n",
54 | "\n",
55 | "# local packages\n",
56 | "from aes import AES # interweb's SlowAES toolbox\n",
57 | "from lracpa import * # my LRA-CPA toolbox\n",
58 | "from condaveraes import * # incremental conditional averaging"
59 | ]
60 | },
61 | {
62 | "cell_type": "code",
63 | "execution_count": null,
64 | "metadata": {
65 | "collapsed": true
66 | },
67 | "outputs": [],
68 | "source": [
69 | "# launch sideby console for manual insight into results\n",
70 | "%qtconsole"
71 | ]
72 | },
73 | {
74 | "cell_type": "markdown",
75 | "metadata": {},
76 | "source": [
77 | "## 2. Attack settings"
78 | ]
79 | },
80 | {
81 | "cell_type": "code",
82 | "execution_count": null,
83 | "metadata": {
84 | "collapsed": true
85 | },
86 | "outputs": [],
87 | "source": [
88 | "## Traceset, number of traces, and S-box to attack\n",
89 | "tracesetFilename = \"traces/swaes_atmega_power.npz\"\n",
90 | "sampleRange = (900, 1200) # range of samples to attack, in the format (low, high)\n",
91 | "N = 100 # number of traces to attack (less or equal to the amount of traces in the file)\n",
92 | "offset = 0 # trace number to start from\n",
93 | "evolutionStep = 10 # step for intermediate reports\n",
94 | "SboxNum = 2 # S-box to attack, counting from 0\n",
95 | "\n",
96 | "## Leakage model\n",
97 | "## (these parameters correspond to function names in lracpa module)\n",
98 | "intermediateFunction = sBoxOut # for CPA and LRA\n",
99 | "leakageFunction = leakageModelHW # for CPA\n",
100 | "basisFunctionsModel = basisModelSingleBits # for LRA\n",
101 | "\n",
102 | "## Known key for ranking\n",
103 | "knownKeyStr = \"2B7E151628AED2A6ABF7158809CF4F3C\".decode(\"hex\") # the correct key\n",
104 | "encrypt = True # to avoid selective commenting in the following lines below "
105 | ]
106 | },
107 | {
108 | "cell_type": "code",
109 | "execution_count": null,
110 | "metadata": {
111 | "collapsed": true
112 | },
113 | "outputs": [],
114 | "source": [
115 | "# get the round key\n",
116 | "if encrypt: # for encryption, the first round key is as is\n",
117 | " knownKey = np.array(map(ord, knownKeyStr), dtype=\"uint8\")\n",
118 | "else: # for decryption, need to run key expansion \n",
119 | " expandedKnownKey = AES().expandKey(map(ord, knownKeyStr), 16, 16 * 11) # this returs a list\n",
120 | " knownKey = np.array(expandedKnownKey[176-16:177], dtype=\"uint8\")\n",
121 | "print \"Known roundkey : 0x%s\" % str(bytearray(knownKey)).encode(\"hex\")"
122 | ]
123 | },
124 | {
125 | "cell_type": "markdown",
126 | "metadata": {},
127 | "source": [
128 | "## 3. Load samples and data"
129 | ]
130 | },
131 | {
132 | "cell_type": "code",
133 | "execution_count": null,
134 | "metadata": {
135 | "collapsed": true
136 | },
137 | "outputs": [],
138 | "source": [
139 | "# Readout\n",
140 | "print \"Loading \" + tracesetFilename\n",
141 | "t0 = time.clock()\n",
142 | "npzfile = np.load(tracesetFilename)\n",
143 | "data = npzfile['data'][offset:offset + N,SboxNum] # selecting only the required byte\n",
144 | "traces = npzfile['traces'][offset:offset + N,sampleRange[0]:sampleRange[1]]\n",
145 | "t1 = time.clock()\n",
146 | "timeLoad = t1 - t0\n",
147 | "\n",
148 | "# Log traceset parameters\n",
149 | "(numTraces, traceLength) = traces.shape\n",
150 | "print \"Number of traces loaded :\", numTraces\n",
151 | "print \"Trace length :\", traceLength\n",
152 | "print \"Loading time : %0.2f s\" % timeLoad"
153 | ]
154 | },
155 | {
156 | "cell_type": "code",
157 | "execution_count": null,
158 | "metadata": {
159 | "collapsed": true
160 | },
161 | "outputs": [],
162 | "source": [
163 | "# dump some data\n",
164 | "data[0:10]"
165 | ]
166 | },
167 | {
168 | "cell_type": "markdown",
169 | "metadata": {},
170 | "source": [
171 | "## 4. LRA and CPA with intermediate snapshots"
172 | ]
173 | },
174 | {
175 | "cell_type": "code",
176 | "execution_count": null,
177 | "metadata": {
178 | "collapsed": true
179 | },
180 | "outputs": [],
181 | "source": [
182 | "t0 = time.clock()\n",
183 | "\n",
184 | "# initialize the incremental averager\n",
185 | "CondAver = ConditionalAveragerAesSbox(256, traceLength)\n",
186 | "\n",
187 | "# allocate arrays for storing key rank evolution\n",
188 | "numSteps = int(np.ceil(N / np.double(evolutionStep)))\n",
189 | "keyRankEvolutionCPA = np.zeros(numSteps)\n",
190 | "keyRankEvolutionLRA = np.zeros(numSteps)\n",
191 | "\n",
192 | "# the incremental loop\n",
193 | "tracesToSkip = 20 # warm-up to avoid numerical problems for small evolution step\n",
194 | "for i in range (0, tracesToSkip - 1):\n",
195 | " CondAver.addTrace(data[i], traces[i])\n",
196 | "for i in range(tracesToSkip - 1, N):\n",
197 | " CondAver.addTrace(data[i], traces[i])\n",
198 | "\n",
199 | " if (((i + 1) % evolutionStep == 0) or ((i + 1) == N)):\n",
200 | "\n",
201 | " (avdata, avtraces) = CondAver.getSnapshot()\n",
202 | " \n",
203 | " CorrTraces = cpaAES(avdata, avtraces, intermediateFunction, leakageFunction)\n",
204 | " R2, coefs = lraAES(avdata, avtraces, intermediateFunction, basisFunctionsModel)\n",
205 | "\n",
206 | " print \"---\\nResults after %d traces\" % (i + 1)\n",
207 | " print \"CPA\"\n",
208 | " CorrPeaks = np.max(np.abs(CorrTraces), axis=1) # global maximization, absolute value!\n",
209 | " CpaWinningCandidate = np.argmax(CorrPeaks)\n",
210 | " CpaWinningCandidatePeak = np.max(CorrPeaks)\n",
211 | " CpaCorrectCandidateRank = np.count_nonzero(CorrPeaks >= CorrPeaks[knownKey[SboxNum]])\n",
212 | " CpaCorrectCandidatePeak = CorrPeaks[knownKey[SboxNum]]\n",
213 | " print \"Winning candidate: 0x%02x, peak magnitude %f\" % (CpaWinningCandidate, CpaWinningCandidatePeak)\n",
214 | " print \"Correct candidate: 0x%02x, peak magnitude %f, rank %d\" % (knownKey[SboxNum], CpaCorrectCandidatePeak, CpaCorrectCandidateRank)\n",
215 | "\n",
216 | " print \"LRA\"\n",
217 | " R2Peaks = np.max(R2, axis=1) # global maximization\n",
218 | " LraWinningCandidate = np.argmax(R2Peaks)\n",
219 | " LraWinningCandidatePeak = np.max(R2Peaks)\n",
220 | " LraCorrectCandidateRank = np.count_nonzero(R2Peaks >= R2Peaks[knownKey[SboxNum]])\n",
221 | " LraCorrectCandidatePeak = R2Peaks[knownKey[SboxNum]]\n",
222 | " print \"Winning candidate: 0x%02x, peak magnitude %f\" % (LraWinningCandidate, LraWinningCandidatePeak)\n",
223 | " print \"Correct candidate: 0x%02x, peak magnitude %f, rank %d\" % (knownKey[SboxNum], LraCorrectCandidatePeak, LraCorrectCandidateRank)\n",
224 | "\n",
225 | " stepCount = int(np.floor(i / np.double(evolutionStep)))\n",
226 | " keyRankEvolutionCPA[stepCount] = CpaCorrectCandidateRank\n",
227 | " keyRankEvolutionLRA[stepCount] = LraCorrectCandidateRank\n",
228 | "\n",
229 | "t1 = time.clock()\n",
230 | "timeAll = t1 - t0\n",
231 | "\n",
232 | "print \"---\\nCumulative timing\"\n",
233 | "print \"%0.2f s\" % timeAll"
234 | ]
235 | },
236 | {
237 | "cell_type": "code",
238 | "execution_count": null,
239 | "metadata": {
240 | "collapsed": true
241 | },
242 | "outputs": [],
243 | "source": [
244 | "# save the rank evolution for later processing\n",
245 | "np.savez(\"results/AES-keyRankEvolutionSbox%02d\" % SboxNum, kreCPA=keyRankEvolutionCPA, kreLRA=keyRankEvolutionLRA, step=evolutionStep)"
246 | ]
247 | },
248 | {
249 | "cell_type": "markdown",
250 | "metadata": {},
251 | "source": [
252 | "## 5. Visualize results"
253 | ]
254 | },
255 | {
256 | "cell_type": "code",
257 | "execution_count": null,
258 | "metadata": {
259 | "collapsed": true
260 | },
261 | "outputs": [],
262 | "source": [
263 | "fig = plt.figure()\n",
264 | "\n",
265 | "# allocate grid\n",
266 | "axCPA = plt.subplot2grid((3, 2), (0, 0))\n",
267 | "axLRA = plt.subplot2grid((3, 2), (1, 0))\n",
268 | "axLRAcoefs = plt.subplot2grid((3, 2), (2, 0))\n",
269 | "axRankEvolution = plt.subplot2grid((2, 2), (0, 1), rowspan = 3)\n",
270 | "\n",
271 | "# compute trace nubmers for x axis (TODO: move into block 3)\n",
272 | "traceNumbers = np.arange(evolutionStep, N + 1, evolutionStep)\n",
273 | "\n",
274 | "# CPA\n",
275 | "axCPA.plot(CorrTraces.T, color = 'grey')\n",
276 | "if CpaWinningCandidate != knownKey[SboxNum]:\n",
277 | " axCPA.plot(CorrTraces[CpaWinningCandidate, :], 'blue')\n",
278 | "axCPA.plot(CorrTraces[knownKey[SboxNum], :], 'r')\n",
279 | "axRankEvolution.plot(traceNumbers, keyRankEvolutionCPA, color = 'green')\n",
280 | "axCPA.set_xlim([0, traceLength])\n",
281 | "\n",
282 | "# LRA\n",
283 | "axLRA.plot(R2.T, color = 'grey')\n",
284 | "if LraWinningCandidate != knownKey[SboxNum]:\n",
285 | " axLRA.plot(R2[LraWinningCandidate, :], 'blue')\n",
286 | "axLRA.plot(R2[knownKey[SboxNum], :], 'r')\n",
287 | "axRankEvolution.plot(traceNumbers, keyRankEvolutionLRA, color = 'magenta')\n",
288 | "axLRA.set_xlim([0, traceLength])\n",
289 | "\n",
290 | "# LRA coefs\n",
291 | "coefsKnownKey = np.array(coefs[knownKey[SboxNum]])\n",
292 | "axLRAcoefs.pcolormesh(coefsKnownKey[:,:-1].T, cmap=\"jet\")\n",
293 | "axLRAcoefs.set_xlim([0, traceLength])\n",
294 | "\n",
295 | "# labels\n",
296 | "fig.suptitle(\"CPA and LRA on %d traces\" % N)\n",
297 | "axCPA.set_ylabel('Correlation')\n",
298 | "axLRA.set_ylabel('R2')\n",
299 | "axLRAcoefs.set_ylabel('Basis function (bit)')\n",
300 | "axLRAcoefs.set_xlabel('Time sample')\n",
301 | "axRankEvolution.set_ylabel('Correct key candidate rank')\n",
302 | "axRankEvolution.set_xlabel('Number of traces')\n",
303 | "axRankEvolution.set_title('Correct key rank evolution (global maximisation)')\n",
304 | "\n",
305 | "# Limits and tick labels for key rand evolution plot\n",
306 | "axRankEvolution.set_xlim([traceNumbers[int(np.ceil(tracesToSkip / np.double(evolutionStep))) - 1], N])\n",
307 | "axRankEvolution.set_ylim([0, 256])\n",
308 | "axRankEvolution.grid(b=True, which='both', color='0.65',linestyle='-')\n",
309 | "#axRankEvolution.ticklabel_format(style='sci', axis='x', scilimits=(0,0), useOffset=True)\n",
310 | "\n",
311 | "# Legend for rank evolution plot\n",
312 | "axRankEvolution.legend(['CPA', 'LRA'], loc='upper right')\n",
313 | "\n",
314 | "plt.show()"
315 | ]
316 | }
317 | ],
318 | "metadata": {
319 | "kernelspec": {
320 | "display_name": "Python 2",
321 | "language": "python",
322 | "name": "python2"
323 | },
324 | "language_info": {
325 | "codemirror_mode": {
326 | "name": "ipython",
327 | "version": 2
328 | },
329 | "file_extension": ".py",
330 | "mimetype": "text/x-python",
331 | "name": "python",
332 | "nbconvert_exporter": "python",
333 | "pygments_lexer": "ipython2",
334 | "version": "2.7.13"
335 | }
336 | },
337 | "nbformat": 4,
338 | "nbformat_minor": 1
339 | }
340 |
--------------------------------------------------------------------------------
/AttackDesRoundXor.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# LRA and CPA on DES round XOR (per S-box)\n",
8 | "\n",
9 | "This file is part of pysca toolbox, license is GPLv3, see https://www.gnu.org/licenses/gpl-3.0.en.html\n",
10 | "\n",
11 | "Author: Ilya Kizhvatov\n",
12 | "\n",
13 | "Version: 1.0, 2017-05-14\n",
14 | "\n",
15 | "The code should be self-explanatory.\n",
16 | "\n",
17 | "The attack uses conditional averaging for performance. Note how for DES this requires splitting the intermediate variable computation into two parts: part for averaging and part for the final intermediate value compuation."
18 | ]
19 | },
20 | {
21 | "cell_type": "markdown",
22 | "metadata": {},
23 | "source": [
24 | "## 1. Configure the environment"
25 | ]
26 | },
27 | {
28 | "cell_type": "code",
29 | "execution_count": null,
30 | "metadata": {
31 | "collapsed": true
32 | },
33 | "outputs": [],
34 | "source": [
35 | "# we will be plotting figures right here and not in a separate window\n",
36 | "%matplotlib inline \n",
37 | "\n",
38 | "# generic python stuff\n",
39 | "import matplotlib\n",
40 | "import matplotlib.pyplot as plt\n",
41 | "import numpy as np # make sure you use numpy-MKL build for adequate performance!\n",
42 | "import struct\n",
43 | "import time\n",
44 | "\n",
45 | "# configure figure size\n",
46 | "matplotlib.rcParams['figure.figsize'] = (15.0, 10.0)\n",
47 | "\n",
48 | "# local packages\n",
49 | "from desutils import * # my DES utilities\n",
50 | "from lracpa import * # my LRA-CPA toolbox\n",
51 | "from condaverdes import * # incremental conditional averaging"
52 | ]
53 | },
54 | {
55 | "cell_type": "code",
56 | "execution_count": null,
57 | "metadata": {
58 | "collapsed": true
59 | },
60 | "outputs": [],
61 | "source": [
62 | "# lauch sideby console for manual insight into results\n",
63 | "%qtconsole"
64 | ]
65 | },
66 | {
67 | "cell_type": "markdown",
68 | "metadata": {},
69 | "source": [
70 | "## 2. Attack settings"
71 | ]
72 | },
73 | {
74 | "cell_type": "code",
75 | "execution_count": null,
76 | "metadata": {
77 | "collapsed": true
78 | },
79 | "outputs": [],
80 | "source": [
81 | "## Traceset, number of traces, and S-box to attack\n",
82 | "tracesetFilename = \"traces/hwdes_card8_power.npz\"\n",
83 | "sampleRange = (0, 50) # range of smaples to attack\n",
84 | "N = 10000 # number of traces to attack (not more that nthe file has)\n",
85 | "offset = 0 # trace number to start from\n",
86 | "evolutionStep = 500 # step for intermediate reports\n",
87 | "SboxNum = 1 # S-box to attack, counting from 0\n",
88 | "\n",
89 | "## Leakage model\n",
90 | "## (these parameters correspond to function names in lracpa module)\n",
91 | "averagingFunction = roundXOR_valueForAveraging # for CPA and LRA\n",
92 | "intermediateFunction = roundXOR_targetVariable # for CPA and LRA\n",
93 | "leakageFunction = leakageModelHW # for CPA\n",
94 | "basisFunctionsModel = basisModelSingleBits # for LRA\n",
95 | "\n",
96 | "## Known key for ranking\n",
97 | "knownKey = 0x8A7400A03230DA28 # the correct key\n",
98 | "encrypt = True"
99 | ]
100 | },
101 | {
102 | "cell_type": "code",
103 | "execution_count": null,
104 | "metadata": {
105 | "collapsed": true
106 | },
107 | "outputs": [],
108 | "source": [
109 | "# get the known round key\n",
110 | "roundKeyNum = 1\n",
111 | "if (encrypt == False):\n",
112 | " roundKeyNum = 16\n",
113 | "roundKey = computeRoundKeys(knownKey, roundKeyNum)[roundKeyNum-1]\n",
114 | "knownKeyChunk = roundKeyChunk(roundKey, SboxNum)\n",
115 | "print \"Known round key: \" + format(roundKey, '#014x'),\n",
116 | "print '[',\n",
117 | "for i in range(8):\n",
118 | " print format(roundKeyChunk(roundKey, i), '#04x'),\n",
119 | "print ']'"
120 | ]
121 | },
122 | {
123 | "cell_type": "markdown",
124 | "metadata": {},
125 | "source": [
126 | "## 3. Load samples and data"
127 | ]
128 | },
129 | {
130 | "cell_type": "code",
131 | "execution_count": null,
132 | "metadata": {
133 | "collapsed": true
134 | },
135 | "outputs": [],
136 | "source": [
137 | "# Readout\n",
138 | "print \"Loading \" + tracesetFilename\n",
139 | "t0 = time.clock()\n",
140 | "npzfile = np.load(tracesetFilename)\n",
141 | "data = npzfile['data'][0:N]\n",
142 | "traces = npzfile['traces'][0:N,sampleRange[0]:sampleRange[1]]\n",
143 | "t1 = time.clock()\n",
144 | "timeLoad = t1 - t0\n",
145 | "\n",
146 | "# convert data byte arrays to integers (more convenient for DES)\n",
147 | "datanew = []\n",
148 | "for i in range(0, len(data)):\n",
149 | " datanew.append(struct.unpack('!Q', data[i][0:8].tostring())[0])\n",
150 | "data = datanew # old data will be garbage-collected\n",
151 | "\n",
152 | "# Log traceset parameters\n",
153 | "(numTraces, traceLength) = traces.shape\n",
154 | "print \"Number of traces loaded :\", numTraces\n",
155 | "print \"Trace length :\", traceLength\n",
156 | "print \"Loading time : %0.2f s\" % timeLoad"
157 | ]
158 | },
159 | {
160 | "cell_type": "markdown",
161 | "metadata": {},
162 | "source": [
163 | "## 4. Attack with a fixed number of traces"
164 | ]
165 | },
166 | {
167 | "cell_type": "code",
168 | "execution_count": null,
169 | "metadata": {
170 | "collapsed": true
171 | },
172 | "outputs": [],
173 | "source": [
174 | "# perform conditional averaging\n",
175 | "CondAver = ConditionalAveragerDes(1024, traceLength)\n",
176 | "for i in range(N):\n",
177 | " CondAver.addTrace(data[i], traces[i], averagingFunction, SboxNum)\n",
178 | "(avdata, avtraces) = CondAver.getSnapshot()\n",
179 | "\n",
180 | "# CPA\n",
181 | "CorrTraces = cpaDES(avdata, avtraces, intermediateFunction, SboxNum, leakageFunction)\n",
182 | "\n",
183 | "# LRA\n",
184 | "R2, coefs = lraDES(avdata, avtraces, intermediateFunction, SboxNum, basisFunctionsModel)\n",
185 | "\n",
186 | "### visualize results\n",
187 | "\n",
188 | "fig = plt.figure()\n",
189 | "\n",
190 | "# allocate grid\n",
191 | "axCPA = plt.subplot2grid((3, 1), (0, 0))\n",
192 | "axLRA = plt.subplot2grid((3, 1), (1, 0))\n",
193 | "axLRAcoefs = plt.subplot2grid((3, 1), (2, 0))\n",
194 | "\n",
195 | "# CPA\n",
196 | "axCPA.plot(CorrTraces.T, color = 'grey')\n",
197 | "axCPA.plot(CorrTraces[knownKeyChunk, :], 'r')\n",
198 | "axCPA.set_xlim([0, traceLength])\n",
199 | "\n",
200 | "# LRA\n",
201 | "axLRA.plot(R2.T, color = 'grey')\n",
202 | "axLRA.plot(R2[knownKeyChunk, :], 'r')\n",
203 | "axLRA.set_xlim([0, traceLength])\n",
204 | "\n",
205 | "# LRA coefs\n",
206 | "coefsKnownKey = np.array(coefs[knownKeyChunk])\n",
207 | "axLRAcoefs.pcolormesh(coefsKnownKey[:,:-1].T, cmap=\"jet\")\n",
208 | "axLRAcoefs.set_xlim([0, traceLength])\n",
209 | "\n",
210 | "# labels\n",
211 | "fig.suptitle(\"CPA and LRA on %d traces\" % N)\n",
212 | "axCPA.set_ylabel('Correlation')\n",
213 | "axLRA.set_ylabel('R2')\n",
214 | "axLRAcoefs.set_ylabel('Basis function (bit)')\n",
215 | "axLRAcoefs.set_xlabel('Time sample')\n",
216 | "\n",
217 | "plt.show()"
218 | ]
219 | },
220 | {
221 | "cell_type": "markdown",
222 | "metadata": {},
223 | "source": [
224 | "## 5. Attack with evolving number of traces"
225 | ]
226 | },
227 | {
228 | "cell_type": "code",
229 | "execution_count": null,
230 | "metadata": {
231 | "collapsed": true
232 | },
233 | "outputs": [],
234 | "source": [
235 | "t0 = time.clock()\n",
236 | "\n",
237 | "# initialize the incremental averager\n",
238 | "CondAver = ConditionalAveragerDes(1024, traceLength)\n",
239 | "\n",
240 | "# allocate arrays for storing key rank evolution\n",
241 | "numSteps = int(np.ceil(N / np.double(evolutionStep)))\n",
242 | "keyRankEvolutionCPA = np.zeros(numSteps)\n",
243 | "keyRankEvolutionLRA = np.zeros(numSteps)\n",
244 | "\n",
245 | "# the incremental loop\n",
246 | "tracesToSkip = 20 # warm-up to avoid numerical problems for small evolution step\n",
247 | "for i in range (0, tracesToSkip - 1):\n",
248 | " CondAver.addTrace(data[i], traces[i], averagingFunction, SboxNum)\n",
249 | "for i in range(tracesToSkip - 1, N):\n",
250 | " CondAver.addTrace(data[i], traces[i], averagingFunction, SboxNum)\n",
251 | "\n",
252 | " if (((i + 1) % evolutionStep == 0) or ((i + 1) == N)):\n",
253 | "\n",
254 | " (avdata, avtraces) = CondAver.getSnapshot()\n",
255 | " \n",
256 | " CorrTraces = cpaDES(avdata, avtraces, intermediateFunction, SboxNum, leakageFunction)\n",
257 | " R2, coefs = lraDES(avdata, avtraces, intermediateFunction, SboxNum, basisFunctionsModel)\n",
258 | " #R2 = normalizeR2Traces(R2)\n",
259 | "\n",
260 | " print \"---\\nResults after %d traces\" % (i + 1)\n",
261 | " print \"CPA\"\n",
262 | " CorrPeaks = np.max(np.abs(CorrTraces), axis=1) # global maximization, absolute value!\n",
263 | " CpaWinningCandidate = np.argmax(CorrPeaks)\n",
264 | " CpaWinningCandidatePeak = np.max(CorrPeaks)\n",
265 | " CpaCorrectCandidateRank = np.count_nonzero(CorrPeaks >= CorrPeaks[knownKeyChunk])\n",
266 | " CpaCorrectCandidatePeak = CorrPeaks[knownKeyChunk]\n",
267 | " print \"Winning candidate: 0x%02x, peak magnitude %f\" % (CpaWinningCandidate, CpaWinningCandidatePeak)\n",
268 | " print \"Correct candidate: 0x%02x, peak magnitude %f, rank %d\" % (knownKeyChunk, CpaCorrectCandidatePeak, CpaCorrectCandidateRank)\n",
269 | "\n",
270 | " print \"LRA\"\n",
271 | " R2Peaks = np.max(R2, axis=1) # global maximization\n",
272 | " LraWinningCandidate = np.argmax(R2Peaks)\n",
273 | " LraWinningCandidatePeak = np.max(R2Peaks)\n",
274 | " LraCorrectCandidateRank = np.count_nonzero(R2Peaks >= R2Peaks[knownKeyChunk])\n",
275 | " LraCorrectCandidatePeak = R2Peaks[knownKeyChunk]\n",
276 | " print \"Winning candidate: 0x%02x, peak magnitude %f\" % (LraWinningCandidate, LraWinningCandidatePeak)\n",
277 | " print \"Correct candidate: 0x%02x, peak magnitude %f, rank %d\" % (knownKeyChunk, LraCorrectCandidatePeak, LraCorrectCandidateRank)\n",
278 | "\n",
279 | " stepCount = int(np.floor(i / np.double(evolutionStep)))\n",
280 | " keyRankEvolutionCPA[stepCount] = CpaCorrectCandidateRank\n",
281 | " keyRankEvolutionLRA[stepCount] = LraCorrectCandidateRank\n",
282 | "\n",
283 | "t1 = time.clock()\n",
284 | "timeAll = t1 - t0\n",
285 | "\n",
286 | "print \"---\\nCumulative timing\"\n",
287 | "print \"%0.2f s\" % timeAll"
288 | ]
289 | },
290 | {
291 | "cell_type": "code",
292 | "execution_count": null,
293 | "metadata": {
294 | "collapsed": true
295 | },
296 | "outputs": [],
297 | "source": [
298 | "# save the rank evolution for later processing\n",
299 | "np.savez(\"results/keyRankEvolutionSbox%02d\" % SboxNum, kreCPA=keyRankEvolutionCPA, kreLRA=keyRankEvolutionLRA, step=evolutionStep)"
300 | ]
301 | },
302 | {
303 | "cell_type": "markdown",
304 | "metadata": {},
305 | "source": [
306 | "## 7. Visualize results"
307 | ]
308 | },
309 | {
310 | "cell_type": "code",
311 | "execution_count": null,
312 | "metadata": {
313 | "collapsed": true
314 | },
315 | "outputs": [],
316 | "source": [
317 | "fig = plt.figure()\n",
318 | "\n",
319 | "# allocate grid\n",
320 | "axCPA = plt.subplot2grid((3, 2), (0, 0))\n",
321 | "axLRA = plt.subplot2grid((3, 2), (1, 0))\n",
322 | "axLRAcoefs = plt.subplot2grid((3, 2), (2, 0))\n",
323 | "axRankEvolution = plt.subplot2grid((2, 2), (0, 1), rowspan = 3)\n",
324 | "\n",
325 | "# compute trace nubmers for x axis (TODO: move into block 3)\n",
326 | "traceNumbers = np.arange(evolutionStep, N + 1, evolutionStep)\n",
327 | "\n",
328 | "# CPA\n",
329 | "axCPA.plot(CorrTraces.T, color = 'grey')\n",
330 | "if CpaWinningCandidate != knownKeyChunk:\n",
331 | " axCPA.plot(CorrTraces[CpaWinningCandidate, :], 'blue')\n",
332 | "axCPA.plot(CorrTraces[knownKeyChunk, :], 'r')\n",
333 | "axRankEvolution.plot(traceNumbers, keyRankEvolutionCPA, color = 'green')\n",
334 | "axCPA.set_xlim([0, traceLength])\n",
335 | "\n",
336 | "# LRA\n",
337 | "axLRA.plot(R2.T, color = 'grey')\n",
338 | "if LraWinningCandidate != knownKeyChunk:\n",
339 | " axLRA.plot(R2[LraWinningCandidate, :], 'blue')\n",
340 | "axLRA.plot(R2[knownKeyChunk, :], 'r')\n",
341 | "axRankEvolution.plot(traceNumbers, keyRankEvolutionLRA, color = 'magenta')\n",
342 | "axLRA.set_xlim([0, traceLength])\n",
343 | "\n",
344 | "# LRA coefs\n",
345 | "coefsKnownKey = np.array(coefs[knownKeyChunk])\n",
346 | "axLRAcoefs.pcolormesh(coefsKnownKey[:,:-1].T, cmap=\"jet\")\n",
347 | "axLRAcoefs.set_xlim([0, traceLength])\n",
348 | "\n",
349 | "# labels\n",
350 | "fig.suptitle(\"CPA and LRA on %d traces\" % N)\n",
351 | "axCPA.set_ylabel('Correlation')\n",
352 | "axLRA.set_ylabel('R2')\n",
353 | "axLRAcoefs.set_ylabel('Basis function (bit)')\n",
354 | "axLRAcoefs.set_xlabel('Time sample')\n",
355 | "axRankEvolution.set_ylabel('Correct key candidate rank')\n",
356 | "axRankEvolution.set_xlabel('Number of traces')\n",
357 | "axRankEvolution.set_title('Correct key rank evolution (global maximisation)')\n",
358 | "\n",
359 | "# Limits and tick labels for key rand evolution plot\n",
360 | "axRankEvolution.set_xlim([traceNumbers[int(np.ceil(tracesToSkip / np.double(evolutionStep))) - 1], N])\n",
361 | "axRankEvolution.set_ylim([0, 64])\n",
362 | "axRankEvolution.grid(b=True, which='both', color='0.65',linestyle='-')\n",
363 | "#axRankEvolution.ticklabel_format(style='sci', axis='x', scilimits=(0,0), useOffset=True)\n",
364 | "\n",
365 | "# Legend for rank evolution plot\n",
366 | "axRankEvolution.legend(['CPA', 'LRA'], loc='upper right')\n",
367 | "\n",
368 | "plt.show()"
369 | ]
370 | }
371 | ],
372 | "metadata": {
373 | "kernelspec": {
374 | "display_name": "Python 2",
375 | "language": "python",
376 | "name": "python2"
377 | },
378 | "language_info": {
379 | "codemirror_mode": {
380 | "name": "ipython",
381 | "version": 2
382 | },
383 | "file_extension": ".py",
384 | "mimetype": "text/x-python",
385 | "name": "python",
386 | "nbconvert_exporter": "python",
387 | "pygments_lexer": "ipython2",
388 | "version": "2.7.13"
389 | }
390 | },
391 | "nbformat": 4,
392 | "nbformat_minor": 1
393 | }
394 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | {project} Copyright (C) {year} {fullname}
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Pysca toolbox
2 |
3 | This toolbox was started in 2014 to experiment with efficient differential power analysis (DPA) techniques from the paper "Behind the Scene of Side Channel Attacks" by Victor Lomné, Emmanuel Prouff, and Thomas Roche (https://eprint.iacr.org/2013/794).
4 |
5 | To clone this repo with the included example traces you will need [Git-LFS](https://git-lfs.github.com). Without Git-LFS, only pointers to traces will be cloned.
6 |
7 | ## Why
8 | The toolbox was designed with the following in mind:
9 | * state-of-the-art DPA techniques
10 | * performance
11 | * visualization of metrics for security evaluations purpose (and not just attack)
12 | * simplicity and flexibility through use of a language suitable for scientific computing
13 |
14 | In terms of these points, Pysca (still) outperforms some commercial tooling. Pysca is nowadays mostly superseded by https://github.com/Riscure/Jlsca.
15 |
16 | ## What
17 | Pysca implements:
18 | * non-profiled linear-regression analysis (LRA) with configurable basis functions
19 | * classical correlation power analysis (CPA)
20 | * significant speed-up of the above by conditional averaging
21 | * targets: AES (S-box out) and DES (round in XOR round out, round out, S-box out)
22 | * visualization of results
23 |
24 | ## How
25 |
26 | For usage basics refer to the [HOWTO](howto/HOWTO.md).
27 |
28 | For a deeper dive into [leakage modelling using linear regression](https://github.com/ikizhvatov/leakage-modelling-tutorial), clone the tutorial into the subfolder:
29 |
30 | git clone https://github.com/ikizhvatov/leakage-modelling-tutorial.git
31 |
32 | ## Details
33 | Pysca works on traces stored in npz (numpy zipped) format. Example tracesets are included in the repo using git-lfs. The conversion script from Riscure Inspector trs format is included. The trs reader was originally implemented by Erik van den Brink.
34 |
35 | Under the hood, the most interesting technical tricks in pysca are perhaps:
36 | * fast computation of correlation (see https://github.com/ikizhvatov/efficient-columnwise-correlation for a dedicated study)
37 | * conditional averaging implementation for DES (because of all the bit permutations, it requires splitting the leakage function into two stages)
38 |
39 | Author: Ilya Kizhvatov
40 | Version: 1.0, 2017-05-14
41 |
--------------------------------------------------------------------------------
/Trace.py:
--------------------------------------------------------------------------------
1 | '''
2 | This file is part of pysca toolbox, license is GPLv3, see https://www.gnu.org/licenses/gpl-3.0.en.html
3 | Authors: Erik van den Brink, Ilya Kizhvatov, Pol van Aubel
4 | Version: 1.0, 2017-05-14
5 |
6 | Open an INS TraceSet
7 |
8 | Versions of this file:
9 |
10 | v0.6 28-05-2017 (Pol)
11 | * performance greatly improved by using np.fromfile
12 |
13 | v0.55 05-12-2014 (yet unidentified author at Riscure)
14 | * Added writing trace fileSize
15 |
16 | v0.5 12-11-2013 (Ilya)
17 | * Fixed the format typo; a bit of cleanup
18 |
19 | v0.4 12-11-2013 (Ilya)
20 | * Fixed the sample reading bug in general
21 |
22 | v0.3 11-09-2013 (Erik)
23 | * Fixed sample reading bug in getTrace() as pointed out by Ilya
24 |
25 | v0.2 5-3-2013 (Erik)
26 | * Fixed __iter__ method and removed the no longer necesarry getTraces() method
27 | * Moved header constants inside TraceSet class
28 | * Removed debug code
29 | '''
30 |
31 | from __future__ import print_function
32 |
33 | import sys
34 | import struct
35 | import numpy as np
36 |
37 | class Trace():
38 | def __init__(self, title, data, samples):
39 | self._title = title
40 | self._data = data
41 | self._samples = samples
42 |
43 | class TraceSet():
44 | #header definitions
45 | NumberOfTraces = 0x41
46 | NumberOfSamplesPerTrace = 0x42
47 | SampleCoding = 0x43
48 | DataSpace = 0x44
49 | TitleSpace = 0x45
50 | GlobalTitle = 0x46
51 | Description = 0x47
52 | XLabel = 0x49
53 | YLabel = 0x4a
54 | XScale = 0x4b
55 | YScale = 0x4c
56 | ScopeRange = 0x55
57 | ChannelCoupling = 0x56
58 | Offset = 0x57
59 | ScopeID = 0x59
60 | TraceBlock = 0x5F #Trace block, a flat memory space
61 |
62 | # enum for sampe coding
63 | CodingByte = 0x01
64 | CodingShort = 0x02
65 | CodingInt = 0x04
66 | CodingFloat = 0x14
67 |
68 | def __init__(self):
69 | self._handle = None
70 | self._traceBlockOffset = None
71 | self._numberOfTraces = None
72 | self._numberOfSamplesPerTrace = None
73 | self._sampleCoding = None
74 | self._npSampleCoding = None
75 | self._sampleCodingByteSize = None
76 | self._titleSpace = 0
77 | self._dataSpace = 0
78 | self._yscale = 1
79 | self._fileName = None
80 |
81 | #properties
82 | self._sampleSpace = None
83 | self._traceSpace = None
84 | self._traceBlockSpace = 0
85 |
86 | self._iterIndex = 0
87 |
88 | def __iter__(self):
89 | for i in range(self._numberOfTraces):
90 | yield self.getTrace(i)
91 |
92 | def _readUINT8(self):
93 | return struct.unpack("B",self._handle.read(1))[0];
94 |
95 | def _readUINT16(self):
96 | return struct.unpack("H",self._handle.read(2))[0];
97 |
98 | def _readUINT32(self):
99 | return struct.unpack("I",self._handle.read(4))[0];
100 |
101 | def _readFloat32(self):
102 | return struct.unpack("f",self._handle.read(4))[0];
103 |
104 | def _writeUINT8(self, val):
105 | #print("UINT8: %02x"%(val&0xFF))
106 | return self._handle.write(struct.pack("B",(val&0xFF)));
107 |
108 | def _writeUINT16(self, val):
109 | #print("UINT16: %04x"%(val&0xFFFF))
110 | return self._handle.write(struct.pack("H",(val&0xFFFF)));
111 |
112 | def _writeUINT32(self, val):
113 | #print("UINT32: %08x"%(val&0xFFFFFFFF))
114 | return self._handle.write(struct.pack("I",(val&0xFFFFFFFF)));
115 |
116 | def _writeTitleSpace(self, val):
117 | self._writeUINT8(self.TitleSpace)
118 | self._writeUINT8(1)
119 | self._writeUINT8(val)
120 | self._titleSpace = val
121 |
122 | def _writeNumberOfTraces(self, val):
123 | self._writeUINT8(self.NumberOfTraces)
124 | self._writeUINT8(4)
125 | self._writeUINT32(val)
126 | self._numberOfTraces = val
127 |
128 | def _updateNumberOfTraces(self, val):
129 | self.findTag(self.NumberOfTraces)
130 | self._writeUINT8(self.NumberOfTraces)
131 | self._writeUINT8(4)
132 | self._writeUINT32(val)
133 | self._numberOfTraces = val
134 |
135 | def _writeDataSpace(self, val):
136 | self._writeUINT8(self.DataSpace)
137 | self._writeUINT8(2)
138 | self._writeUINT16(val)
139 | self._dataSpace = val
140 |
141 | def _writeNumberOfSamplesPerTrace(self, val):
142 | self._writeUINT8(self.NumberOfSamplesPerTrace)
143 | self._writeUINT8(4)
144 | self._writeUINT32(val)
145 | self._numberOfSamplesPerTrace = val
146 |
147 | def _writeSampleCoding(self, val):
148 | self._writeUINT8(self.SampleCoding)
149 | self._writeUINT8(1)
150 | self._writeUINT8(val)
151 | self._sampleCoding = val
152 |
153 | def _writeTraceBlock(self):
154 | self._writeUINT8(self.TraceBlock)
155 | self._writeUINT8(0)
156 |
157 | def open(self, fileName):
158 | self._handle = open(fileName,'rb')
159 | f = self._handle
160 | f.seek(0,2)
161 |
162 | fileSize = f.tell()
163 | f.seek(0)
164 | offset = 0
165 |
166 | while (offset < fileSize - self._traceBlockSpace):
167 | tag = ord(f.read(1))
168 | length = ord(f.read(1))
169 | addLen = 0
170 |
171 | if ((length & 0x80) != 0): #length is encoded in more then 1 byte
172 | addLen = length & 0x7F #how many byte the length is actually encoded in.
173 | length = 0
174 | for i in range(addLen):
175 | length = length + (ord(f.read(1)) << (i * 8))
176 |
177 | if tag == self.TraceBlock:
178 | self._sampleSpace = self._numberOfSamplesPerTrace * self._sampleCodingByteSize
179 | self._traceSpace = self._sampleSpace + self._dataSpace + self._titleSpace
180 | self._traceBlockSpace = self._numberOfTraces * self._traceSpace
181 |
182 | self._traceBlockOffset = f.tell() #get current pos
183 | f.seek(self._traceBlockOffset + self._traceBlockSpace) # XXX: why this?
184 | elif tag == self.TitleSpace:
185 | if length != 1:
186 | raise ValueError("Incorrect length for TitleSpace header field")
187 | self._titleSpace = self._readUINT8()
188 | elif tag == self.NumberOfTraces:
189 | if length != 4:
190 | raise ValueError("Incorrect length for NumberOfTraces header field")
191 | self._numberOfTraces = self._readUINT32()
192 | elif tag == self.DataSpace:
193 | if length != 2:
194 | raise ValueError("Incorrect length for DataSpace header field")
195 | self._dataSpace = self._readUINT16()
196 | elif tag == self.NumberOfSamplesPerTrace:
197 | if length != 4:
198 | raise ValueError("Incorrect length for NumberOfSamplesPerTrace header field")
199 | self._numberOfSamplesPerTrace = self._readUINT32()
200 | elif tag == self.YScale:
201 | if length != 4:
202 | raise ValueError("Incorrect length for YScale header field")
203 | self._yscale = self._readFloat32()
204 | elif tag == self.SampleCoding:
205 | if length != 1:
206 | raise ValueError("Incorrect length for SampleCoding header field")
207 | self._sampleCoding = self._readUINT8()
208 | #compensate for float sample coding tag
209 | if self._sampleCoding == self.CodingFloat: #float
210 | self._sampleCodingByteSize = 4
211 | self._npSampleCoding = "float32"
212 | else:
213 | self._npSampleCoding = "int" + str(self._sampleCoding * 8)
214 | self._sampleCodingByteSize = self._sampleCoding
215 | else:
216 | print("Unhandled tag: %x len: %d" % (tag, length), file=sys.stderr) # TODO: support other optional tags
217 | f.read(length)
218 |
219 | offset = offset + 2 + addLen + length
220 |
221 | def findTag(self,searchTag):
222 | if (self._handle == None):
223 | return 0
224 | f = self._handle
225 | f.seek(0,2)
226 | fileSize = f.tell()
227 | f.seek(0)
228 | offset = 0
229 |
230 | while (offset < fileSize - self._traceBlockSpace):
231 | tag = ord(f.read(1))
232 | length = ord(f.read(1))
233 | addLen = 0
234 |
235 | if ((length & 0x80) != 0): #length is encoded in more then 1 byte
236 | addLen = length & 0x7F #how many byte the length is actually encoded in.
237 | length = 0
238 | for i in range(addLen):
239 | length = length + (ord(f.read(1)) << (i * 8))
240 | if (tag == searchTag):
241 | f.seek(offset)
242 | return 1
243 | f.read(length)
244 | offset = offset + 2 + addLen + length
245 | return 0
246 |
247 | def new(self, fileName, titleSpace, sampleCoding, dataSpace, numberOfSamples):
248 | self._fileName = fileName
249 | self._handle = open(fileName,'wb')
250 | self._handle.close()
251 | self._handle = open(fileName,'r+b')
252 |
253 | self._writeTitleSpace(titleSpace)
254 | self._writeSampleCoding(sampleCoding)
255 | if self._sampleCoding == self.CodingFloat: #float
256 | self._sampleCodingByteSize = 4
257 | self._npSampleCoding = "float32"
258 | else:
259 | self._npSampleCoding = "int" + str(self._sampleCoding * 8)
260 | self._sampleCodingByteSize = self._sampleCoding
261 | self._writeDataSpace(dataSpace)
262 | self._writeNumberOfSamplesPerTrace(numberOfSamples)
263 | self._writeNumberOfTraces(0)
264 | self._sampleSpace = self._numberOfSamplesPerTrace * self._sampleCodingByteSize
265 | self._traceSpace = self._sampleSpace + self._dataSpace + self._titleSpace
266 | self._traceBlockSpace = self._numberOfTraces * self._traceSpace
267 | self._writeTraceBlock()
268 | self._traceBlockOffset = self._handle.tell() #get current pos
269 |
270 | def getTrace(self, traceIndex):
271 | if (self._handle == None):
272 | return None
273 | f = self._handle
274 | f.seek(self._traceBlockOffset + traceIndex * self._traceSpace)
275 |
276 | title = f.read(self._titleSpace)
277 | data = np.fromfile(f, dtype='uint8', count=self._dataSpace)
278 | samples = np.fromfile(f, dtype=self._npSampleCoding, count=self._numberOfSamplesPerTrace)
279 |
280 | return Trace(title, data, samples)
281 |
282 | def addTrace(self, trace):
283 | if (self._handle == None):
284 | return
285 | f = self._handle
286 | f.seek(0,2)
287 |
288 | # we only accept exact same size inputs
289 | if (len(trace._title) != self._titleSpace):
290 | raise ValueError("Wrong title size! %08x/%08x"%(len(trace._title),self._titleSpace))
291 | f.write(trace._title)
292 | if (len(trace._data) != self._dataSpace):
293 | raise ValueError("Wrong data size!")
294 | trace._data.tofile(f)
295 | trace._samples.tofile(f)
296 | self._numberOfTraces+=1
297 | # update the trace count
298 | self._updateNumberOfTraces(self._numberOfTraces)
299 | # go to the end again
300 | f.seek(0,2)
301 |
302 | def close(self):
303 | self._handle.close()
304 |
--------------------------------------------------------------------------------
/aes.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 | #
3 | # aes.py: implements AES - Advanced Encryption Standard
4 | # from the SlowAES project, http://code.google.com/p/slowaes/
5 | #
6 | # Copyright (c) 2008 Josh Davis ( http://www.josh-davis.org ),
7 | # Alex Martelli ( http://www.aleax.it )
8 | #
9 | # Ported from C code written by Laurent Haan ( http://www.progressive-coding.com )
10 | #
11 | # Licensed under the Apache License, Version 2.0
12 | # http://www.apache.org/licenses/
13 | #
14 | import os
15 | import sys
16 | import math
17 |
18 | class AES(object):
19 | '''AES funtions for a single block
20 | '''
21 | # Very annoying code: all is for an object, but no state is kept!
22 | # Should just be plain functions in a AES modlule.
23 |
24 | # valid key sizes
25 | keySize = dict(SIZE_128=16, SIZE_192=24, SIZE_256=32)
26 |
27 | # Rijndael S-box
28 | sbox = [0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67,
29 | 0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59,
30 | 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7,
31 | 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1,
32 | 0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05,
33 | 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83,
34 | 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29,
35 | 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b,
36 | 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, 0xd0, 0xef, 0xaa,
37 | 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c,
38 | 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc,
39 | 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec,
40 | 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19,
41 | 0x73, 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee,
42 | 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49,
43 | 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
44 | 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4,
45 | 0xea, 0x65, 0x7a, 0xae, 0x08, 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6,
46 | 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 0x70,
47 | 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9,
48 | 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e,
49 | 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 0x8c, 0xa1,
50 | 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0,
51 | 0x54, 0xbb, 0x16]
52 |
53 | # Rijndael Inverted S-box
54 | rsbox = [0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3,
55 | 0x9e, 0x81, 0xf3, 0xd7, 0xfb , 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f,
56 | 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb , 0x54,
57 | 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b,
58 | 0x42, 0xfa, 0xc3, 0x4e , 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24,
59 | 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25 , 0x72, 0xf8,
60 | 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d,
61 | 0x65, 0xb6, 0x92 , 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda,
62 | 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84 , 0x90, 0xd8, 0xab,
63 | 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3,
64 | 0x45, 0x06 , 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1,
65 | 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b , 0x3a, 0x91, 0x11, 0x41,
66 | 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6,
67 | 0x73 , 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9,
68 | 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e , 0x47, 0xf1, 0x1a, 0x71, 0x1d,
69 | 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b ,
70 | 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0,
71 | 0xfe, 0x78, 0xcd, 0x5a, 0xf4 , 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07,
72 | 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f , 0x60,
73 | 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f,
74 | 0x93, 0xc9, 0x9c, 0xef , 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5,
75 | 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61 , 0x17, 0x2b,
76 | 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55,
77 | 0x21, 0x0c, 0x7d]
78 |
79 | def getSBoxValue(self,num):
80 | """Retrieves a given S-Box Value"""
81 | return self.sbox[num]
82 |
83 | def getSBoxInvert(self,num):
84 | """Retrieves a given Inverted S-Box Value"""
85 | return self.rsbox[num]
86 |
87 | def rotate(self, word):
88 | """ Rijndael's key schedule rotate operation.
89 |
90 | Rotate a word eight bits to the left: eg, rotate(1d2c3a4f) == 2c3a4f1d
91 | Word is an char list of size 4 (32 bits overall).
92 | """
93 | return word[1:] + word[:1]
94 |
95 | # Rijndael Rcon
96 | Rcon = [0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36,
97 | 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97,
98 | 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72,
99 | 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66,
100 | 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04,
101 | 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d,
102 | 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3,
103 | 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61,
104 | 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a,
105 | 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40,
106 | 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc,
107 | 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5,
108 | 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a,
109 | 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d,
110 | 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c,
111 | 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35,
112 | 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4,
113 | 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc,
114 | 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08,
115 | 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a,
116 | 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d,
117 | 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2,
118 | 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74,
119 | 0xe8, 0xcb ]
120 |
121 | def getRconValue(self, num):
122 | """Retrieves a given Rcon Value"""
123 | return self.Rcon[num]
124 |
125 | def core(self, word, iteration):
126 | """Key schedule core."""
127 | # rotate the 32-bit word 8 bits to the left
128 | word = self.rotate(word)
129 | # apply S-Box substitution on all 4 parts of the 32-bit word
130 | for i in range(4):
131 | word[i] = self.getSBoxValue(word[i])
132 | # XOR the output of the rcon operation with i to the first part
133 | # (leftmost) only
134 | word[0] = word[0] ^ self.getRconValue(iteration)
135 | return word
136 |
137 | def expandKey(self, key, size, expandedKeySize):
138 | """Rijndael's key expansion.
139 |
140 | Expands an 128,192,256 key into an 176,208,240 bytes key
141 |
142 | expandedKey is a char list of large enough size,
143 | key is the non-expanded key.
144 | """
145 | # current expanded keySize, in bytes
146 | currentSize = 0
147 | rconIteration = 1
148 | expandedKey = [0] * expandedKeySize
149 |
150 | # set the 16, 24, 32 bytes of the expanded key to the input key
151 | for j in range(size):
152 | expandedKey[j] = key[j]
153 | currentSize += size
154 |
155 | while currentSize < expandedKeySize:
156 | # assign the previous 4 bytes to the temporary value t
157 | t = expandedKey[currentSize-4:currentSize]
158 |
159 | # every 16,24,32 bytes we apply the core schedule to t
160 | # and increment rconIteration afterwards
161 | if currentSize % size == 0:
162 | t = self.core(t, rconIteration)
163 | rconIteration += 1
164 | # For 256-bit keys, we add an extra sbox to the calculation
165 | if size == self.keySize["SIZE_256"] and ((currentSize % size) == 16):
166 | for l in range(4): t[l] = self.getSBoxValue(t[l])
167 |
168 | # We XOR t with the four-byte block 16,24,32 bytes before the new
169 | # expanded key. This becomes the next four bytes in the expanded
170 | # key.
171 | for m in range(4):
172 | expandedKey[currentSize] = expandedKey[currentSize - size] ^ \
173 | t[m]
174 | currentSize += 1
175 |
176 | return expandedKey
177 |
178 | def addRoundKey(self, state, roundKey):
179 | """Adds (XORs) the round key to the state."""
180 | for i in range(16):
181 | state[i] ^= roundKey[i]
182 | return state
183 |
184 | def createRoundKey(self, expandedKey, roundKeyPointer):
185 | """Create a round key.
186 | Creates a round key from the given expanded key and the
187 | position within the expanded key.
188 | """
189 | roundKey = [0] * 16
190 | for i in range(4):
191 | for j in range(4):
192 | roundKey[j*4+i] = expandedKey[roundKeyPointer + i*4 + j]
193 | return roundKey
194 |
195 | def galois_multiplication(self, a, b):
196 | """Galois multiplication of 8 bit characters a and b."""
197 | p = 0
198 | for counter in range(8):
199 | if b & 1: p ^= a
200 | hi_bit_set = a & 0x80
201 | a <<= 1
202 | # keep a 8 bit
203 | a &= 0xFF
204 | if hi_bit_set:
205 | a ^= 0x1b
206 | b >>= 1
207 | return p
208 |
209 | #
210 | # substitute all the values from the state with the value in the SBox
211 | # using the state value as index for the SBox
212 | #
213 | def subBytes(self, state, isInv):
214 | if isInv: getter = self.getSBoxInvert
215 | else: getter = self.getSBoxValue
216 | for i in range(16): state[i] = getter(state[i])
217 | return state
218 |
219 | # iterate over the 4 rows and call shiftRow() with that row
220 | def shiftRows(self, state, isInv):
221 | for i in range(4):
222 | state = self.shiftRow(state, i*4, i, isInv)
223 | return state
224 |
225 | # each iteration shifts the row to the left by 1
226 | def shiftRow(self, state, statePointer, nbr, isInv):
227 | for i in range(nbr):
228 | if isInv:
229 | state[statePointer:statePointer+4] = \
230 | state[statePointer+3:statePointer+4] + \
231 | state[statePointer:statePointer+3]
232 | else:
233 | state[statePointer:statePointer+4] = \
234 | state[statePointer+1:statePointer+4] + \
235 | state[statePointer:statePointer+1]
236 | return state
237 |
238 | # galois multiplication of the 4x4 matrix
239 | def mixColumns(self, state, isInv):
240 | # iterate over the 4 columns
241 | for i in range(4):
242 | # construct one column by slicing over the 4 rows
243 | column = state[i:i+16:4]
244 | # apply the mixColumn on one column
245 | column = self.mixColumn(column, isInv)
246 | # put the values back into the state
247 | state[i:i+16:4] = column
248 |
249 | return state
250 |
251 | # galois multiplication of 1 column of the 4x4 matrix
252 | def mixColumn(self, column, isInv):
253 | if isInv: mult = [14, 9, 13, 11]
254 | else: mult = [2, 1, 1, 3]
255 | cpy = list(column)
256 | g = self.galois_multiplication
257 |
258 | column[0] = g(cpy[0], mult[0]) ^ g(cpy[3], mult[1]) ^ \
259 | g(cpy[2], mult[2]) ^ g(cpy[1], mult[3])
260 | column[1] = g(cpy[1], mult[0]) ^ g(cpy[0], mult[1]) ^ \
261 | g(cpy[3], mult[2]) ^ g(cpy[2], mult[3])
262 | column[2] = g(cpy[2], mult[0]) ^ g(cpy[1], mult[1]) ^ \
263 | g(cpy[0], mult[2]) ^ g(cpy[3], mult[3])
264 | column[3] = g(cpy[3], mult[0]) ^ g(cpy[2], mult[1]) ^ \
265 | g(cpy[1], mult[2]) ^ g(cpy[0], mult[3])
266 | return column
267 |
268 | # applies the 4 operations of the forward round in sequence
269 | def aes_round(self, state, roundKey):
270 | state = self.subBytes(state, False)
271 | state = self.shiftRows(state, False)
272 | state = self.mixColumns(state, False)
273 | state = self.addRoundKey(state, roundKey)
274 | return state
275 |
276 | # applies the 4 operations of the inverse round in sequence
277 | def aes_invRound(self, state, roundKey):
278 | state = self.shiftRows(state, True)
279 | state = self.subBytes(state, True)
280 | state = self.addRoundKey(state, roundKey)
281 | state = self.mixColumns(state, True)
282 | return state
283 |
284 | # Perform the initial operations, the standard round, and the final
285 | # operations of the forward aes, creating a round key for each round
286 | def aes_main(self, state, expandedKey, nbrRounds):
287 | state = self.addRoundKey(state, self.createRoundKey(expandedKey, 0))
288 | i = 1
289 | while i < nbrRounds:
290 | state = self.aes_round(state,
291 | self.createRoundKey(expandedKey, 16*i))
292 | i += 1
293 | state = self.subBytes(state, False)
294 | state = self.shiftRows(state, False)
295 | state = self.addRoundKey(state,
296 | self.createRoundKey(expandedKey, 16*nbrRounds))
297 | return state
298 |
299 | # Perform the initial operations, the standard round, and the final
300 | # operations of the inverse aes, creating a round key for each round
301 | def aes_invMain(self, state, expandedKey, nbrRounds):
302 | state = self.addRoundKey(state,
303 | self.createRoundKey(expandedKey, 16*nbrRounds))
304 | i = nbrRounds - 1
305 | while i > 0:
306 | state = self.aes_invRound(state,
307 | self.createRoundKey(expandedKey, 16*i))
308 | i -= 1
309 | state = self.shiftRows(state, True)
310 | state = self.subBytes(state, True)
311 | state = self.addRoundKey(state, self.createRoundKey(expandedKey, 0))
312 | return state
313 |
314 | # encrypts a 128 bit input block against the given key of size specified
315 | def encrypt(self, iput, key, size):
316 | output = [0] * 16
317 | # the number of rounds
318 | nbrRounds = 0
319 | # the 128 bit block to encode
320 | block = [0] * 16
321 | # set the number of rounds
322 | if size == self.keySize["SIZE_128"]: nbrRounds = 10
323 | elif size == self.keySize["SIZE_192"]: nbrRounds = 12
324 | elif size == self.keySize["SIZE_256"]: nbrRounds = 14
325 | else: return None
326 |
327 | # the expanded keySize
328 | expandedKeySize = 16*(nbrRounds+1)
329 |
330 | # Set the block values, for the block:
331 | # a0,0 a0,1 a0,2 a0,3
332 | # a1,0 a1,1 a1,2 a1,3
333 | # a2,0 a2,1 a2,2 a2,3
334 | # a3,0 a3,1 a3,2 a3,3
335 | # the mapping order is a0,0 a1,0 a2,0 a3,0 a0,1 a1,1 ... a2,3 a3,3
336 | #
337 | # iterate over the columns
338 | for i in range(4):
339 | # iterate over the rows
340 | for j in range(4):
341 | block[(i+(j*4))] = iput[(i*4)+j]
342 |
343 | # expand the key into an 176, 208, 240 bytes key
344 | # the expanded key
345 | expandedKey = self.expandKey(key, size, expandedKeySize)
346 |
347 | # encrypt the block using the expandedKey
348 | block = self.aes_main(block, expandedKey, nbrRounds)
349 |
350 | # unmap the block again into the output
351 | for k in range(4):
352 | # iterate over the rows
353 | for l in range(4):
354 | output[(k*4)+l] = block[(k+(l*4))]
355 | return output
356 |
357 | # decrypts a 128 bit input block against the given key of size specified
358 | def decrypt(self, iput, key, size):
359 | output = [0] * 16
360 | # the number of rounds
361 | nbrRounds = 0
362 | # the 128 bit block to decode
363 | block = [0] * 16
364 | # set the number of rounds
365 | if size == self.keySize["SIZE_128"]: nbrRounds = 10
366 | elif size == self.keySize["SIZE_192"]: nbrRounds = 12
367 | elif size == self.keySize["SIZE_256"]: nbrRounds = 14
368 | else: return None
369 |
370 | # the expanded keySize
371 | expandedKeySize = 16*(nbrRounds+1)
372 |
373 | # Set the block values, for the block:
374 | # a0,0 a0,1 a0,2 a0,3
375 | # a1,0 a1,1 a1,2 a1,3
376 | # a2,0 a2,1 a2,2 a2,3
377 | # a3,0 a3,1 a3,2 a3,3
378 | # the mapping order is a0,0 a1,0 a2,0 a3,0 a0,1 a1,1 ... a2,3 a3,3
379 |
380 | # iterate over the columns
381 | for i in range(4):
382 | # iterate over the rows
383 | for j in range(4):
384 | block[(i+(j*4))] = iput[(i*4)+j]
385 | # expand the key into an 176, 208, 240 bytes key
386 | expandedKey = self.expandKey(key, size, expandedKeySize)
387 | # decrypt the block using the expandedKey
388 | block = self.aes_invMain(block, expandedKey, nbrRounds)
389 | # unmap the block again into the output
390 | for k in range(4):
391 | # iterate over the rows
392 | for l in range(4):
393 | output[(k*4)+l] = block[(k+(l*4))]
394 | return output
395 |
396 |
397 | class AESModeOfOperation(object):
398 | '''Handles AES with plaintext consistingof multiple blocks.
399 | Choice of block encoding modes: OFT, CFB, CBC
400 | '''
401 | # Very annoying code: all is for an object, but no state is kept!
402 | # Should just be plain functions in an AES_BlockMode module.
403 | aes = AES()
404 |
405 | # structure of supported modes of operation
406 | modeOfOperation = dict(OFB=0, CFB=1, CBC=2)
407 |
408 | # converts a 16 character string into a number array
409 | def convertString(self, string, start, end, mode):
410 | if end - start > 16: end = start + 16
411 | if mode == self.modeOfOperation["CBC"]: ar = [0] * 16
412 | else: ar = []
413 |
414 | i = start
415 | j = 0
416 | while len(ar) < end - start:
417 | ar.append(0)
418 | while i < end:
419 | ar[j] = ord(string[i])
420 | j += 1
421 | i += 1
422 | return ar
423 |
424 | # Mode of Operation Encryption
425 | # stringIn - Input String
426 | # mode - mode of type modeOfOperation
427 | # hexKey - a hex key of the bit length size
428 | # size - the bit length of the key
429 | # hexIV - the 128 bit hex Initilization Vector
430 | def encrypt(self, stringIn, mode, key, size, IV):
431 | if len(key) % size:
432 | return None
433 | if len(IV) % 16:
434 | return None
435 | # the AES input/output
436 | plaintext = []
437 | iput = [0] * 16
438 | output = []
439 | ciphertext = [0] * 16
440 | # the output cipher string
441 | cipherOut = []
442 | # char firstRound
443 | firstRound = True
444 | if stringIn != None:
445 | for j in range(int(math.ceil(float(len(stringIn))/16))):
446 | start = j*16
447 | end = j*16+16
448 | if end > len(stringIn):
449 | end = len(stringIn)
450 | plaintext = self.convertString(stringIn, start, end, mode)
451 | # print 'PT@%s:%s' % (j, plaintext)
452 | if mode == self.modeOfOperation["CFB"]:
453 | if firstRound:
454 | output = self.aes.encrypt(IV, key, size)
455 | firstRound = False
456 | else:
457 | output = self.aes.encrypt(iput, key, size)
458 | for i in range(16):
459 | if len(plaintext)-1 < i:
460 | ciphertext[i] = 0 ^ output[i]
461 | elif len(output)-1 < i:
462 | ciphertext[i] = plaintext[i] ^ 0
463 | elif len(plaintext)-1 < i and len(output) < i:
464 | ciphertext[i] = 0 ^ 0
465 | else:
466 | ciphertext[i] = plaintext[i] ^ output[i]
467 | for k in range(end-start):
468 | cipherOut.append(ciphertext[k])
469 | iput = ciphertext
470 | elif mode == self.modeOfOperation["OFB"]:
471 | if firstRound:
472 | output = self.aes.encrypt(IV, key, size)
473 | firstRound = False
474 | else:
475 | output = self.aes.encrypt(iput, key, size)
476 | for i in range(16):
477 | if len(plaintext)-1 < i:
478 | ciphertext[i] = 0 ^ output[i]
479 | elif len(output)-1 < i:
480 | ciphertext[i] = plaintext[i] ^ 0
481 | elif len(plaintext)-1 < i and len(output) < i:
482 | ciphertext[i] = 0 ^ 0
483 | else:
484 | ciphertext[i] = plaintext[i] ^ output[i]
485 | for k in range(end-start):
486 | cipherOut.append(ciphertext[k])
487 | iput = output
488 | elif mode == self.modeOfOperation["CBC"]:
489 | for i in range(16):
490 | if firstRound:
491 | iput[i] = plaintext[i] ^ IV[i]
492 | else:
493 | iput[i] = plaintext[i] ^ ciphertext[i]
494 | # print 'IP@%s:%s' % (j, iput)
495 | firstRound = False
496 | ciphertext = self.aes.encrypt(iput, key, size)
497 | # always 16 bytes because of the padding for CBC
498 | for k in range(16):
499 | cipherOut.append(ciphertext[k])
500 | return mode, len(stringIn), cipherOut
501 |
502 | # Mode of Operation Decryption
503 | # cipherIn - Encrypted String
504 | # originalsize - The unencrypted string length - required for CBC
505 | # mode - mode of type modeOfOperation
506 | # key - a number array of the bit length size
507 | # size - the bit length of the key
508 | # IV - the 128 bit number array Initilization Vector
509 | def decrypt(self, cipherIn, originalsize, mode, key, size, IV):
510 | # cipherIn = unescCtrlChars(cipherIn)
511 | if len(key) % size:
512 | return None
513 | if len(IV) % 16:
514 | return None
515 | # the AES input/output
516 | ciphertext = []
517 | iput = []
518 | output = []
519 | plaintext = [0] * 16
520 | # the output plain text character list
521 | chrOut = []
522 | # char firstRound
523 | firstRound = True
524 | if cipherIn != None:
525 | for j in range(int(math.ceil(float(len(cipherIn))/16))):
526 | start = j*16
527 | end = j*16+16
528 | if j*16+16 > len(cipherIn):
529 | end = len(cipherIn)
530 | ciphertext = cipherIn[start:end]
531 | if mode == self.modeOfOperation["CFB"]:
532 | if firstRound:
533 | output = self.aes.encrypt(IV, key, size)
534 | firstRound = False
535 | else:
536 | output = self.aes.encrypt(iput, key, size)
537 | for i in range(16):
538 | if len(output)-1 < i:
539 | plaintext[i] = 0 ^ ciphertext[i]
540 | elif len(ciphertext)-1 < i:
541 | plaintext[i] = output[i] ^ 0
542 | elif len(output)-1 < i and len(ciphertext) < i:
543 | plaintext[i] = 0 ^ 0
544 | else:
545 | plaintext[i] = output[i] ^ ciphertext[i]
546 | for k in range(end-start):
547 | chrOut.append(chr(plaintext[k]))
548 | iput = ciphertext
549 | elif mode == self.modeOfOperation["OFB"]:
550 | if firstRound:
551 | output = self.aes.encrypt(IV, key, size)
552 | firstRound = False
553 | else:
554 | output = self.aes.encrypt(iput, key, size)
555 | for i in range(16):
556 | if len(output)-1 < i:
557 | plaintext[i] = 0 ^ ciphertext[i]
558 | elif len(ciphertext)-1 < i:
559 | plaintext[i] = output[i] ^ 0
560 | elif len(output)-1 < i and len(ciphertext) < i:
561 | plaintext[i] = 0 ^ 0
562 | else:
563 | plaintext[i] = output[i] ^ ciphertext[i]
564 | for k in range(end-start):
565 | chrOut.append(chr(plaintext[k]))
566 | iput = output
567 | elif mode == self.modeOfOperation["CBC"]:
568 | output = self.aes.decrypt(ciphertext, key, size)
569 | for i in range(16):
570 | if firstRound:
571 | plaintext[i] = IV[i] ^ output[i]
572 | else:
573 | plaintext[i] = iput[i] ^ output[i]
574 | firstRound = False
575 | if originalsize is not None and originalsize < end:
576 | for k in range(originalsize-start):
577 | chrOut.append(chr(plaintext[k]))
578 | else:
579 | for k in range(end-start):
580 | chrOut.append(chr(plaintext[k]))
581 | iput = ciphertext
582 | return "".join(chrOut)
583 |
584 |
585 | def append_PKCS7_padding(s):
586 | """return s padded to a multiple of 16-bytes by PKCS7 padding"""
587 | numpads = 16 - (len(s)%16)
588 | return s + numpads*chr(numpads)
589 |
590 | def strip_PKCS7_padding(s):
591 | """return s stripped of PKCS7 padding"""
592 | if len(s)%16 or not s:
593 | raise ValueError("String of len %d can't be PCKS7-padded" % len(s))
594 | numpads = ord(s[-1])
595 | if numpads > 16:
596 | raise ValueError("String ending with %r can't be PCKS7-padded" % s[-1])
597 | return s[:-numpads]
598 |
599 | def encryptData(key, data, mode=AESModeOfOperation.modeOfOperation["CBC"]):
600 | """encrypt `data` using `key`
601 |
602 | `key` should be a string of bytes.
603 |
604 | returned cipher is a string of bytes prepended with the initialization
605 | vector.
606 |
607 | """
608 | key = map(ord, key)
609 | if mode == AESModeOfOperation.modeOfOperation["CBC"]:
610 | data = append_PKCS7_padding(data)
611 | keysize = len(key)
612 | assert keysize in AES.keySize.values(), 'invalid key size: %s' % keysize
613 | # create a new iv using random data
614 | iv = [ord(i) for i in os.urandom(16)]
615 | moo = AESModeOfOperation()
616 | (mode, length, ciph) = moo.encrypt(data, mode, key, keysize, iv)
617 | # With padding, the original length does not need to be known. It's a bad
618 | # idea to store the original message length.
619 | # prepend the iv.
620 | return ''.join(map(chr, iv)) + ''.join(map(chr, ciph))
621 |
622 | def decryptData(key, data, mode=AESModeOfOperation.modeOfOperation["CBC"]):
623 | """decrypt `data` using `key`
624 |
625 | `key` should be a string of bytes.
626 |
627 | `data` should have the initialization vector prepended as a string of
628 | ordinal values.
629 | """
630 |
631 | key = map(ord, key)
632 | keysize = len(key)
633 | assert keysize in AES.keySize.values(), 'invalid key size: %s' % keysize
634 | # iv is first 16 bytes
635 | iv = map(ord, data[:16])
636 | data = map(ord, data[16:])
637 | moo = AESModeOfOperation()
638 | decr = moo.decrypt(data, None, mode, key, keysize, iv)
639 | if mode == AESModeOfOperation.modeOfOperation["CBC"]:
640 | decr = strip_PKCS7_padding(decr)
641 | return decr
642 |
643 | def generateRandomKey(keysize):
644 | """Generates a key from random data of length `keysize`.
645 | The returned key is a string of bytes.
646 | """
647 | if keysize not in (16, 24, 32):
648 | emsg = 'Invalid keysize, %s. Should be one of (16, 24, 32).'
649 | raise ValueError, emsg % keysize
650 | return os.urandom(keysize)
651 |
652 | def testStr(cleartext, keysize=16, modeName = "CBC"):
653 | '''Test with random key, choice of mode.'''
654 | print 'Random key test', 'Mode:', modeName
655 | print 'cleartext:', cleartext
656 | key = generateRandomKey(keysize)
657 | print 'Key:', [ord(x) for x in key]
658 | mode = AESModeOfOperation.modeOfOperation[modeName]
659 | cipher = encryptData(key, cleartext, mode)
660 | print 'Cipher:', [ord(x) for x in cipher]
661 | decr = decryptData(key, cipher, mode)
662 | print 'Decrypted:', decr
663 |
664 |
665 | if __name__ == "__main__":
666 | moo = AESModeOfOperation()
667 | cleartext = "This is a test with several blocks!"
668 | cypherkey = [143,194,34,208,145,203,230,143,177,246,97,206,145,92,255,84]
669 | iv = [103,35,148,239,76,213,47,118,255,222,123,176,106,134,98,92]
670 | mode, orig_len, ciph = moo.encrypt(cleartext, moo.modeOfOperation["CBC"],
671 | cypherkey, moo.aes.keySize["SIZE_128"], iv)
672 | print 'm=%s, ol=%s (%s), ciph=%s' % (mode, orig_len, len(cleartext), ciph)
673 | decr = moo.decrypt(ciph, orig_len, mode, cypherkey,
674 | moo.aes.keySize["SIZE_128"], iv)
675 | print decr
676 | testStr(cleartext, 16, "CBC")
677 |
678 |
679 |
680 |
681 |
682 |
--------------------------------------------------------------------------------
/attackaessbox.py:
--------------------------------------------------------------------------------
1 | '''
2 | This file is part of pysca toolbox, license is GPLv3, see https://www.gnu.org/licenses/gpl-3.0.en.html
3 | Author: Ilya Kizhvatov
4 | Version: 1.0, 2017-05-14
5 |
6 | CPA and LRA attacks on the AES S-box
7 |
8 | The code should be self-explanatory (especially if you look into lracpa.py module)
9 |
10 | In the plots:
11 | - red trace is for known correct candidate
12 | - blue trace is for the winning candidate (e.g. the one with maximum peak)
13 | - grey traces are for all other candidates
14 | '''
15 |
16 | import numpy as np
17 | import matplotlib.pyplot as plt
18 | import time
19 |
20 | from aes import AES # interweb's SlowAES toolbox
21 | from lracpa import * # my LRA-CPA toolbox
22 | from condaveraes import * # incremental conditional averaging
23 |
24 |
25 | ##################################################
26 | ### 0. Configurable parameters
27 |
28 | ## Traceset, number of traces, and S-box to attack
29 | tracesetFilename = "traces/swaes_atmega_power.npz"
30 | sampleRange = (800, 1500) # range of samples to attack, in the format (low, high)
31 | N = 100 # number of traces to attack (less or equal to the amount of traces in the file)
32 | offset = 0 # trace number to start from
33 | evolutionStep = 10 # step for intermediate reports
34 | SboxNum = 2 # S-box to attack, counting from 0
35 |
36 | ## Leakage model
37 | ## (these parameters correspond to function names in lracpa module)
38 | intermediateFunction = sBoxOut # for CPA and LRA
39 | leakageFunction = leakageModelHW # for CPA
40 | basisFunctionsModel = basisModelSingleBits # for LRA
41 |
42 | ## Known key for ranking
43 | knownKeyStr = "2B7E151628AED2A6ABF7158809CF4F3C".decode("hex") # the correct key
44 | encrypt = True # to avoid selective commenting in the following lines below
45 |
46 | if encrypt: # for encryption, the first round key is as is
47 | knownKey = np.array(map(ord, knownKeyStr), dtype="uint8")
48 | else: # for decryption, need to run key expansion
49 | expandedKnownKey = AES().expandKey(map(ord, knownKeyStr), 16, 16 * 11) # this returs a list
50 | knownKey = np.array(expandedKnownKey[176-16:177], dtype="uint8")
51 |
52 |
53 | ##################################################
54 | ### 1. Log the parameters
55 |
56 | print "---\nAttack parameters"
57 | print "Intermediate function :", intermediateFunction.__name__
58 | print "CPA leakage function :", leakageFunction.__name__
59 | print "LRA basis functions :", basisFunctionsModel.__name__
60 | print "Encryption :", encrypt
61 | print "S-box number :", SboxNum
62 | print "Known key : 0x" + knownKeyStr.encode("hex")
63 | print "Known roundkey : 0x%s" % str(bytearray(knownKey)).encode("hex")
64 |
65 |
66 | #################################################
67 | ### 2. Load samples and data
68 |
69 | # Readout
70 | print "---\nLoading " + tracesetFilename
71 | t0 = time.clock()
72 | npzfile = np.load(tracesetFilename)
73 | data = npzfile['data'][offset:offset + N,SboxNum] # selecting only the required byte
74 | traces = npzfile['traces'][offset:offset + N,sampleRange[0]:sampleRange[1]]
75 | t1 = time.clock()
76 | timeLoad = t1 - t0
77 |
78 | # Log traceset parameters
79 | (numTraces, traceLength) = traces.shape
80 | print "Number of traces loaded :", numTraces
81 | print "Trace length :", traceLength
82 | print "Loading time : %0.2f s" % timeLoad
83 |
84 |
85 | #################################################
86 | ### 3. LRA and CPA with evolving amount of traces
87 |
88 | print "---\nAttack"
89 |
90 | t0 = time.clock()
91 |
92 | # initialize the incremental averager
93 | CondAver = ConditionalAveragerAesSbox(256, traceLength)
94 |
95 | # allocate arrays for storing key rank evolution
96 | numSteps = int(np.ceil(N / np.double(evolutionStep)))
97 | keyRankEvolutionCPA = np.zeros(numSteps)
98 | keyRankEvolutionLRA = np.zeros(numSteps)
99 |
100 | # the incremental loop
101 | tracesToSkip = 20 # warm-up to avoid numerical problems for small evolution step
102 | for i in range (0, tracesToSkip - 1):
103 | CondAver.addTrace(data[i], traces[i])
104 | for i in range(tracesToSkip - 1, N):
105 | CondAver.addTrace(data[i], traces[i])
106 |
107 | if (((i + 1) % evolutionStep == 0) or ((i + 1) == N)):
108 |
109 | (avdata, avtraces) = CondAver.getSnapshot()
110 |
111 | CorrTraces = cpaAES(avdata, avtraces, intermediateFunction, leakageFunction)
112 | R2, coefs = lraAES(avdata, avtraces, intermediateFunction, basisFunctionsModel)
113 |
114 | print "---\nResults after %d traces" % (i + 1)
115 | print "CPA"
116 | CorrPeaks = np.max(np.abs(CorrTraces), axis=1) # global maximization, absolute value!
117 | CpaWinningCandidate = np.argmax(CorrPeaks)
118 | CpaWinningCandidatePeak = np.max(CorrPeaks)
119 | CpaCorrectCandidateRank = np.count_nonzero(CorrPeaks >= CorrPeaks[knownKey[SboxNum]])
120 | CpaCorrectCandidatePeak = CorrPeaks[knownKey[SboxNum]]
121 | print "Winning candidate: 0x%02x, peak magnitude %f" % (CpaWinningCandidate, CpaWinningCandidatePeak)
122 | print "Correct candidate: 0x%02x, peak magnitude %f, rank %d" % (knownKey[SboxNum], CpaCorrectCandidatePeak, CpaCorrectCandidateRank)
123 |
124 | print "LRA"
125 | R2Peaks = np.max(R2, axis=1) # global maximization
126 | LraWinningCandidate = np.argmax(R2Peaks)
127 | LraWinningCandidatePeak = np.max(R2Peaks)
128 | LraCorrectCandidateRank = np.count_nonzero(R2Peaks >= R2Peaks[knownKey[SboxNum]])
129 | LraCorrectCandidatePeak = R2Peaks[knownKey[SboxNum]]
130 | print "Winning candidate: 0x%02x, peak magnitude %f" % (LraWinningCandidate, LraWinningCandidatePeak)
131 | print "Correct candidate: 0x%02x, peak magnitude %f, rank %d" % (knownKey[SboxNum], LraCorrectCandidatePeak, LraCorrectCandidateRank)
132 |
133 | stepCount = int(np.floor(i / np.double(evolutionStep)))
134 | keyRankEvolutionCPA[stepCount] = CpaCorrectCandidateRank
135 | keyRankEvolutionLRA[stepCount] = LraCorrectCandidateRank
136 |
137 | t1 = time.clock()
138 | timeAll = t1 - t0
139 |
140 | print "---\nCumulative timing"
141 | print "%0.2f s" % timeAll
142 |
143 | # save the rank evolution for later processing
144 | #np.savez("results/keyRankEvolutionSbox%02d" % SboxNum, kreCPA=keyRankEvolutionCPA, kreLRA=keyRankEvolutionLRA, step=evolutionStep)
145 |
146 | #################################################
147 | ### 4. Visualize results
148 |
149 | print "---\nPlotting..."
150 |
151 | fig = plt.figure()
152 |
153 | # allocate grid
154 | axCPA = plt.subplot2grid((3, 2), (0, 0))
155 | axLRA = plt.subplot2grid((3, 2), (1, 0))
156 | axLRAcoefs = plt.subplot2grid((3, 2), (2, 0))
157 | axRankEvolution = plt.subplot2grid((2, 2), (0, 1), rowspan = 3)
158 |
159 | # compute trace nubmers for x axis (TODO: move into block 3)
160 | traceNumbers = np.arange(evolutionStep, N + 1, evolutionStep)
161 |
162 | # CPA
163 | axCPA.plot(CorrTraces.T, color = 'grey')
164 | if CpaWinningCandidate != knownKey[SboxNum]:
165 | axCPA.plot(CorrTraces[CpaWinningCandidate, :], 'blue')
166 | axCPA.plot(CorrTraces[knownKey[SboxNum], :], 'r')
167 | axRankEvolution.plot(traceNumbers, keyRankEvolutionCPA, color = 'green')
168 | axCPA.set_xlim([0, traceLength])
169 |
170 | # LRA
171 | axLRA.plot(R2.T, color = 'grey')
172 | if LraWinningCandidate != knownKey[SboxNum]:
173 | axLRA.plot(R2[LraWinningCandidate, :], 'blue')
174 | axLRA.plot(R2[knownKey[SboxNum], :], 'r')
175 | axRankEvolution.plot(traceNumbers, keyRankEvolutionLRA, color = 'magenta')
176 | axLRA.set_xlim([0, traceLength])
177 |
178 | # LRA coefs
179 | coefsKnownKey = np.array(coefs[knownKey[SboxNum]])
180 | axLRAcoefs.pcolormesh(coefsKnownKey[:,:-1].T, cmap="jet")
181 | axLRAcoefs.set_xlim([0, traceLength])
182 |
183 | # labels
184 | fig.suptitle("CPA and LRA on %d traces" % N)
185 | axCPA.set_ylabel('Correlation')
186 | axLRA.set_ylabel('R2')
187 | axLRAcoefs.set_ylabel('Basis function (bit)')
188 | axLRAcoefs.set_xlabel('Time sample')
189 | axRankEvolution.set_ylabel('Correct key candidate rank')
190 | axRankEvolution.set_xlabel('Number of traces')
191 | axRankEvolution.set_title('Correct key rank evolution (global maximisation)')
192 |
193 | # Limits and tick labels for key rand evolution plot
194 | axRankEvolution.set_xlim([traceNumbers[int(np.ceil(tracesToSkip / np.double(evolutionStep))) - 1], N])
195 | axRankEvolution.set_ylim([0, 256])
196 | axRankEvolution.grid(b=True, which='both', color='0.65',linestyle='-')
197 | #axRankEvolution.ticklabel_format(style='sci', axis='x', scilimits=(0,0), useOffset=True)
198 |
199 | # Legend for rank evolution plot
200 | axRankEvolution.legend(['CPA', 'LRA'], loc='upper right')
201 |
202 | plt.show()
203 |
--------------------------------------------------------------------------------
/attackdesroundxor.py:
--------------------------------------------------------------------------------
1 | '''
2 | This file is part of pysca toolbox, license is GPLv3, see https://www.gnu.org/licenses/gpl-3.0.en.html
3 | Author: Ilya Kizhvatov
4 | Version: 1.0, 2017-05-14
5 |
6 | CPA and LRA attacks on DES round in XOR out
7 |
8 | The code should be self-explanatory (especially if you look into lracpa.py module)
9 |
10 | In the plots:
11 | - red trace is for known correct candidate
12 | - blue trace is for the winning candidate (e.g. the one with maximum peak)
13 | - grey traces are for all other candidates
14 | '''
15 |
16 | import numpy as np
17 | import matplotlib.pyplot as plt
18 | import struct
19 | import time
20 |
21 | from desutils import * # my DES utilities
22 | from lracpa import * # my LRA-CPA toolbox
23 | from condaverdes import * # incremental conditional averaging
24 |
25 |
26 | ##################################################
27 | ### 0. Configurable parameters
28 |
29 | ## Traceset, number of traces, and S-box to attack
30 | tracesetFilename = "traces/hwdes_card8_power.npz"
31 | sampleRange = (0, 50) # range of smaples to attack
32 | N = 10000 # number of traces to attack (less or equal to the amount of traces in the file)
33 | offset = 0 # trace number to start from
34 | evolutionStep = 500 # step for intermediate reports
35 | SboxNum = 1 # S-box to attack, counting from 0
36 |
37 | ## Leakage model
38 | ## (these parameters correspond to function names in lracpa module)
39 | averagingFunction = roundXOR_valueForAveraging # for CPA and LRA
40 | intermediateFunction = roundXOR_targetVariable # for CPA and LRA
41 | leakageFunction = leakageModelHW # for CPA
42 | basisFunctionsModel = basisModelSingleBits # for LRA
43 |
44 | ## Known key for ranking
45 | knownKey = 0x8A7400A03230DA28
46 | encrypt = True
47 |
48 | # get the known key
49 | roundKeyNum = 1
50 | if (encrypt == False):
51 | roundKeyNum = 16
52 | roundKey = computeRoundKeys(knownKey, roundKeyNum)[roundKeyNum-1]
53 | knownKeyChunk = roundKeyChunk(roundKey, SboxNum)
54 |
55 | ##################################################
56 | ### 1. Log the parameters
57 |
58 | print "---\nAttack parameters"
59 | print "Averaging function :", averagingFunction.__name__
60 | print "Intermediate function :", intermediateFunction.__name__
61 | print "CPA leakage function :", leakageFunction.__name__
62 | print "LRA basis functions :", basisFunctionsModel.__name__
63 | print "Encryption :", encrypt
64 | print "S-box number :", SboxNum
65 | print "Known key : " + format(knownKey, "#018x")
66 | print "Known round key : " + format(roundKey, '#014x'),
67 | print '[',
68 | for i in range(8):
69 | print format(roundKeyChunk(roundKey, i), '#04x'),
70 | print ']'
71 |
72 |
73 | #################################################
74 | ### 2. Load samples and data
75 |
76 | # Readout
77 | print "---\nLoading " + tracesetFilename
78 | t0 = time.clock()
79 | npzfile = np.load(tracesetFilename)
80 | data = npzfile['data'][0:N]
81 | traces = npzfile['traces'][0:N,sampleRange[0]:sampleRange[1]]
82 | t1 = time.clock()
83 | timeLoad = t1 - t0
84 |
85 | # convert data byte arrays to integers (more convenient for DES)
86 | print "Converting data..."
87 | datanew = []
88 | for i in range(0, len(data)):
89 | datanew.append(struct.unpack('!Q', data[i][0:8].tostring())[0])
90 | data = datanew # old data will be garbage-collected
91 |
92 | # Log traceset parameters
93 | (numTraces, traceLength) = traces.shape
94 | print "Number of traces loaded :", numTraces
95 | print "Trace length :", traceLength
96 | print "Loading time : %0.2f s" % timeLoad
97 |
98 | #################################################
99 | ### 3. Attack with fixed amount of traces
100 | '''
101 | print "---\nAttack"
102 |
103 | # perform conditional averaging
104 | CondAver = ConditionalAveragerDes(1024, traceLength)
105 | for i in range(N):
106 | CondAver.addTrace(data[i], traces[i], averagingFunction, SboxNum)
107 | (avdata, avtraces) = CondAver.getSnapshot()
108 |
109 | # CPA
110 | CorrTraces = cpaDES(avdata, avtraces, intermediateFunction, SboxNum, leakageFunction)
111 |
112 | # LRA
113 | R2, coefs = lraDES(avdata, avtraces, intermediateFunction, SboxNum, basisFunctionsModel)
114 |
115 | ### visualize results
116 |
117 | fig = plt.figure()
118 |
119 | # allocate grid
120 | axCPA = plt.subplot2grid((3, 1), (0, 0))
121 | axLRA = plt.subplot2grid((3, 1), (1, 0))
122 | axLRAcoefs = plt.subplot2grid((3, 1), (2, 0))
123 |
124 | # CPA
125 | axCPA.plot(CorrTraces.T, color = 'grey')
126 | axCPA.plot(CorrTraces[knownKeyChunk, :], 'r')
127 | axCPA.set_xlim([0, traceLength])
128 |
129 | # LRA
130 | axLRA.plot(R2.T, color = 'grey')
131 | axLRA.plot(R2[knownKeyChunk, :], 'r')
132 | axLRA.set_xlim([0, traceLength])
133 |
134 | # LRA coefs
135 | coefsKnownKey = np.array(coefs[knownKeyChunk])
136 | axLRAcoefs.pcolormesh(coefsKnownKey[:,:-1].T, cmap="jet")
137 | axLRAcoefs.set_xlim([0, traceLength])
138 |
139 | # labels
140 | fig.suptitle("CPA and LRA on %d traces" % N)
141 | axCPA.set_ylabel('Correlation')
142 | axLRA.set_ylabel('R2')
143 | axLRAcoefs.set_ylabel('Basis function (bit)')
144 | axLRAcoefs.set_xlabel('Time sample')
145 |
146 | plt.show()
147 | '''
148 | #################################################
149 | ### 4. Attack with evolving amount of traces
150 |
151 | print "---\nAttack"
152 |
153 | t0 = time.clock()
154 |
155 | # initialize the incremental averager
156 | CondAver = ConditionalAveragerDes(1024, traceLength)
157 |
158 | # allocate arrays for storing key rank evolution
159 | numSteps = int(np.ceil(N / np.double(evolutionStep)))
160 | keyRankEvolutionCPA = np.zeros(numSteps)
161 | keyRankEvolutionLRA = np.zeros(numSteps)
162 |
163 | # the incremental loop
164 | tracesToSkip = 20 # warm-up to avoid numerical problems for small evolution step
165 | for i in range (0, tracesToSkip - 1):
166 | CondAver.addTrace(data[i], traces[i], averagingFunction, SboxNum)
167 | for i in range(tracesToSkip - 1, N):
168 | CondAver.addTrace(data[i], traces[i], averagingFunction, SboxNum)
169 |
170 | if (((i + 1) % evolutionStep == 0) or ((i + 1) == N)):
171 |
172 | (avdata, avtraces) = CondAver.getSnapshot()
173 |
174 | CorrTraces = cpaDES(avdata, avtraces, intermediateFunction, SboxNum, leakageFunction)
175 | R2, coefs = lraDES(avdata, avtraces, intermediateFunction, SboxNum, basisFunctionsModel)
176 | #R2 = normalizeR2Traces(R2)
177 |
178 | print "---\nResults after %d traces" % (i + 1)
179 | print "CPA"
180 | CorrPeaks = np.max(np.abs(CorrTraces), axis=1) # global maximization, absolute value!
181 | CpaWinningCandidate = np.argmax(CorrPeaks)
182 | CpaWinningCandidatePeak = np.max(CorrPeaks)
183 | CpaCorrectCandidateRank = np.count_nonzero(CorrPeaks >= CorrPeaks[knownKeyChunk])
184 | CpaCorrectCandidatePeak = CorrPeaks[knownKeyChunk]
185 | print "Winning candidate: 0x%02x, peak magnitude %f" % (CpaWinningCandidate, CpaWinningCandidatePeak)
186 | print "Correct candidate: 0x%02x, peak magnitude %f, rank %d" % (knownKeyChunk, CpaCorrectCandidatePeak, CpaCorrectCandidateRank)
187 |
188 | print "LRA"
189 | R2Peaks = np.max(R2, axis=1) # global maximization
190 | LraWinningCandidate = np.argmax(R2Peaks)
191 | LraWinningCandidatePeak = np.max(R2Peaks)
192 | LraCorrectCandidateRank = np.count_nonzero(R2Peaks >= R2Peaks[knownKeyChunk])
193 | LraCorrectCandidatePeak = R2Peaks[knownKeyChunk]
194 | print "Winning candidate: 0x%02x, peak magnitude %f" % (LraWinningCandidate, LraWinningCandidatePeak)
195 | print "Correct candidate: 0x%02x, peak magnitude %f, rank %d" % (knownKeyChunk, LraCorrectCandidatePeak, LraCorrectCandidateRank)
196 |
197 | stepCount = int(np.floor(i / np.double(evolutionStep)))
198 | keyRankEvolutionCPA[stepCount] = CpaCorrectCandidateRank
199 | keyRankEvolutionLRA[stepCount] = LraCorrectCandidateRank
200 |
201 | t1 = time.clock()
202 | timeAll = t1 - t0
203 |
204 | print "---\nCumulative timing"
205 | print "%0.2f s" % timeAll
206 |
207 | # save the rank evolution for later processing
208 | #np.savez("results/keyRankEvolutionSbox%02d" % SboxNum, kreCPA=keyRankEvolutionCPA, kreLRA=keyRankEvolutionLRA, step=evolutionStep)
209 |
210 | #################################################
211 | ### 5. Visualize results
212 |
213 | print "---\nPlotting..."
214 |
215 | fig = plt.figure()
216 |
217 | # allocate grid
218 | axCPA = plt.subplot2grid((3, 2), (0, 0))
219 | axLRA = plt.subplot2grid((3, 2), (1, 0))
220 | axLRAcoefs = plt.subplot2grid((3, 2), (2, 0))
221 | axRankEvolution = plt.subplot2grid((2, 2), (0, 1), rowspan = 3)
222 |
223 | # compute trace nubmers for x axis (TODO: move into block 3)
224 | traceNumbers = np.arange(evolutionStep, N + 1, evolutionStep)
225 |
226 | # CPA
227 | axCPA.plot(CorrTraces.T, color = 'grey')
228 | if CpaWinningCandidate != knownKeyChunk:
229 | axCPA.plot(CorrTraces[CpaWinningCandidate, :], 'blue')
230 | axCPA.plot(CorrTraces[knownKeyChunk, :], 'r')
231 | axRankEvolution.plot(traceNumbers, keyRankEvolutionCPA, color = 'green')
232 | axCPA.set_xlim([0, traceLength])
233 |
234 | # LRA
235 | axLRA.plot(R2.T, color = 'grey')
236 | if LraWinningCandidate != knownKeyChunk:
237 | axLRA.plot(R2[LraWinningCandidate, :], 'blue')
238 | axLRA.plot(R2[knownKeyChunk, :], 'r')
239 | axRankEvolution.plot(traceNumbers, keyRankEvolutionLRA, color = 'magenta')
240 | axLRA.set_xlim([0, traceLength])
241 |
242 | # LRA coefs
243 | coefsKnownKey = np.array(coefs[knownKeyChunk])
244 | axLRAcoefs.pcolormesh(coefsKnownKey[:,:-1].T, cmap="jet")
245 | axLRAcoefs.set_xlim([0, traceLength])
246 |
247 | # labels
248 | fig.suptitle("CPA and LRA on %d traces" % N)
249 | axCPA.set_ylabel('Correlation')
250 | axLRA.set_ylabel('R2')
251 | axLRAcoefs.set_ylabel('Basis function (bit)')
252 | axLRAcoefs.set_xlabel('Time sample')
253 | axRankEvolution.set_ylabel('Correct key candidate rank')
254 | axRankEvolution.set_xlabel('Number of traces')
255 | axRankEvolution.set_title('Correct key rank evolution (global maximisation)')
256 |
257 | # Limits and tick labels for key rand evolution plot
258 | axRankEvolution.set_xlim([traceNumbers[int(np.ceil(tracesToSkip / np.double(evolutionStep))) - 1], N])
259 | axRankEvolution.set_ylim([0, 64])
260 | axRankEvolution.grid(b=True, which='both', color='0.65',linestyle='-')
261 | #axRankEvolution.ticklabel_format(style='sci', axis='x', scilimits=(0,0), useOffset=True)
262 |
263 | # Legend for rank evolution plot
264 | axRankEvolution.legend(['CPA', 'LRA'], loc='upper right')
265 |
266 | plt.show()
--------------------------------------------------------------------------------
/compareperformance.py:
--------------------------------------------------------------------------------
1 | '''
2 | This file is part of pysca toolbox, license is GPLv3, see https://www.gnu.org/licenses/gpl-3.0.en.html
3 | Author: Ilya Kizhvatov
4 | Version: 1.0, 2017-05-14
5 |
6 | Compare perfromance and output of LRA and CPA with and without conditional averaging
7 | '''
8 |
9 | import numpy as np
10 | import matplotlib.pyplot as plt
11 | import time
12 |
13 | from aes import AES # interweb's SlowAES toolbox
14 | from lracpa import * # my LRA-CPA toolbox
15 | from condaveraes import * # incremental conditional averaging
16 |
17 | ##################################################
18 | ### 0. Configurable parameters
19 |
20 | ## Traceset, number of traces, and S-box to attack
21 | tracesetFilename = "traces/swaes_atmega_power.npz"
22 | sampleRange = (950, 1150) # range of samples to attack, in the format (low, high)
23 | N = 2000 # number of traces to attack (less or equal to the amount of traces in the file)
24 | offset = 0 # trace number to start from
25 | SboxNum = 0 # S-box to attack, counting from 0
26 |
27 | ## Leakage model
28 | ## (these parameters correspond to function names in lracpa module)
29 | intermediateFunction = sBoxOut # for CPA and LRA
30 | leakageFunction = leakageModelHW # for CPA
31 | basisFunctionsModel = basisModelSingleBits # for LRA
32 |
33 | ## Known key for ranking
34 | knownKeyStr = "2B7E151628AED2A6ABF7158809CF4F3C".decode("hex") # the correct key
35 | encrypt = True # to avoid selective commenting in the following lines below
36 |
37 | if encrypt: # for encryption, the first round key is as is
38 | knownKey = np.array(map(ord, knownKeyStr), dtype="uint8")
39 | else: # for decryption, need to run key expansion
40 | expandedKnownKey = AES().expandKey(map(ord, knownKeyStr), 16, 16 * 11) # this returs a list
41 | knownKey = np.array(expandedKnownKey[176-16:177], dtype="uint8")
42 |
43 |
44 | ##################################################
45 | ### 1. Log the parameters
46 |
47 | print "---\nAttack parameters"
48 | print "Intermediate function :", intermediateFunction.__name__
49 | print "CPA leakage function :", leakageFunction.__name__
50 | print "LRA basis functions :", basisFunctionsModel.__name__
51 | print "Encryption :", encrypt
52 | print "S-box number :", SboxNum
53 | print "Known roundkey : 0x%s" % str(bytearray(knownKey)).encode("hex")
54 |
55 |
56 | #################################################
57 | ### 2. Load samples and data
58 |
59 | # Readout
60 | print "---\nLoading " + tracesetFilename
61 | t0 = time.clock()
62 | npzfile = np.load(tracesetFilename)
63 | data = npzfile['data'][offset:offset + N,SboxNum] # selecting only the required byte
64 | traces = npzfile['traces'][offset:offset + N,sampleRange[0]:sampleRange[1]]
65 | t1 = time.clock()
66 | timeLoad = t1 - t0
67 |
68 | # Log traceset parameters
69 | (numTraces, traceLength) = traces.shape
70 | print "Number of traces loaded :", numTraces
71 | print "Trace length :", traceLength
72 | print "Loading time : %0.2f s" % timeLoad
73 |
74 | #################################################
75 | ### 2. LRA and CPA with a fixed number of traces
76 |
77 | print "---\nAttacks with %d traces" % numTraces
78 | print "Running CPA...",
79 | t0 = time.clock()
80 | CorrTraces = cpaAES(data, traces, intermediateFunction, leakageFunction)
81 | t1 = time.clock()
82 | print "done in %f s" % (t1 - t0)
83 | print "Running LRA...",
84 | t0 = time.clock()
85 | (R2, coefs) = lraAES(data, traces, intermediateFunction, basisFunctionsModel)
86 | t1 = time.clock()
87 | print "done in %f s" % (t1 - t0)
88 | print "Normalizing LRA results...",
89 | R2norm = normalizeR2Traces(R2)
90 | print "done"
91 |
92 | print "---\nAttacks with %d traces and conditional averaging" % numTraces
93 | print "Performing conditional trace averaging...",
94 | t0 = time.clock()
95 | (avdata, avtraces) = conditionalAveragingAESSbox(data[0:numTraces], traces[0:numTraces])
96 | t1 = time.clock()
97 | print "done in %f s" % (t1 - t0)
98 | print "Running CPA on averaged traces...",
99 | t0 = time.clock()
100 | CorrTracesAv = cpaAES(avdata, avtraces, intermediateFunction, leakageFunction)
101 | t1 = time.clock()
102 | print "done in %f s" % (t1 - t0)
103 | print "Running LRA on averaged traces...",
104 | t0 = time.clock()
105 | (R2Av, coefsav) = lraAES(avdata, avtraces, intermediateFunction, basisFunctionsModel)
106 | t1 = time.clock()
107 | print "done in %f s" % (t1 - t0)
108 | print "Normalizing LRA results...",
109 | R2AvNorm = normalizeR2Traces(R2Av)
110 | print "done"
111 |
112 | ### 3. visualize the result, highlighting the correct trace
113 |
114 | print "---\nPlotting..."
115 | fig, ax = plt.subplots(3,2,sharex=True, squeeze=True)
116 |
117 | WrongKeyRange = range(0, knownKey[SboxNum]) + range(knownKey[SboxNum] + 1, 256)
118 |
119 | ax[0][0].plot(CorrTraces[WrongKeyRange, :].T, color = 'grey')
120 | ax[0][0].plot(CorrTraces[knownKey[SboxNum], :], 'r')
121 |
122 | ax[1][0].plot(R2[WrongKeyRange, :].T, color = 'grey')
123 | ax[1][0].plot(R2[knownKey[SboxNum], :], 'r')
124 |
125 | ax[2][0].plot(R2norm[WrongKeyRange, :].T, color = 'grey')
126 | ax[2][0].plot(R2norm[knownKey[SboxNum], :], 'r')
127 |
128 | ax[0][1].plot(CorrTracesAv[WrongKeyRange, :].T, color = 'grey')
129 | ax[0][1].plot(CorrTracesAv[knownKey[SboxNum], :], 'r')
130 |
131 | ax[1][1].plot(R2Av[WrongKeyRange, :].T, color = 'grey')
132 | ax[1][1].plot(R2Av[knownKey[SboxNum], :], 'r')
133 |
134 | ax[2][1].plot(R2AvNorm[WrongKeyRange, :].T, color = 'grey')
135 | ax[2][1].plot(R2AvNorm[knownKey[SboxNum], :], 'r')
136 |
137 | # same vertical scales for correlation and R2
138 | ax[0][0].set_ylim(ax[0][1].get_ylim())
139 | ax[1][0].set_ylim(ax[1][1].get_ylim())
140 |
141 | fig.suptitle("CPA and LRA on %d traces" % numTraces)
142 | ax[0][0].set_title('Without cond. averaging')
143 | ax[0][1].set_title('With cond. averaging')
144 | ax[0][0].set_ylabel('Correlation')
145 | ax[1][0].set_ylabel('R2')
146 | ax[2][0].set_ylabel('Normalized R2')
147 | ax[2][0].set_xlabel('Time sample')
148 | ax[2][1].set_xlabel('Time sample')
149 |
150 | plt.show()
--------------------------------------------------------------------------------
/condaveraes.py:
--------------------------------------------------------------------------------
1 | '''
2 | This file is part of pysca toolbox, license is GPLv3, see https://www.gnu.org/licenses/gpl-3.0.en.html
3 | Author: Ilya Kizhvatov
4 | Version: 1.0, 2017-05-14
5 |
6 | Conditional averaging for AES. Very rough so far.
7 |
8 | TODO:
9 | - iterator (therefore loop inside)
10 | - automatic readout from a file
11 | '''
12 |
13 | import numpy as np
14 |
15 | class ConditionalAveragerAesSbox:
16 |
17 | def __init__(self, numValues, traceLength):
18 | '''Allocate the matrix of averaged traces'''
19 | self.avtraces = np.zeros((numValues, traceLength))
20 | self.counters = np.zeros(numValues)
21 | print 'ConditionalAverager: initialized for %d values and trace length %d' % (numValues, traceLength)
22 |
23 | def addTrace(self, data, trace):
24 | '''Add a single trace with corresponding single chunk of data'''
25 | if (self.counters[data] == 0):
26 | self.avtraces[data] = trace
27 | else:
28 | self.avtraces[data] = self.avtraces[data] + (trace - self.avtraces[data]) / self.counters[data]
29 | self.counters[data] += 1
30 |
31 | def getSnapshot(self):
32 | ''' return a snapshot of the average matrix'''
33 | avdataSnap = np.flatnonzero(self.counters) # get an vector of only _observed_ values
34 | avtracesSnap = self.avtraces[avdataSnap] # remove lines corresponding to non-observed values
35 | return avdataSnap, avtracesSnap
36 |
--------------------------------------------------------------------------------
/condaverdes.py:
--------------------------------------------------------------------------------
1 | '''
2 | This file is part of pysca toolbox, license is GPLv3, see https://www.gnu.org/licenses/gpl-3.0.en.html
3 | Author: Ilya Kizhvatov
4 | Version: 1.0, 2017-05-14
5 |
6 | Conditional averaging for DES
7 | '''
8 |
9 | import numpy as np
10 |
11 | class ConditionalAveragerDes:
12 |
13 | def __init__(self, numValues, traceLength):
14 | '''Allocate the matrix of averaged traces'''
15 | self.avtraces = np.zeros((numValues, traceLength))
16 | self.counters = np.zeros(numValues)
17 | print 'ConditionalAverager: initialized for %d values and trace length %d' % (numValues, traceLength)
18 |
19 | def addTrace(self, data, trace, dataFunction, sBoxNumber):
20 | '''Add a single trace with corresponding single chunk of data computed based on the given function'''
21 |
22 | x = dataFunction(data, sBoxNumber)
23 |
24 | if (self.counters[x] == 0):
25 | self.avtraces[x] = trace
26 | else:
27 | self.avtraces[x] = self.avtraces[x] + (trace - self.avtraces[x]) / self.counters[x]
28 | self.counters[x] += 1
29 |
30 | def getSnapshot(self):
31 | ''' return a snapshot of the average matrix'''
32 | avdataSnap = np.flatnonzero(self.counters) # get an vector of only _observed_ values
33 | avtracesSnap = self.avtraces[avdataSnap] # remove lines corresponding to non-observed values
34 | return avdataSnap, avtracesSnap
35 |
--------------------------------------------------------------------------------
/cpavisualdemo.py:
--------------------------------------------------------------------------------
1 | '''
2 | This file is part of pysca toolbox, license is GPLv3, see https://www.gnu.org/licenses/gpl-3.0.en.html
3 | Author: Ilya Kizhvatov
4 | Version: 1.0, 2017-05-14
5 |
6 | CPA visual demo with live evolution, with AES-128 traces from ATmega16
7 | '''
8 |
9 | import numpy as np
10 | import matplotlib as mpl
11 | mpl.use('TkAgg') # enforcing the backend, otherwise fails on Mac OS X with its default "macosx" backend
12 | import matplotlib.pyplot as plt
13 | import matplotlib.patches as pch
14 |
15 | from lracpa import correlationTraces # my LRA-CPA toolbox
16 |
17 | ##############################################################################
18 | # Parameters
19 |
20 | numByte = 0 # byte to attack, from 0 to 15
21 |
22 | # range for the nubmer of traces to attack (there are 2000 traces)
23 | startTraces = 5 # less than 5 leads to numerical problems in correlation computation
24 | stopTraces = 100
25 | stepTraces = 1
26 |
27 | # range of samples to attack (traces are 2800 samples long)
28 | sampleRange = range(950,1100)
29 |
30 |
31 | ##############################################################################
32 | # Prerequisites
33 |
34 | # the correct key (for later metrics, if any)
35 | correctKey = np.array([0x2B,0x7E,0x15,0x16,0x28,0xAE,0xD2,0xA6,0xAB,0xF7,0x15,0x88,0x09,0xCF,0x4F,0x3C])
36 |
37 | # hamming weight leakage model (pure)
38 | byteHammingWeight = np.load('data/bytehammingweight.npy') # HW table
39 | def leakageModel_HW(x):
40 | return byteHammingWeight[x]
41 |
42 |
43 | ##############################################################################
44 | # Preload and precompute
45 |
46 | # load AES S-Box
47 | sbox = np.load('data/aessbox.npy')
48 |
49 | # load samples and data
50 | npzfile = np.load('traces/swaes_atmega_power.npz')
51 | data = npzfile['data']
52 | traces = npzfile['traces'][:,sampleRange]
53 |
54 | # output traceset parameters
55 | numTraces = traces.shape[0]
56 | traceLength = traces.shape[1]
57 | print "Number of traces: ", numTraces
58 | print "Trace length: ", traceLength
59 |
60 | # compute intermediate variable hypotheses for all the key candidates
61 | k = np.arange(0,256, dtype='uint8')
62 | H = np.zeros((256, len(data)), dtype='uint8')
63 | for i in range(256):
64 | H[i,:] = sbox[data[:, numByte] ^ k[i]]
65 |
66 | # compute leakage hypotheses for every
67 | HL = np.array(map(leakageModel_HW, H)).T # leakage model here can be changed
68 |
69 |
70 | ##############################################################################
71 | # CPA attack (interleaved with incremental plotting, so a bit of a mess)
72 |
73 | ### Graphics stuff
74 | # allocate a line object for every correlation trace and evolution trace
75 | hc = []
76 | he = []
77 | fig, (ax1,ax2) = plt.subplots(1,2, sharey=True)
78 | for i in range(256):
79 | hc.append(ax2.plot([],[], linewidth=2, color='grey')[0])
80 | he.append(ax1.plot([],[], linewidth=2, color='grey')[0])
81 | # put the text label for showing the winning key candidate
82 | ht = plt.text(10, -0.95, "", fontsize=18, fontweight='bold')
83 | ax1.set_ylabel('Correlation', fontsize=18)
84 | ax1.set_xlabel('Number of traces', fontsize=18)
85 | ax2.set_xlabel('Time sample', fontsize=18)
86 | ax1.tick_params(axis='both', which='major', labelsize=18)
87 | ax2.tick_params(axis='both', which='major', labelsize=18)
88 | # show the figure and save the background
89 | ax2.axis([0, traceLength, -1, 1])
90 | ax1.axis([0, stopTraces, -1, 1])
91 | fig.show()
92 | fig.canvas.draw()
93 | for i in range(256):
94 | hc[i].set_xdata(range(1,traceLength+1))
95 |
96 | hp = pch.ConnectionPatch(xyA=(0,0), xyB =(0,0), coordsA='data', axesA=ax2, axesB=ax1, color='black', linestyle='dashed')
97 | ax2.add_artist(hp)
98 |
99 | # main loop; attack and graphics are inevitably interleaved
100 | corrTraces = np.empty([256, traceLength]);
101 | guessedKeyBytePrev = 0
102 | for n in range(startTraces, stopTraces, stepTraces):
103 |
104 | # compute correlation traces, update them in the plot
105 | corrTraces = correlationTraces(traces[0:n], HL[0:n])
106 | for i in range(0, 256):
107 | hc[i].set_ydata(corrTraces[i])
108 | ax1.draw_artist(hc[i])
109 |
110 | # determine the peaks and the most probable key candidate
111 | corrPeaks = np.max(corrTraces, axis=1)
112 | guessedKeyByte = np.argmax(corrPeaks)
113 |
114 | # update highlighting to the current winning key candidate
115 | hc[guessedKeyBytePrev].set_color('grey')
116 | hc[guessedKeyByte].set_color('red')
117 | he[guessedKeyBytePrev].set_color('grey')
118 | he[guessedKeyByte].set_color('red')
119 | guessedKeyBytePrev = guessedKeyByte
120 |
121 | for i in range(0, 256):
122 | he[i].set_xdata(np.append(he[i].get_xdata(), n))
123 | he[i].set_ydata(np.append(he[i].get_ydata(), corrPeaks[i]))
124 | ax1.draw_artist(he[i])
125 |
126 | # update the label
127 | label = "Key 0x%02x, peak %0.4f" % (guessedKeyByte, np.max(corrPeaks))
128 | ht.set_text(label)
129 | ax2.draw_artist(ht)
130 |
131 | # show connecting line between the peak and the evolution plot
132 | hp.xy2 = (n, corrPeaks[guessedKeyByte])
133 | hp.xy1 = (np.argmax(corrTraces[guessedKeyByte]), corrPeaks[guessedKeyByte])
134 | ax2.draw_artist(hp)
135 |
136 | # refresh the plot
137 | # NOTE: no need to use blitting here or otherwise optimize
138 | # we even do not want to be very fast!
139 | fig.canvas.draw()
140 | fig.canvas.flush_events() # crucial: prevents freezing!
141 |
142 | plt.show() # to keep the figure open
143 |
--------------------------------------------------------------------------------
/data/aesinvsbox.npy:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ikizhvatov/pysca/36e136c93e87c2465abc7eeaf66aa030a43e4f1e/data/aesinvsbox.npy
--------------------------------------------------------------------------------
/data/aessbox.npy:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ikizhvatov/pysca/36e136c93e87c2465abc7eeaf66aa030a43e4f1e/data/aessbox.npy
--------------------------------------------------------------------------------
/data/bytehammingweight.npy:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ikizhvatov/pysca/36e136c93e87c2465abc7eeaf66aa030a43e4f1e/data/bytehammingweight.npy
--------------------------------------------------------------------------------
/desutils.py:
--------------------------------------------------------------------------------
1 | '''
2 | This file is part of pysca toolbox, license is GPLv3, see https://www.gnu.org/licenses/gpl-3.0.en.html
3 | Author: Ilya Kizhvatov
4 | Version: 1.0, 2017-05-14
5 |
6 | DES transformations required for DPA with conditional averaging.
7 |
8 | Self-tests included
9 |
10 | Uses minor chunks of code from pyDES-2.0.1 (https://twhiteman.netfirms.com/des.html)
11 | and DPA contest v1 DES example (https://svn.comelec.enst.fr/dpacontest/code/reference/).
12 |
13 | TODO: rewrite in Cython or in C using cyclic shifts and other natural bitwise
14 | operations; look at DES implementation in libtomcrypt as an example.
15 | '''
16 |
17 | from operator import sub
18 |
19 |
20 | ##############################################################################
21 | # Core functionality
22 |
23 | ''' Bit permutations '''
24 | def permuteBits(x, permutation, inputLength):
25 | ''' Permutes bits of x given a permutation table. Assumes that permutation table is 0-offset.
26 | The input bitlength is a parameter
27 | The output bitlength is determined by the permutation table
28 | '''
29 | result = 0L
30 | for i in range(0, len(permutation)):
31 | result = ((result << 1) |
32 | ((x >> (inputLength - 1 - permutation[i])) & 1))
33 | return result
34 |
35 | # These are bit permutaions to be used with permuteBits above,
36 | # not lookup tables.
37 | InitialPermutation = [
38 | 57, 49, 41, 33, 25, 17, 9, 1,
39 | 59, 51, 43, 35, 27, 19, 11, 3,
40 | 61, 53, 45, 37, 29, 21, 13, 5,
41 | 63, 55, 47, 39, 31, 23, 15, 7,
42 | 56, 48, 40, 32, 24, 16, 8, 0,
43 | 58, 50, 42, 34, 26, 18, 10, 2,
44 | 60, 52, 44, 36, 28, 20, 12, 4,
45 | 62, 54, 46, 38, 30, 22, 14, 6
46 | ]
47 | RoundPermutation = [
48 | 15, 6, 19, 20, 28, 11, 27, 16,
49 | 0, 14, 22, 25, 4, 17, 30, 9,
50 | 1, 7, 23, 13, 31, 26, 2, 8,
51 | 18, 12, 29, 5, 21, 10, 3, 24
52 | ]
53 | PC1Permutation = [
54 | 56, 48, 40, 32, 24, 16, 8,
55 | 0, 57, 49, 41, 33, 25, 17,
56 | 9, 1, 58, 50, 42, 34, 26,
57 | 18, 10, 2, 59, 51, 43, 35,
58 | 62, 54, 46, 38, 30, 22, 14,
59 | 6, 61, 53, 45, 37, 29, 21,
60 | 13, 5, 60, 52, 44, 36, 28,
61 | 20, 12, 4, 27, 19, 11, 3
62 | ]
63 | PC2Permutation = [
64 | 13, 16, 10, 23, 0, 4,
65 | 2, 27, 14, 5, 20, 9,
66 | 22, 18, 11, 3, 25, 7,
67 | 15, 6, 26, 19, 12, 1,
68 | 40, 51, 30, 36, 46, 54,
69 | 29, 39, 50, 44, 32, 47,
70 | 43, 48, 38, 55, 33, 52,
71 | 45, 41, 49, 35, 28, 31
72 | ]
73 |
74 | ''' S-box '''
75 | def sBox(m, x):
76 | row = ((x & 0x20) >> 4) ^ (x & 1)
77 | col = (x & 0x1e) >> 1
78 | return SBoxLUT[m][16 * row + col]
79 |
80 | # This is a 6-to-4 bits lookup table. It is not directly
81 | # addressable with S-box input but requires a row-col transform,
82 | # see sBox() above.
83 | SBoxLUT = [
84 | # S1
85 | [14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7,
86 | 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8,
87 | 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0,
88 | 15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13],
89 |
90 | # S2
91 | [15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10,
92 | 3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5,
93 | 0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15,
94 | 13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9],
95 |
96 | # S3
97 | [10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8,
98 | 13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1,
99 | 13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7,
100 | 1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12],
101 |
102 | # S4
103 | [7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15,
104 | 13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9,
105 | 10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4,
106 | 3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14],
107 |
108 | # S5
109 | [2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9,
110 | 14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6,
111 | 4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14,
112 | 11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3],
113 |
114 | # S6
115 | [12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11,
116 | 10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8,
117 | 9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6,
118 | 4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13],
119 |
120 | # S7
121 | [4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1,
122 | 13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6,
123 | 1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2,
124 | 6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12],
125 |
126 | # S8
127 | [13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7,
128 | 1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2,
129 | 7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8,
130 | 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11]
131 | ]
132 |
133 |
134 | ''' Extension permutation, as a list of function per S-box.
135 | x is supposed to be a 32-bit wide integer. If not, function will work
136 | incorrectly.
137 | Calling example: ExtensionPermutationPerSbox[4](x) - retrive the part
138 | of E(x) corresponding to S-box 4'''
139 | ExpansionPerSbox = {
140 | 0 : lambda x : ((x >> 27) | (x << 5)) & 0x3f,
141 | 1 : lambda x : (x >> 23) & 0x3f,
142 | 2 : lambda x : (x >> 19) & 0x3f,
143 | 3 : lambda x : (x >> 15) & 0x3f,
144 | 4 : lambda x : (x >> 11) & 0x3f,
145 | 5 : lambda x : (x >> 7) & 0x3f,
146 | 6 : lambda x : (x >> 3) & 0x3f,
147 | 7 : lambda x : ((x << 1) | (x >> 31)) & 0x3f
148 | }
149 |
150 | '''Inverse P permutation as a list of bit-gathering functions per S-box.
151 | Generated using a helper function below.'''
152 | InversePermutationPerSbox = {
153 | 0 : lambda x : ((x >> 20) & 8) | ((x >> 13) & 4) | ((x >> 8) & 2) | ((x >> 1) & 1),
154 | 1 : lambda x : ((x >> 16) & 8) | ((x >> 2) & 4) | ((x >> 29) & 2) | ((x >> 14) & 1),
155 | 2 : lambda x : ((x >> 5) & 8) | ((x >> 14) & 4) | ((x >> 1) & 2) | ((x >> 26) & 1),
156 | 3 : lambda x : ((x >> 3) & 8) | ((x >> 10) & 4) | ((x >> 21) & 2) | ((x >> 31) & 1),
157 | 4 : lambda x : ((x >> 21) & 8) | ((x >> 16) & 4) | ((x >> 6) & 2) | ((x >> 29) & 1),
158 | 5 : lambda x : ((x >> 25) & 8) | ((x >> 1) & 4) | ((x >> 20) & 2) | ((x >> 13) & 1),
159 | 6 : lambda x : ((x << 3) & 8) | ((x >> 18) & 4) | ((x >> 9) & 2) | ((x >> 25) & 1),
160 | 7 : lambda x : ((x >> 24) & 8) | ((x >> 3) & 4) | ((x >> 16) & 2) | ((x >> 11) & 1)
161 | }
162 |
163 | ''' Key expansion '''
164 | def computeRoundKeys(key, numberOfRounds):
165 |
166 | keyShifts = [1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1]
167 | mask28 = 0xfffffff
168 |
169 | # rotate left modulo 28 bits
170 | rol28 = lambda x, n: ((x << n) & mask28) | ((x & mask28) >> (28 - n))
171 |
172 | permutedKey = permuteBits(key, PC1Permutation, 64)
173 |
174 | l = (permutedKey >> 28) & mask28
175 | r = permutedKey & mask28
176 |
177 | roundKeys = []
178 | for i in range(numberOfRounds):
179 | l = rol28(l, keyShifts[i])
180 | r = rol28(r, keyShifts[i])
181 | lr = (l << 28) ^ r
182 | roundKey = permuteBits(lr, PC2Permutation, 56)
183 | roundKeys.append(roundKey)
184 |
185 | return roundKeys
186 |
187 | ''' Return n-th 6-bit chunk of the 48-bit round key '''
188 | def roundKeyChunk(roundKey, n):
189 | return (roundKey >> (42 - 6 * n)) & 0x3f
190 |
191 |
192 | ##############################################################################
193 | # Tandem of functions for round in xor out intermediate. First functions
194 | # obtains value for conditional averaging. Second function obtains the value
195 | # of the target variable from that
196 |
197 | def roundXOR_valueForAveraging(input, sBoxNumber):
198 | ''' Compute the value for conditional averaging from input, for a given
199 | S-box number '''
200 |
201 | # prepare the first round input halves
202 | permutedInput = permuteBits(input, InitialPermutation, 64)
203 | rightHalf = permutedInput & 0xFFFFFFFF
204 | leftHalf = permutedInput >> 32
205 |
206 | # 1. get 6-bit first part: the input chunks per S-box based on the structre value
207 | # 2. get 4-bit second part: the bits from XOR of left and right input
208 | # 3. concatenate to 10-bit value
209 | # TODO: consider a structure instead of concatenation
210 | a = ExpansionPerSbox[sBoxNumber](rightHalf)
211 | b = InversePermutationPerSbox[sBoxNumber](rightHalf ^ leftHalf)
212 | r = (a << 4) | b
213 |
214 | return r
215 |
216 | def roundXOR_targetVariable(averagingValue, keyChunk, sBoxNumber):
217 | ''' Compute the intermediate variable the value used for from key chunk,
218 | for a given S-box number '''
219 |
220 | # unpack the value
221 | x = (averagingValue >> 4) & 0x3f
222 | y = averagingValue & 0xf
223 |
224 | # compute the intermediate value
225 | SBoxIn = x ^ keyChunk
226 | SBoxOut = sBox(sBoxNumber, SBoxIn)
227 | RoundInXorOutPerSBox = SBoxOut ^ y
228 |
229 | return RoundInXorOutPerSBox
230 |
231 | # Both merged into none, for attack without conditional averaging
232 | def roundXOR_allInOne(input, keyChunk, sBoxNumber):
233 |
234 | # prepare the first round input halves
235 | permutedInput = permuteBits(input, InitialPermutation, 64)
236 | rightHalf = permutedInput & 0xFFFFFFFF
237 | leftHalf = permutedInput >> 32
238 |
239 | # get S-box output
240 | a = ExpansionPerSbox[sBoxNumber](rightHalf) # returns 6 bits of S-box input
241 | SBoxIn = a ^ keyChunk
242 | SBoxOut = sBox(sBoxNumber, SBoxIn)
243 |
244 | # gather the input bits that need to be XORed with the S-box output
245 | b = InversePermutationPerSbox[sBoxNumber](rightHalf ^ leftHalf)
246 |
247 | # compute the XOR
248 | RoundInXorOutPerSBox = SBoxOut ^ b
249 |
250 | return RoundInXorOutPerSBox
251 |
252 |
253 | ##############################################################################
254 | # Self-creators
255 |
256 | def generateInversePermutationPerSbox():
257 | ''' Helper used to generate the shifts. In the output, negative values should be manually replaced by a left shift! '''
258 | print '\n--- generateInversePermutationPerSbox ---'
259 |
260 | initialPositionsPerSbox = [
261 | [ 8, 16, 22, 30],
262 | [12, 27, 1, 17],
263 | [23, 15, 29, 5],
264 | [25, 19, 9, 0],
265 | [ 7, 13, 24, 2],
266 | [ 3, 28, 10, 18],
267 | [31, 11, 21, 6],
268 | [ 4, 26, 14, 20]
269 | ]
270 | finalPositions = [28, 29, 30, 31]
271 |
272 | for group in initialPositionsPerSbox:
273 | shifts = map(sub, finalPositions, group) # element-wise list subtraction
274 | print "((x >> %d) & 8) | ((x >> %d) & 4) | ((x >> %d) & 2) | ((x >> %d) & 1)" % (shifts[0], shifts[1], shifts[2], shifts[3])
275 |
276 |
277 | ##############################################################################
278 | # Self-tests
279 |
280 | def testDesUtilities():
281 | ''' Dump the state of the first round to compare against a reference implementation.
282 | Compare the inverse round permutation against the forward one.
283 | The output should look like:
284 |
285 | --- testDesUtilites ---
286 | L : 0x59e0bc92L
287 | R : 0xa69230c8L
288 | RK0: 0x8805bc20c812L
289 | Rt : 0x50d4a41a1651L
290 | Rtk: 0xd8d1183ade43L
291 | z : 0x789b6fef
292 | zp : 0x9c7eafebL
293 | Testing the inverse permutation
294 | z' : 0x789b6fefL
295 | Success!
296 | '''
297 | print '\n--- testDesUtilites ---'
298 |
299 | # data from the first trace in TC8 PA training traceset
300 | key = 0x8a7400a03230da28L
301 | plaintext = 0x40a184466d9c52b7L
302 | ciphertext = 0x1cb5ca37b8a7a388L
303 |
304 | # key schedule
305 | roundKeys = computeRoundKeys(key, 16)
306 | k = roundKeys[0]
307 |
308 | # prepare the first round input halves (checked)
309 | permutedInput = permuteBits(plaintext, InitialPermutation, 64)
310 | rightHalf = permutedInput & 0xFFFFFFFF
311 | leftHalf = permutedInput >> 32
312 | print 'L : ' + hex(leftHalf)
313 | print 'R : ' + hex(rightHalf)
314 | print 'RK0: ' + hex(k)
315 |
316 | # expansion (checked)
317 | Rt = 0L
318 | for i in range(0, 8):
319 | a = ExpansionPerSbox[i](rightHalf)
320 | Rt = (Rt << 6) ^ a;
321 | print 'Rt : ' + hex(Rt)
322 |
323 | # key addition
324 | Rt = Rt ^ k
325 | print 'Rtk: ' + hex(Rt)
326 |
327 | # S-boxes
328 | z = 0L
329 | for i in range(0, 8):
330 | z ^= (sBox(7 - i, Rt & 0x3f) << (i * 4))
331 | Rt = Rt >> 6
332 | print 'z : ' + hex(z)
333 |
334 | # permutation
335 | zp = permuteBits(z, RoundPermutation, 32)
336 | print 'zp : ' + hex(zp)
337 |
338 | # testing the inverse permutation
339 | print 'Testing the inverse permutation'
340 | zb = 0L
341 | for i in range(0, 8):
342 | zb ^= InversePermutationPerSbox[i](zp) << ((7 - i) * 4)
343 | print "z' : " + hex(zb)
344 | if (zb == z):
345 | print 'Success!'
346 | else:
347 | print 'Fail!'
348 |
349 |
350 | def dumpRoundKeys():
351 | ''' Dump all round keys '''
352 | print '\n--- dumpRoundKeys ---'
353 |
354 | key = 0x8a7400a03230da28L
355 | roundKeys = computeRoundKeys(key, 16)
356 | print 'Key : ' + format(key, '#018x')
357 | for i in range(16):
358 | print 'RK' + format(i, '02d') + ' : ' + format(roundKeys[i], '#014x'),
359 | print '[',
360 | for j in range(8):
361 | print format(roundKeyChunk(roundKeys[i], j), '#04x'),
362 | print ']'
363 |
364 | def dumpMiscValues():
365 | ''' Print out the values, just in case '''
366 | print '\n--- dumpMiscValues ---'
367 |
368 | Input = 0xA76DB873C63FE078
369 | KeyChunk = 0x2B
370 | print "Input:", hex(Input)
371 | print "Key chunk:", hex(KeyChunk)
372 |
373 | print "Values for averaging and target variables:"
374 | for i in range(0, 8):
375 | r = roundXOR_valueForAveraging(Input, i)
376 | t = roundXOR_targetVariable(r, KeyChunk, i)
377 | print "0x%04x, 0x%04x" % (r, t)
378 |
379 | print "Initial permutation"
380 | print hex(permuteBits(Input, InitialPermutation, 64))
381 |
382 | RightHalf = Input & 0xFFFFFFFF
383 |
384 | print "Expansion per S-box:",
385 | print hex(ExpansionPerSbox[0](RightHalf)),
386 | print hex(ExpansionPerSbox[1](RightHalf)),
387 | print hex(ExpansionPerSbox[2](RightHalf)),
388 | print hex(ExpansionPerSbox[3](RightHalf)),
389 | print hex(ExpansionPerSbox[4](RightHalf)),
390 | print hex(ExpansionPerSbox[5](RightHalf)),
391 | print hex(ExpansionPerSbox[6](RightHalf)),
392 | print hex(ExpansionPerSbox[7](RightHalf))
393 |
394 | print "Inverse permutation per S-box:",
395 | print hex(InversePermutationPerSbox[0](RightHalf)),
396 | print hex(InversePermutationPerSbox[1](RightHalf)),
397 | print hex(InversePermutationPerSbox[2](RightHalf)),
398 | print hex(InversePermutationPerSbox[3](RightHalf)),
399 | print hex(InversePermutationPerSbox[4](RightHalf)),
400 | print hex(InversePermutationPerSbox[5](RightHalf)),
401 | print hex(InversePermutationPerSbox[6](RightHalf)),
402 | print hex(InversePermutationPerSbox[7](RightHalf))
403 |
404 |
405 | ##############################################################################
406 | # Entrypoint for self-testing
407 |
408 | if __name__ == "__main__":
409 | testDesUtilities()
410 | dumpRoundKeys()
411 | dumpMiscValues()
412 | generateInversePermutationPerSbox()
413 |
--------------------------------------------------------------------------------
/howto/HOWTO.md:
--------------------------------------------------------------------------------
1 | # Pysca toolbox HOWTO
2 |
3 | This is a walkthrough showing how to put pysca in action with the provided example tracesets. It does not go deep under the hood; if you like that, the best way is to dive into the code starting from the scripts used here.
4 |
5 | ## Environment setup
6 |
7 | Pysca needs python 2.7 with numpy and matplotlib, and jupyter if you like to work with notebook format in a browser. Here is how to create a minimal environment for pysca with Anaconda python distribution in Linux and activate it:
8 |
9 | elbrus:pysca ilya$ conda create --name py27min python=2.7 numpy matplotlib jupyter
10 | [... all the conda printouts will be here ..]
11 | elbrus:pysca ilya$ source activate py27min
12 | (py27min) elbrus:pysca ilya$
13 |
14 | Note that Anaconda provides numpy built against Intel MKL (Math Kernel Library), which is essential for performance. If you use other python dstribution, ensure that you use numpy-MKL.
15 |
16 | ## Traceset conversion
17 |
18 | Convert an example set of power traces obtained from a software AES running on an ATmega microcontroller.
19 |
20 | (py27min) elbrus:pysca ilya$ python trs2npz.py traces\swaes_atmega_power
21 | Number of traces: 2000
22 | Samples per trace: 2800
23 | Samples datatype: int8
24 | Data bytes: 16
25 | Trace block size:
26 | Header size:
27 | Preallocating arrays
28 | Populating arrays
29 | Saving file
30 | Done
31 |
32 | ## CPA and LRA attacks on SW AES
33 |
34 | For this example we will use the commad line script. Execute the script that performs the attacks, recovering a single key byte.
35 |
36 | (py27min) elbrus:pysca ilya$ attackaessbox.py
37 | ---
38 | Attack parameters
39 | Intermediate function : sBoxOut
40 | CPA leakage function : leakageModelHW
41 | LRA basis functions : basisModelSingleBits
42 | Encryption : True
43 | S-box number : 2
44 | Known key : 0x2b7e151628aed2a6abf7158809cf4f3c
45 | Known roundkey : 0x2b7e151628aed2a6abf7158809cf4f3c
46 | ---
47 | Loading traces/swaes_atmega_power.npz
48 | Number of traces loaded : 100
49 | Trace length : 700
50 | Loading time : 0.03 s
51 | ---
52 | Attack
53 | ConditionalAverager: initialized for 256 values and trace length 700
54 | ---
55 | Results after 20 traces
56 | CPA
57 | Winning candidate: 0xd3, peak magnitude 0.827157
58 | Correct candidate: 0x15, peak magnitude 0.748879, rank 22
59 | LRA
60 | Winning candidate: 0x7d, peak magnitude 0.951581
61 | Correct candidate: 0x15, peak magnitude 0.884216, rank 50
62 | ---
63 | [...]
64 | Results after 100 traces
65 | CPA
66 | Winning candidate: 0x15, peak magnitude 0.481228
67 | Correct candidate: 0x15, peak magnitude 0.481228, rank 1
68 | LRA
69 | Winning candidate: 0x15, peak magnitude 0.512743
70 | Correct candidate: 0x15, peak magnitude 0.512743, rank 1
71 | ---
72 | Cumulative timing
73 | 24.56 s
74 | ---
75 | Plotting...
76 |
77 | Observe the result visualization. The plots show results of CPA (correlation traces) and LRA (R2 traces and matrix of basis fucntion coefficients characterising the leakage function) for the maximum amonut of traces, and evolution of the correct key candidate rank with the increasing amount of traces.
78 |
79 |
80 |
81 | The parameters of the attack can be adjusted in the configuration section of the script.
82 |
83 | ## CPA and LRA attack on HW DES
84 |
85 | For this example, we will use another (convenient) way to work: a Jupyter noteboook in a browser. Launch the notebook server:
86 |
87 | (py27min) elbrus:pysca ilya$ jupyter notebook
88 | [I 13:15:38.823 NotebookApp] Serving notebooks from local directory: /Users/ilya/pysca
89 | [I 13:15:38.823 NotebookApp] 0 active kernels
90 | [I 13:15:38.824 NotebookApp] The Jupyter Notebook is running at: http://localhost:8888/?token=a75f5aa53be646d4a96bedc760728c9baea3a3a72b9111be
91 | [I 13:15:38.824 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
92 |
93 | You will see the browser popping up with the directory contents, with two .ipynb notebooks.
94 |
95 |
96 |
97 | Open the notebook with the attack on DES round XOR.
98 |
99 |
100 |
101 | The code in the notebook is arranged in cells. Here is the cell with attack settings:
102 |
103 |
104 |
105 | The example traceset comes in npz format. Execute cells one-by-one and get an attack result plot in-line.
106 |
107 |
108 |
109 | This is the instantaneous attack result. To see the evolution, you can proceed with the following cells.
110 |
111 | This is it so far for the basics.
112 |
--------------------------------------------------------------------------------
/howto/howto-notebook-des-result.png:
--------------------------------------------------------------------------------
1 | version https://git-lfs.github.com/spec/v1
2 | oid sha256:7eff88206ab3739f9e481125c7ded913a6ed4a43b35bedaf660280221fa10cab
3 | size 193420
4 |
--------------------------------------------------------------------------------
/howto/howto-notebook-des-settings.png:
--------------------------------------------------------------------------------
1 | version https://git-lfs.github.com/spec/v1
2 | oid sha256:90a2a2f314d0196eb11a5079af5985fe3880f3ddd744f83433a17b4cab16cf6a
3 | size 247090
4 |
--------------------------------------------------------------------------------
/howto/howto-notebook-des.png:
--------------------------------------------------------------------------------
1 | version https://git-lfs.github.com/spec/v1
2 | oid sha256:677a9713e893fb7a93f3cce3a0b447af8bef040056affa7c69ccc18a2f6ec640
3 | size 208744
4 |
--------------------------------------------------------------------------------
/howto/howto-notebooks.png:
--------------------------------------------------------------------------------
1 | version https://git-lfs.github.com/spec/v1
2 | oid sha256:87667d694141dffc519ec10176924ad828b26ab8f17ff7209540a3f853c97886
3 | size 103662
4 |
--------------------------------------------------------------------------------
/howto/howto-script-aes-result.png:
--------------------------------------------------------------------------------
1 | version https://git-lfs.github.com/spec/v1
2 | oid sha256:88abce3231c1903583727eb9bf756d2abbd9373ae532277666eca26e9b5e420d
3 | size 144628
4 |
--------------------------------------------------------------------------------
/lracpa.py:
--------------------------------------------------------------------------------
1 | '''
2 | This file is part of pysca toolbox, license is GPLv3, see https://www.gnu.org/licenses/gpl-3.0.en.html
3 | Author: Ilya Kizhvatov
4 | Version: 1.0, 2017-05-14
5 |
6 | This file is a library of functions for CPA and LRA. The attacks are supposed to be
7 | implemented as scripts importing this library.
8 |
9 | AES S-box output and DES per-S-box round XOR are supported as target variables.
10 |
11 | Leakage functions for CPA and basis function models for LRA are defiend here as well.
12 |
13 | Non-profiled LRA is implemented a la ASIACRYPT'13 paper [https://eprint.iacr.org/2013/794].
14 | Implementation uses manual OLS (dot-products and matrix inversion, relying on numpy-MKL
15 | efficient implementation).
16 | '''
17 |
18 | import numpy as np
19 |
20 | # preload the precomputed lookup tables, to avoid bloating of this code
21 | sbox = np.load('data/aessbox.npy') # AES S-box
22 | invsbox = np.load('data/aesinvsbox.npy') # AES inverse S-box
23 | byteHammingWeight = np.load('data/bytehammingweight.npy') # HW of a byte
24 |
25 |
26 | #############################################################################
27 | ### Common for both attacks
28 |
29 | # Functions for computing intermediate values
30 | # data is a 1-D array, keyByte is a scalar
31 | def sBoxOut(data, keyByte):
32 | sBoxIn = data ^ keyByte
33 | return sbox[sBoxIn]
34 | def sBoxInXorOut(data, keyByte):
35 | sBoxIn = data ^ keyByte
36 | return sBoxIn ^ sbox[sBoxIn]
37 | def invSboxOut(data, keyByte):
38 | sBoxIn = data ^ keyByte
39 | return invsbox[sBoxIn]
40 | def invSboxInXorOut(data, keyByte):
41 | sBoxIn = data ^ keyByte
42 | return sBoxIn ^ invsbox[sBoxIn]
43 |
44 | ##############################################################################
45 | ### A. LRA attack stuff
46 |
47 | ### Leakge modelling
48 | # These functions do 2 things in the same place:
49 | # 1. define basis functions gi(x) of a leakage model for a byte x:
50 | # b0 x g0(x) + b1 x g1(x) + ... + bn x gn(x)
51 | # 2. compute and return the values of gi(x), such that they can be used
52 | # later to obtain rows of the matrix for linear regression
53 | # Note that column of ones is included!
54 | # Note also that not all the functions are currently compatible with the code
55 | # in the CPA and LRA functions because latter use wrapper functions for
56 | # incremental binding. Only those are compatible that take a second bitWidth
57 | # argument.
58 | # TODO: make all functions compatible with incremental binding.
59 |
60 |
61 | # A simple linear model - sum of bits with different coefficients:
62 | # gi = xi, 0 <= i < bitWidth.
63 | def basisModelSingleBits(x, bitWidth):
64 | g = []
65 | for i in range(0, bitWidth):
66 | bit = (x >> i) & 1 # this is the definition: gi = [bit i of x]
67 | g.append(bit)
68 | g.append(1)
69 | return g
70 |
71 | # Invididual bits and all pairwise products of bits
72 | def basisModelSingleBitsAndPairs(x, bitWidth):
73 | g = []
74 | for i in range(0, bitWidth):
75 | # append single bits
76 | bit = (x >> i) & 1 # this is the definition: gi = [bit i of x]
77 | g.append(bit)
78 | # append pairs
79 | for j in range(i + 1, bitWidth):
80 | otherbit = (x >> j) & 1
81 | bitproduct = bit * otherbit
82 | g.append(bitproduct)
83 | g.append(1)
84 | return g
85 |
86 | # A Hamming weight model: g0 = HW(x)
87 | def basisModelHW(x):
88 | g = []
89 | hw = byteHammingWeight[x] # this is the definition: gi = HW(x)
90 | g.append(hw)
91 | g.append(1)
92 | return g
93 |
94 | # An 'all 256 bit combinations' model:
95 | # a) helper from http://wiki.python.org/moin/BitManipulation
96 | def parityOf(int_type):
97 | parity = 0
98 | while (int_type):
99 | parity = ~parity
100 | int_type = int_type & (int_type - 1)
101 | if (parity != 0): # to convert -1 to 1
102 | parity = 1
103 | return(parity)
104 | # b) the model itself
105 | def basisModel256(x):
106 | g = []
107 | # note that we start from 1 to exclude case 0 which means the function
108 | # does not depend on any bit of x, i.e. a constant - we will add the
109 | # constant explicitly later as the last column.
110 | for i in np.arange(1, 256, dtype='uint8'):
111 | xmasked = x & i
112 | gi = parityOf(xmasked)
113 | g.append(gi)
114 | g.append(1)
115 | return g
116 |
117 | # LRA attack on AES
118 | # data - 1-D array of input bytes
119 | # traces - 2-D array of traces
120 | # intermediateFunction - one of the functions like sBoxOut above in the common section
121 | # basisFunctionsModel - one of the functions like basisModelSingleBits above
122 | # in this section
123 | # TODO parametrize hard-coded values such as 256, 8
124 | def lraAES(data, traces, intermediateFunction, basisFunctionsModel):
125 |
126 | ### 0. some helper variables
127 | (numTraces, traceLength) = traces.shape
128 |
129 | # define a wrapper for currying (incremental parameter binding)
130 | def basisFunctionsModelWrapper(y):
131 | def basisFunctionsModelCurry(x):
132 | return basisFunctionsModel(x, y)
133 | return basisFunctionsModelCurry
134 |
135 | ### 1: compute SST over the traces
136 | SStot = np.sum((traces - np.mean(traces, 0)) ** 2, 0)
137 |
138 | ### 2. The main attack loop
139 |
140 | # preallocate arrays
141 | SSreg = np.empty((256, traceLength)) # Sum of Squares due to regression
142 | E = np.empty(numTraces) # expected values
143 |
144 | allCoefs = [] # placeholder for regression coefficients
145 |
146 | # per-keycandidate loop
147 | for k in np.arange(0, 256, dtype='uint8'):
148 |
149 | # predict intermediate variable
150 | intermediateVariable = intermediateFunction(data, k)
151 |
152 | # buld equation system
153 | M = np.array(map(basisFunctionsModelWrapper(8), intermediateVariable))
154 |
155 | # some precomputations before the per-sample loop
156 | P = np.dot(np.linalg.inv(np.dot(M.T, M)), M.T)
157 | #Q = np.dot(M, P)
158 |
159 | coefs = [] # placeholder for regression coefficients
160 |
161 | # per-sample loop: solve the system for each time moment
162 | for u in range(0,traceLength):
163 |
164 | # if do not need coefficients beta - use precomputed value
165 | #np.dot(Q, traces[:,u], out=E)
166 |
167 | # if need the coefficients - do the multiplication using
168 | # two dot products and let the functuion return beta alongside R2
169 | beta = np.dot(P, traces[:,u])
170 | coefs.append(beta)
171 | E = np.dot(M, beta)
172 |
173 | SSreg[k,u] = np.sum((E - traces[:,u]) ** 2)
174 |
175 | allCoefs.append(coefs)
176 | #print 'Done with candidate', k
177 |
178 | ### 3. compute Rsquared
179 | R2 = 1 - SSreg / SStot[None, :]
180 |
181 | return R2, allCoefs
182 |
183 | # LRA attack on DES
184 | # data - array of inputs (format depends on intermediateFunction)
185 | # traces - 2-D array of traces
186 | # intermediateFunction - one of functions like sBoxOut above in the common section
187 | # sBoxNumber - DES S-box to attack
188 | # basisFunctionsModel - one of function like basisModel9 above in this section
189 | # TODO parametrize hard-coded values such as 64, 6, refactor to merge common part with AES
190 | def lraDES(data, traces, intermediateFunction, sBoxNumber, basisFunctionsModel):
191 |
192 | ### 0. some helper variables
193 | (numTraces, traceLength) = traces.shape
194 |
195 | # define a wrapper (currying) for incremental parameter binding
196 | def basisFunctionsModelWrapper(y):
197 | def basisFunctionsModelCurry(x):
198 | return basisFunctionsModel(x, y)
199 | return basisFunctionsModelCurry
200 |
201 | ### 1: compute SST over the traces
202 | SStot = np.sum((traces - np.mean(traces, 0)) ** 2, 0)
203 |
204 | ### 2. The main attack loop
205 |
206 | # preallocate arrays
207 | SSreg = np.empty((64, traceLength)) # Sum of Squares due to regression
208 | E = np.empty(numTraces) # expected values
209 |
210 | allCoefs = [] # placeholder for regression coefficient
211 |
212 | # per-keycandidate loop
213 | for k in np.arange(0, 64, dtype='uint8'):
214 |
215 | # predict intermediate variable for the current key candiate value
216 | intermediateVariable = np.zeros(len(data), dtype='uint8')
217 | for j in range(0, len(data)):
218 | intermediateVariable[j] = intermediateFunction(data[j], k, sBoxNumber)
219 |
220 | # buld equation system
221 | M = np.array(map(basisFunctionsModelWrapper(4), intermediateVariable))
222 |
223 | # some precomputations before the per-sample loop
224 | P = np.dot(np.linalg.inv(np.dot(M.T, M)), M.T)
225 | #Q = np.dot(M, P)
226 |
227 | coefs = [] # placeholder for regression coefficients
228 |
229 | # per-sample loop: solve the system for each time moment
230 | for u in range(0,traceLength):
231 |
232 | # if do not need coefficients beta - use precomputed value
233 | #np.dot(Q, traces[:,u], out=E)
234 |
235 | # if need the coefficients - do the multiplication using
236 | # two dot products and let the functuion return beta alongside R2
237 | beta = np.dot(P, traces[:,u])
238 | coefs.append(beta)
239 | E = np.dot(M, beta)
240 |
241 | SSreg[k,u] = np.sum((E - traces[:,u]) ** 2)
242 |
243 | allCoefs.append(coefs)
244 | #print 'Done with candidate', k
245 |
246 | ### 3. compute Rsquared
247 | R2 = 1 - SSreg / SStot[None, :]
248 |
249 | return R2, allCoefs
250 |
251 | # convert R2 to adjusted R2 (https://en.wikipedia.org/wiki/Coefficient_of_determination#Adjusted_R2)
252 | # n - number of samples
253 | # p - the total number of regressors in the linear model (i.e. basis functions), excluding the linear term
254 | def adjustedR2(R2, n, p):
255 | R2adj = 1 - ((1 - R2 ** 2) * (n - 1) / np.double(n - p - 1))
256 | return R2adj
257 |
258 | # normalize the matrix of distinguisher traces according to ASIACRYPT'13 proposal
259 | def normalizeR2Traces(R2):
260 | R2norm = np.empty(R2.shape)
261 | traceLength = R2.shape[1]
262 | for i in range(0,traceLength): # TODO should be possible to do it in one line without a loop
263 | R2norm[:,i] = (R2[:,i] - np.mean(R2[:,i])) / np.var(R2[:,i])
264 | return R2norm
265 |
266 | ##############################################################################
267 | ### A. CPA attack stuff
268 |
269 | def leakageModelHW(x):
270 | return byteHammingWeight[x]
271 |
272 | # correlation trace computation as improved by StackOverflow community
273 | # O - matrix of observed leakage (i.e. traces)
274 | # P - column of predictions
275 | # returns a correlation trace
276 | def correlationTraceSO(O, P):
277 | n = P.size
278 | DO = O - (np.einsum('ij->j', O, dtype='float64', optimize='optimal') / np.double(n))
279 | DP = P - (np.einsum('i->', P, dtype='float64', optimize='optimal') / np.double(n))
280 | tmp = np.einsum('ij,ij->j', DO, DO, optimize='optimal')
281 | tmp *= np.einsum('i,i->', DP, DP, optimize='optimal')
282 | return np.dot(DP, DO) / np.sqrt(tmp)
283 |
284 | # Even faster correlation trace computation
285 | # Takes the full matrix of predictions instead of just a column
286 | # O - (n,t) array of n traces with t samples each
287 | # P - (n,m) array of n predictions for each of the m candidates
288 | # returns an (m,t) correaltion matrix of m traces t samples each
289 | def correlationTraces(O, P):
290 | (n, t) = O.shape # n traces of t samples
291 | (n_bis, m) = P.shape # n predictions for each of m candidates
292 |
293 | DO = O - (np.einsum("nt->t", O, dtype='float64', optimize='optimal') / np.double(n)) # compute O - mean(O)
294 | DP = P - (np.einsum("nm->m", P, dtype='float64', optimize='optimal') / np.double(n)) # compute P - mean(P)
295 |
296 | numerator = np.einsum("nm,nt->mt", DP, DO, optimize='optimal')
297 | tmp1 = np.einsum("nm,nm->m", DP, DP, optimize='optimal')
298 | tmp2 = np.einsum("nt,nt->t", DO, DO, optimize='optimal')
299 | tmp = np.einsum("m,t->mt", tmp1, tmp2, optimize='optimal')
300 | denominator = np.sqrt(tmp)
301 |
302 | return numerator / denominator
303 |
304 | # CPA attack
305 | # data - 1-D array of input bytes
306 | # traces - 2-D array of traces
307 | # intermediateFunction - one of functions like sBoxOut above in the common section
308 | # leakageFunction - one of the fucntions like leakgeModelHW above in this section
309 | def cpaAES(data, traces, intermediateFunction, leakageFunction):
310 |
311 | traceLength = traces.shape[1]
312 |
313 | # compute intermediate variable predictions
314 | k = np.arange(0,256, dtype='uint8') # key chunk candidates
315 | H = np.zeros((256, len(data)), dtype='uint8') # intermediate variable predictions
316 | for i in range(256):
317 | H[i,:] = intermediateFunction(data, k[i])
318 |
319 | # compute leakage hypotheses for every all the key candidates
320 | HL = np.array(map(leakageFunction, H)).T # leakage model here (HW for now)
321 |
322 | CorrTraces = correlationTraces(traces, HL)
323 |
324 | return CorrTraces
325 |
326 | # CPA attack on DES
327 | # data - array of inputs (format depends on intermediateFunction)
328 | # traces - 2-D array of traces
329 | # intermediateFunction - one of functions like sBoxOut above in the common section
330 | # sBoxNumber - DES S-box to attack
331 | # leakageFunction - one of the fucntions like leakageModelHW above in this section
332 | def cpaDES(data, traces, intermediateFunction, sBoxNumber, leakageFunction):
333 |
334 | traceLength = traces.shape[1]
335 |
336 | # compute intermediate variable predictions
337 | k = np.arange(0,64, dtype='uint8') # key chunk candidates
338 | H = np.zeros((64, len(data)), dtype='uint8') # intermediate variable predictions
339 | for i in range(64):
340 | for j in range(0, len(data)):
341 | H[i,j] = intermediateFunction(data[j], k[i], sBoxNumber)
342 |
343 | # compute leakage hypotheses for every all the key candidates
344 | HL = np.array(map(leakageFunction, H)).T # leakage model here (HW for now)
345 |
346 | CorrTraces = correlationTraces(traces, HL)
347 |
348 | return CorrTraces
349 |
--------------------------------------------------------------------------------
/results/attackaessbox_test.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ikizhvatov/pysca/36e136c93e87c2465abc7eeaf66aa030a43e4f1e/results/attackaessbox_test.png
--------------------------------------------------------------------------------
/results/attackaessbox_test.txt:
--------------------------------------------------------------------------------
1 | In [104]: %run attackaessbox.py
2 | ---
3 | Attack parameters
4 | Intermediate function : sBoxOut
5 | CPA leakage function : leakageModelHW
6 | LRA basis functions : basisModel9
7 | Encryption : True
8 | S-box number : 1
9 | Known roundkey : 0x2b7e151628aed2a6abf7158809cf4f3c
10 | ---
11 | Loading traces/swaes_atmega_powertraces.npz
12 | Number of traces loaded : 20
13 | Trace length : 2800
14 | Loading time : 0.01 s
15 | ---
16 | Attack
17 | Performing conditional trace averaging... done in 0.00 s
18 | Running CPA on averaged traces... done in 0.07 s
19 | Running LRA on averaged traces... done in 9.47 s
20 | ---
21 | Results CPA
22 | Winning candidate: 0x20, peak magnitude 0.809684
23 | Correct candidate: 0x7e, peak magnitude 0.750731, rank 22
24 | ---
25 | Results LRA
26 | Winning candidate: 0xfa, peak magnitude 0.964337
27 | Correct candidate: 0x7e, peak magnitude 0.892681, rank 123
28 | ---
29 | Plotting...
--------------------------------------------------------------------------------
/results/performance_logs.txt:
--------------------------------------------------------------------------------
1 | The following results were obtained on an Intel Core i5-2540M, 8GB RAM,
2 | Windows 7 x64, Python 2.7.8 x64, numpy-MKL 1.9.0.
3 |
4 | ----------------------
5 | swaes_atmega_powertraces.trs
6 |
7 | In [3]: %run lra
8 | Traceset parameters
9 | Number of traces: 2000
10 | Trace length: 200
11 | ---
12 | Attacks with 1000 traces:
13 | Running CPA... done in 0.349224 s
14 | Running LRA... done in 37.254000 s
15 | Normalizing LRA results... done
16 | ---
17 | Attacks with 1000 traces and conditional averaging:
18 | Performing conditional trace averaging... done in 0.003820 s
19 | Running CPA on averaged traces... done in 0.057802 s
20 | Running LRA on averaged traces... done in 3.997455 s
21 | Normalizing LRA results... done
22 | ---
23 | Plotting...
24 |
25 | Speedup factor CPA: 5.67
26 | Speedup factor LRA: 9.3
27 |
28 | ----------------------
29 | swaes_atmega_powertraces2_compressed.trs
30 |
31 | In [35]: %run lracpa_swaes.py
32 | Traceset parameters
33 | Number of traces: 10000
34 | Trace length: 274
35 | ---
36 | Attacks with 10000 traces
37 | Running CPA... done in 6.400619 s
38 | Running LRA... done in 3439.946043 s
39 | Normalizing LRA results... done
40 | ---
41 | Attacks with 10000 traces and conditional averaging
42 | Performing conditional trace averaging... done in 0.120957 s
43 | Running CPA on averaged traces... done in 0.086983 s
44 | Running LRA on averaged traces... done in 4.831128 s
45 | Normalizing LRA results... done
46 | ---
47 | Plotting...
48 |
49 | Speedup factor CPA: 30.78
50 | Speedup factor LRA: 694.64
51 |
52 |
53 | ----------------------
54 | This one on the new lab machine (file was opened not the frist time so cached)
55 | ----------------------
56 | In [14]: %run lracpa_swaes.py
57 | Loadingtraces/hwaes_xxx_winres_trimtrim940-100.npz
58 | Traceset parameters
59 | Number of traces: 7798433
60 | Trace length: 100
61 | Loading time: 6.67022741521
62 | ---
63 | Attacks with 7798433 traces and conditional averaging
64 | Performing conditional trace averaging... done in 76.101671 s
65 | Running CPA on averaged traces... done in 0.083418 s
66 | Running LRA on averaged traces... done in 3.642333 s
67 | Normalizing LRA results... done
68 | ---
69 | Plotting...
70 |
71 | -----------------------------
72 | And the same for the laptop (file cached as well)
73 | See the effect of a faster single-core operation
74 | -----------------------------
75 | In [2]: %run lracpa_swaes.py
76 | Loading traces/hwaes_xxx_winres_trimtrim940-100.npz
77 | Traceset parameters
78 | Number of traces: 7798433
79 | Trace length: 100
80 | Loading time: 8.26878899541
81 | ---
82 | Attacks with 7798433 traces and conditional averaging
83 | Performing conditional trace averaging... done in 61.314245 s
84 | Running CPA on averaged traces... done in 0.032915 s
85 | Running LRA on averaged traces... done in 2.942761 s
86 | Normalizing LRA results... done
87 | ---
88 | Plotting...
--------------------------------------------------------------------------------
/results/performance_logs_bis.txt:
--------------------------------------------------------------------------------
1 | compareperformance.py script adjusted to the recent codebase
2 |
3 | The following results were obtained on an Intel Core i5-2540M, 8GB RAM,
4 | Windows 7 x64, Python 2.7.10 x64, numpy-MKL 1.10.1.
5 |
6 | ----------------------
7 | In [6]: %run compareperformance.py
8 | ---
9 | Attack parameters
10 | Intermediate function : sBoxOut
11 | CPA leakage function : leakageModelHW
12 | LRA basis functions : basisModelSingleBits
13 | Encryption : True
14 | S-box number : 3
15 | Known roundkey : 0x2b7e151628aed2a6abf7158809cf4f3c
16 | ---
17 | Loading traces/swaes_atmega_powertraces.npz
18 | Number of traces loaded : 2000
19 | Trace length : 200
20 | Loading time : 0.03 s
21 | ---
22 | Attacks with 2000 traces
23 | Running CPA... done in 0.778006 s
24 | Running LRA... done in 20.568550 s
25 | Normalizing LRA results... done
26 | ---
27 | Attacks with 2000 traces and conditional averaging
28 | Performing conditional trace averaging... done in 0.018740 s
29 | Running CPA on averaged traces... done in 0.057710 s
30 | Running LRA on averaged traces... done in 3.075778 s
31 | Normalizing LRA results... done
32 | ---
33 | Plotting...
34 |
35 | ----------------------
36 | In [7]: %run compareperformance.py
37 | ---
38 | Attack parameters
39 | Intermediate function : sBoxOut
40 | CPA leakage function : leakageModelHW
41 | LRA basis functions : basisModelSingleBits
42 | Encryption : True
43 | S-box number : 3
44 | Known roundkey : 0x2b7e151628aed2a6abf7158809cf4f3c
45 | ---
46 | Loading traces/swaes_atmega_powertraces2_compressed.npz
47 | Number of traces loaded : 10000
48 | Trace length : 274
49 | Loading time : 0.01 s
50 | ---
51 | Attacks with 10000 traces
52 | Running CPA... done in 5.389510 s
53 | Running LRA... done in 107.093492 s
54 | Normalizing LRA results... done
55 | ---
56 | Attacks with 10000 traces and conditional averaging
57 | Performing conditional trace averaging... done in 0.128395 s
58 | Running CPA on averaged traces... done in 0.075705 s
59 | Running LRA on averaged traces... done in 4.017093 s
60 | Normalizing LRA results... done
61 | ---
62 | Plotting...
--------------------------------------------------------------------------------
/traces/hwdes_card8_power.npz:
--------------------------------------------------------------------------------
1 | version https://git-lfs.github.com/spec/v1
2 | oid sha256:f737084c1b6bf1af7b025b602bed6be82163081e4e8b7e277e8b9518d169faf3
3 | size 2160370
4 |
--------------------------------------------------------------------------------
/traces/swaes_atmega_power.trs:
--------------------------------------------------------------------------------
1 | version https://git-lfs.github.com/spec/v1
2 | oid sha256:3257e8005007e1fa3506a6d5fc57d782feb69edfd0f3fc80c7e91d71280a3b0f
3 | size 5888128
4 |
--------------------------------------------------------------------------------
/trs2npz.py:
--------------------------------------------------------------------------------
1 | '''
2 | This file is part of pysca toolbox, license is GPLv3, see https://www.gnu.org/licenses/gpl-3.0.en.html
3 | Author: Ilya Kizhvatov
4 | Version: 1.0, 2017-05-14
5 |
6 | Convert Inspector traceset into numpy array and save to npz.
7 | Reads the entire traceset into memory, so cannot deal with huge tracesets.
8 |
9 | External packages required:
10 | - numpy
11 | - Trace.py
12 |
13 | Versions of this file:
14 | v0.2 2014-10-31 Ilya: data conversion to unit64 made optional; some refactoring
15 | v0.1 2013-11-12 Ilya: initial
16 | '''
17 |
18 | import argparse
19 | import numpy as np
20 | import struct
21 | import Trace as trs
22 |
23 | # Determine coding of samples in .trs traceset and return it in numpy format
24 | def determineTrsSampleCoding(ts):
25 | if ts._sampleCoding == ts.CodingByte:
26 | samplesDataType = "int8"
27 | elif ts._sampleCoding == ts.CodingShort:
28 | samplesDataType = "int16"
29 | elif ts._sampleCoding == ts.CodingInt:
30 | samplesDataType = "int32"
31 | elif ts._sampleCoding == ts.CodingFloat:
32 | samplesDataType = "float32"
33 | else:
34 | samplesDataType = None
35 | return samplesDataType
36 |
37 | # Print main metadata of the .trs traceset
38 | def printTrsMetadata(ts, samplesDataType):
39 | print("Number of traces:\t%d" % ts._numberOfTraces)
40 | print("Samples per trace:\t%d" % ts._numberOfSamplesPerTrace)
41 | print("Samples datatype:\t%s" % samplesDataType)
42 | print("Data bytes:\t\t%d" % ts._dataSpace)
43 | print("Trace block size:\t%d bytes" % ts._traceBlockSpace)
44 | print("Header size:\t\t%d bytes" % ts._traceBlockOffset)
45 |
46 | if __name__ == "__main__":
47 |
48 | parser = argparse.ArgumentParser(description='Convert Inspector 4 traceset into numpy array')
49 | parser.add_argument('-c', '--convertdata', action='store_true', help='convert data from byte array to uint64 chunks')
50 | parser.add_argument('filename', help='traceset file name without trs extension')
51 | args = parser.parse_args()
52 |
53 | ts = trs.TraceSet()
54 | ts.open(args.filename + ".trs")
55 | samplesDataType = determineTrsSampleCoding(ts)
56 | printTrsMetadata(ts, samplesDataType)
57 |
58 | # read out the traces
59 | print("Preallocating arrays")
60 | traces = np.empty(shape=(ts._numberOfTraces, ts._numberOfSamplesPerTrace), dtype = samplesDataType)
61 | data = np.empty(shape=(ts._numberOfTraces, ts._dataSpace), dtype = "uint8")
62 | print("Populating arrays")
63 | for i in range(ts._numberOfTraces):
64 | t = ts.getTrace(i)
65 | traces[i, :] = np.array(t._samples, dtype = samplesDataType)
66 | data[i, :] = np.array(t._data, dtype = "uint8")
67 |
68 | if args.convertdata:
69 | print("Gathering bytes to uint64's")
70 | wordBytes = 8
71 | structCommand = '!Q'
72 | numberOfWordsNecessary = (len(data[0]) + wordBytes - 1)//(wordBytes)
73 | datanew = np.empty((len(data),numberOfWordsNecessary), dtype='uint64')
74 | for i in range(0, len(data)):
75 | if(len(data[i]) < numberOfWordsNecessary*wordBytes):
76 | tempData = np.concatenate((np.zeros(numberOfWordsNecessary*wordBytes - len(data[i]), dtype="uint8"), data[i]))
77 | else:
78 | tempData = data[i]
79 | for j in range(numberOfWordsNecessary):
80 | datanew[i][j] = struct.unpack(structCommand, tempData[(j*wordBytes):((j+1)*wordBytes)].tostring())[0]
81 | data = datanew # old data will be garbage-collected
82 |
83 | print("Saving file")
84 | np.savez(args.filename, traces=traces, data=data)
85 | print("Done")
--------------------------------------------------------------------------------