cracknuts-squirrel 0.0.1b0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cracknuts_squirrel-0.0.1b0/LICENSE +175 -0
- cracknuts_squirrel-0.0.1b0/PKG-INFO +63 -0
- cracknuts_squirrel-0.0.1b0/README.md +40 -0
- cracknuts_squirrel-0.0.1b0/pyproject.toml +53 -0
- cracknuts_squirrel-0.0.1b0/setup.cfg +4 -0
- cracknuts_squirrel-0.0.1b0/src/cracknuts_squirrel/__init__.py +1 -0
- cracknuts_squirrel-0.0.1b0/src/cracknuts_squirrel/correlation_analysis.py +126 -0
- cracknuts_squirrel-0.0.1b0/src/cracknuts_squirrel/correlation_analysis2.py +201 -0
- cracknuts_squirrel-0.0.1b0/src/cracknuts_squirrel/cpa_analysis.py +250 -0
- cracknuts_squirrel-0.0.1b0/src/cracknuts_squirrel/dpa_analysis.py +340 -0
- cracknuts_squirrel-0.0.1b0/src/cracknuts_squirrel/lstm_aes_hd.py +500 -0
- cracknuts_squirrel-0.0.1b0/src/cracknuts_squirrel/preprocessing_basic.py +22 -0
- cracknuts_squirrel-0.0.1b0/src/cracknuts_squirrel/stat.py +33 -0
- cracknuts_squirrel-0.0.1b0/src/cracknuts_squirrel/staticalgin.py +107 -0
- cracknuts_squirrel-0.0.1b0/src/cracknuts_squirrel/test_lstm_model.py +145 -0
- cracknuts_squirrel-0.0.1b0/src/cracknuts_squirrel/trace_io.py +289 -0
- cracknuts_squirrel-0.0.1b0/src/cracknuts_squirrel.egg-info/PKG-INFO +63 -0
- cracknuts_squirrel-0.0.1b0/src/cracknuts_squirrel.egg-info/SOURCES.txt +20 -0
- cracknuts_squirrel-0.0.1b0/src/cracknuts_squirrel.egg-info/dependency_links.txt +1 -0
- cracknuts_squirrel-0.0.1b0/src/cracknuts_squirrel.egg-info/requires.txt +11 -0
- cracknuts_squirrel-0.0.1b0/src/cracknuts_squirrel.egg-info/top_level.txt +1 -0
- cracknuts_squirrel-0.0.1b0/test/test_correlation_analysis.py +31 -0
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: cracknuts-squirrel
|
|
3
|
+
Version: 0.0.1b0
|
|
4
|
+
Summary: A Python library for side-channel analysis
|
|
5
|
+
Author-email: Dingzb <dingzibiao@gmail.com>
|
|
6
|
+
Maintainer-email: Dingzb <dingzibiao@gmail.com>
|
|
7
|
+
License-Expression: Apache-2.0
|
|
8
|
+
Project-URL: homepage, https://cracknuts.io
|
|
9
|
+
Requires-Python: >=3.12
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Requires-Dist: numpy~=1.26.4
|
|
13
|
+
Requires-Dist: pycryptodome~=3.23.0
|
|
14
|
+
Requires-Dist: zarr~=2.18.2
|
|
15
|
+
Requires-Dist: packaging~=24.1
|
|
16
|
+
Requires-Dist: numba~=0.61.2
|
|
17
|
+
Requires-Dist: dask~=2025.5.1
|
|
18
|
+
Requires-Dist: matplotlib~=3.10.3
|
|
19
|
+
Requires-Dist: h5py==3.14.0
|
|
20
|
+
Provides-Extra: jupyter
|
|
21
|
+
Requires-Dist: jupyter~=1.1.1; extra == "jupyter"
|
|
22
|
+
Dynamic: license-file
|
|
23
|
+
|
|
24
|
+
# CrackNuts Squirrel
|
|
25
|
+
|
|
26
|
+
## Installation
|
|
27
|
+
|
|
28
|
+
```shell
|
|
29
|
+
pip install cracknuts-squirrel
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## For Developers
|
|
33
|
+
|
|
34
|
+
In the virtual environment, run the following command to install the dependencies:
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
pip install -e .
|
|
38
|
+
pip install -r requirements-dev.txt
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## 文件功能说明
|
|
42
|
+
|
|
43
|
+
### lstm_aes_hd.py
|
|
44
|
+
|
|
45
|
+
该文件实现了基于LSTM的AES汉明距离(Hamming Distance)模型,用于侧信道分析攻击。主要功能包括:
|
|
46
|
+
|
|
47
|
+
- 定义了AESHDModel神经网络模型,结合了卷积层、双向LSTM层和注意力机制
|
|
48
|
+
- 实现了自定义数据集类(TraceDataset和InMemoryTraceDataset),用于加载和处理侧信道轨迹数据
|
|
49
|
+
- 包含模型训练逻辑,使用PyTorch框架进行训练
|
|
50
|
+
- 实现了Guessing Entropy(猜测熵)计算函数,用于评估攻击效果
|
|
51
|
+
- 提供了保存模型回调函数,在训练过程中定期保存模型并进行评估
|
|
52
|
+
|
|
53
|
+
### test_lstm_model.py
|
|
54
|
+
|
|
55
|
+
该文件用于测试训练好的LSTM模型,执行AES密钥恢复攻击。主要功能包括:
|
|
56
|
+
|
|
57
|
+
- 加载训练好的模型文件(.pt格式)
|
|
58
|
+
- 从zarr文件中加载测试数据(轨迹和明文)
|
|
59
|
+
- 执行攻击过程,使用模型预测结果进行密钥猜测
|
|
60
|
+
- 计算并显示猜测熵,评估攻击效果
|
|
61
|
+
- 显示最可能的密钥候选值,并与实际密钥进行比较
|
|
62
|
+
|
|
63
|
+
这两个文件共同构成了一个完整的AES侧信道分析工具链,从模型训练到攻击测试。
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# CrackNuts Squirrel
|
|
2
|
+
|
|
3
|
+
## Installation
|
|
4
|
+
|
|
5
|
+
```shell
|
|
6
|
+
pip install cracknuts-squirrel
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
## For Developers
|
|
10
|
+
|
|
11
|
+
In the virtual environment, run the following command to install the dependencies:
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
pip install -e .
|
|
15
|
+
pip install -r requirements-dev.txt
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## 文件功能说明
|
|
19
|
+
|
|
20
|
+
### lstm_aes_hd.py
|
|
21
|
+
|
|
22
|
+
该文件实现了基于LSTM的AES汉明距离(Hamming Distance)模型,用于侧信道分析攻击。主要功能包括:
|
|
23
|
+
|
|
24
|
+
- 定义了AESHDModel神经网络模型,结合了卷积层、双向LSTM层和注意力机制
|
|
25
|
+
- 实现了自定义数据集类(TraceDataset和InMemoryTraceDataset),用于加载和处理侧信道轨迹数据
|
|
26
|
+
- 包含模型训练逻辑,使用PyTorch框架进行训练
|
|
27
|
+
- 实现了Guessing Entropy(猜测熵)计算函数,用于评估攻击效果
|
|
28
|
+
- 提供了保存模型回调函数,在训练过程中定期保存模型并进行评估
|
|
29
|
+
|
|
30
|
+
### test_lstm_model.py
|
|
31
|
+
|
|
32
|
+
该文件用于测试训练好的LSTM模型,执行AES密钥恢复攻击。主要功能包括:
|
|
33
|
+
|
|
34
|
+
- 加载训练好的模型文件(.pt格式)
|
|
35
|
+
- 从zarr文件中加载测试数据(轨迹和明文)
|
|
36
|
+
- 执行攻击过程,使用模型预测结果进行密钥猜测
|
|
37
|
+
- 计算并显示猜测熵,评估攻击效果
|
|
38
|
+
- 显示最可能的密钥候选值,并与实际密钥进行比较
|
|
39
|
+
|
|
40
|
+
这两个文件共同构成了一个完整的AES侧信道分析工具链,从模型训练到攻击测试。
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools >= 61.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "cracknuts-squirrel"
|
|
7
|
+
description = "A Python library for side-channel analysis"
|
|
8
|
+
dynamic = ["version"]
|
|
9
|
+
requires-python = ">=3.12"
|
|
10
|
+
readme = "README.md"
|
|
11
|
+
license = "Apache-2.0"
|
|
12
|
+
authors = [{ name = "Dingzb", email = "dingzibiao@gmail.com" }]
|
|
13
|
+
maintainers = [{ name = "Dingzb", email = "dingzibiao@gmail.com" }]
|
|
14
|
+
dependencies = [
|
|
15
|
+
"numpy~=1.26.4",
|
|
16
|
+
"pycryptodome~=3.23.0",
|
|
17
|
+
"zarr~=2.18.2",
|
|
18
|
+
"packaging~=24.1",
|
|
19
|
+
"numba~=0.61.2",
|
|
20
|
+
"dask~=2025.5.1",
|
|
21
|
+
"matplotlib~=3.10.3",
|
|
22
|
+
"h5py==3.14.0",
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
[project.optional-dependencies]
|
|
26
|
+
jupyter = [
|
|
27
|
+
"jupyter~=1.1.1",
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
[project.urls]
|
|
31
|
+
homepage = "https://cracknuts.io"
|
|
32
|
+
|
|
33
|
+
[tool.setuptools.dynamic]
|
|
34
|
+
version = { attr = "cracknuts_squirrel.__version__" }
|
|
35
|
+
|
|
36
|
+
[tool.ruff]
|
|
37
|
+
line-length = 120
|
|
38
|
+
target-version = "py312"
|
|
39
|
+
exclude = ["demo", "tests", "docs"]
|
|
40
|
+
|
|
41
|
+
[tool.ruff.lint]
|
|
42
|
+
extend-select = [
|
|
43
|
+
"F",
|
|
44
|
+
"E",
|
|
45
|
+
"W",
|
|
46
|
+
"UP",
|
|
47
|
+
]
|
|
48
|
+
|
|
49
|
+
[tool.typos.files]
|
|
50
|
+
extend-exclude = [
|
|
51
|
+
"demo",
|
|
52
|
+
"tests"
|
|
53
|
+
]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.0.1-beta.0"
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
# Copyright 2024 CrackNuts. All rights reserved.
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
import zarr
|
|
5
|
+
from cracknuts_squirrel.preprocessing_basic import PPBasic
|
|
6
|
+
import matplotlib.pyplot as plt
|
|
7
|
+
|
|
8
|
+
# Hamming weights of the values 0-255 used for model values
|
|
9
|
+
WEIGHTS = np.array([0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4,
|
|
10
|
+
1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
|
|
11
|
+
1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
|
|
12
|
+
2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
|
|
13
|
+
1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
|
|
14
|
+
2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
|
|
15
|
+
2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
|
|
16
|
+
3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
|
|
17
|
+
1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
|
|
18
|
+
2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
|
|
19
|
+
2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
|
|
20
|
+
3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
|
|
21
|
+
2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
|
|
22
|
+
3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
|
|
23
|
+
3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
|
|
24
|
+
4,5,5,6,5,6,6,7,5,6,6,7,6,7,7,8],
|
|
25
|
+
np.float32)
|
|
26
|
+
|
|
27
|
+
class CorrelationAnalysis(PPBasic):
|
|
28
|
+
"""
|
|
29
|
+
通用相关系数分析类,继承自预处理基类PPBasic
|
|
30
|
+
"""
|
|
31
|
+
def __init__(self, input_path=None, output_path=None, sample_range=(0, None), **kwargs):
|
|
32
|
+
super().__init__(input_path=input_path, output_path=output_path, **kwargs)
|
|
33
|
+
self.sample_range = sample_range
|
|
34
|
+
|
|
35
|
+
def calculate_correlation(self, traces, plaintext_bytes):
|
|
36
|
+
"""
|
|
37
|
+
计算轨迹(traces)与明文字节(plaintext_bytes)之间的相关系数
|
|
38
|
+
|
|
39
|
+
参数:
|
|
40
|
+
traces: numpy数组,形状为(n_traces, n_samples),包含功率轨迹数据
|
|
41
|
+
plaintext_bytes: numpy数组,形状为(n_traces, n_bytes),包含明文字节数据
|
|
42
|
+
|
|
43
|
+
返回:
|
|
44
|
+
correlations: numpy数组,形状为(n_bytes, n_samples),包含每个字节位置与每个样本点的相关系数
|
|
45
|
+
"""
|
|
46
|
+
# 确保输入是numpy数组
|
|
47
|
+
traces = np.asarray(traces)
|
|
48
|
+
plaintext_bytes = np.asarray(plaintext_bytes)
|
|
49
|
+
|
|
50
|
+
# 检查输入维度是否匹配
|
|
51
|
+
if traces.shape[0] != plaintext_bytes.shape[0]:
|
|
52
|
+
raise ValueError("轨迹数量与明文数量不匹配")
|
|
53
|
+
|
|
54
|
+
n_traces, n_samples = traces.shape
|
|
55
|
+
n_bytes = plaintext_bytes.shape[1]
|
|
56
|
+
|
|
57
|
+
# 初始化相关系数结果数组
|
|
58
|
+
correlations = np.zeros((n_bytes, n_samples))
|
|
59
|
+
|
|
60
|
+
# 对每个字节位置计算相关系数
|
|
61
|
+
for byte_idx in range(n_bytes):
|
|
62
|
+
# 提取当前字节数据
|
|
63
|
+
byte_data = plaintext_bytes[:, byte_idx]
|
|
64
|
+
|
|
65
|
+
# 对每个样本点计算相关系数
|
|
66
|
+
for sample_idx in range(n_samples):
|
|
67
|
+
# 提取当前样本点的轨迹数据
|
|
68
|
+
trace_data = traces[:, sample_idx]
|
|
69
|
+
|
|
70
|
+
# 计算皮尔逊相关系数
|
|
71
|
+
correlations[byte_idx, sample_idx] = np.corrcoef(byte_data, trace_data)[0, 1]
|
|
72
|
+
|
|
73
|
+
return correlations
|
|
74
|
+
|
|
75
|
+
def perform_analysis(self):
|
|
76
|
+
"""
|
|
77
|
+
执行相关系数分析(使用明文字节的汉明重量作为模型值)
|
|
78
|
+
"""
|
|
79
|
+
store = zarr.DirectoryStore(self.output_path)
|
|
80
|
+
root = zarr.group(store=store, overwrite=True)
|
|
81
|
+
|
|
82
|
+
# 获取处理后的轨迹数据
|
|
83
|
+
processed_traces = self.t[:, self.sample_range[0]:self.sample_range[1]]
|
|
84
|
+
|
|
85
|
+
# 获取明文字节并计算汉明重量
|
|
86
|
+
plaintext = self.plaintext[:self.sel_num_traces, :16]
|
|
87
|
+
hw_matrix = WEIGHTS[plaintext]
|
|
88
|
+
|
|
89
|
+
# 计算相关系数矩阵
|
|
90
|
+
correlation_matrix = self.calculate_correlation(
|
|
91
|
+
traces=processed_traces,
|
|
92
|
+
plaintext_bytes=hw_matrix
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
# 存储结果
|
|
96
|
+
root.create_dataset(
|
|
97
|
+
'/0/0/correlation',
|
|
98
|
+
data=correlation_matrix,
|
|
99
|
+
chunks=(16, 1000)
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
# 添加元数据
|
|
103
|
+
root.attrs.update({
|
|
104
|
+
"analysis_metadata": {
|
|
105
|
+
"sample_range": self.sample_range,
|
|
106
|
+
"trace_count": self.sel_num_traces,
|
|
107
|
+
"model_type": "hamming_weight"
|
|
108
|
+
}
|
|
109
|
+
})
|
|
110
|
+
return correlation_matrix
|
|
111
|
+
|
|
112
|
+
if __name__ == "__main__":
|
|
113
|
+
# 示例用法
|
|
114
|
+
analyzer = CorrelationAnalysis(input_path='E:\\codes\\Acquisition\\dataset\\20250722204543.zarr')
|
|
115
|
+
analyzer.auto_out_filename()
|
|
116
|
+
# analyzer.set_range(sample_range=(500, 10000))
|
|
117
|
+
|
|
118
|
+
result = analyzer.perform_analysis()
|
|
119
|
+
|
|
120
|
+
print(result.shape)
|
|
121
|
+
for i in range(16):
|
|
122
|
+
plt.plot(result[i,:])
|
|
123
|
+
|
|
124
|
+
plt.show()
|
|
125
|
+
|
|
126
|
+
print(f"分析完成,最大相关系数:{np.nanmax(np.abs(result)):.4f}")
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
# Copyright 2024 CrackNuts. All rights reserved.
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from typing import Optional
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
import zarr
|
|
8
|
+
|
|
9
|
+
from cracknuts_squirrel.preprocessing_basic import PPBasic
|
|
10
|
+
|
|
11
|
+
@dataclass
|
|
12
|
+
class AnalysisParams:
|
|
13
|
+
data_type: str = "plaintext"
|
|
14
|
+
data_width: int = 1
|
|
15
|
+
start: int = 0
|
|
16
|
+
count: Optional[int] = None
|
|
17
|
+
|
|
18
|
+
class CorrelationAnalysis(PPBasic):
|
|
19
|
+
# Hamming weights of the values 0-255 used for model values
|
|
20
|
+
_HW_TABLE = np.array([
|
|
21
|
+
0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4,
|
|
22
|
+
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
|
|
23
|
+
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
|
|
24
|
+
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
|
|
25
|
+
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
|
|
26
|
+
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
|
|
27
|
+
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
|
|
28
|
+
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
|
|
29
|
+
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
|
|
30
|
+
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
|
|
31
|
+
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
|
|
32
|
+
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
|
|
33
|
+
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
|
|
34
|
+
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
|
|
35
|
+
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
|
|
36
|
+
4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8
|
|
37
|
+
], np.uint8)
|
|
38
|
+
|
|
39
|
+
"""
|
|
40
|
+
通用相关系数分析类,继承自预处理基类PPBasic
|
|
41
|
+
"""
|
|
42
|
+
def __init__(self, input_path=None, output_path=None, sample_range=(0, None), **kwargs):
|
|
43
|
+
super().__init__(input_path=input_path, output_path=output_path, **kwargs)
|
|
44
|
+
self.sample_range = sample_range
|
|
45
|
+
|
|
46
|
+
@classmethod
|
|
47
|
+
def hamming_weight(cls, data: np.ndarray, bit_width: int) -> np.ndarray:
|
|
48
|
+
|
|
49
|
+
if data.ndim != 2:
|
|
50
|
+
raise ValueError(f"输入必须是二维数组,当前形状为 {data.shape}")
|
|
51
|
+
|
|
52
|
+
if data.dtype != np.uint8:
|
|
53
|
+
raise ValueError("输入数组必须是 uint8 类型")
|
|
54
|
+
|
|
55
|
+
if bit_width == 8:
|
|
56
|
+
return cls._HW_TABLE[data]
|
|
57
|
+
|
|
58
|
+
n, m = data.shape
|
|
59
|
+
|
|
60
|
+
if bit_width > 8:
|
|
61
|
+
if bit_width not in (16, 32, 64):
|
|
62
|
+
raise ValueError("合并仅支持 16, 32, 64 位")
|
|
63
|
+
num_bytes = bit_width // 8
|
|
64
|
+
if m % num_bytes != 0:
|
|
65
|
+
raise ValueError(f"列数 {m} 不能被 {num_bytes} 整除")
|
|
66
|
+
|
|
67
|
+
reshaped = data.reshape(n, m // num_bytes, num_bytes)
|
|
68
|
+
tmp_hw = cls._HW_TABLE[reshaped]
|
|
69
|
+
|
|
70
|
+
return tmp_hw.astype(f"uint{bit_width}").sum(axis=2)
|
|
71
|
+
|
|
72
|
+
else: # bit_length < 8
|
|
73
|
+
if bit_width not in (1, 2, 4):
|
|
74
|
+
raise ValueError("拆分仅支持 1, 2, 4 位")
|
|
75
|
+
if 8 % bit_width != 0:
|
|
76
|
+
raise ValueError(f"8 不能被 {bit_width} 整除")
|
|
77
|
+
splits_per_byte = 8 // bit_width
|
|
78
|
+
new_m = m * splits_per_byte
|
|
79
|
+
result = np.zeros((n, new_m), dtype=np.uint8)
|
|
80
|
+
|
|
81
|
+
for i in range(splits_per_byte):
|
|
82
|
+
shift = 8 - bit_width * (i + 1)
|
|
83
|
+
mask = (1 << bit_width) - 1
|
|
84
|
+
result[:, i::splits_per_byte] = (data >> shift) & mask
|
|
85
|
+
|
|
86
|
+
return cls._HW_TABLE[result]
|
|
87
|
+
|
|
88
|
+
@staticmethod
|
|
89
|
+
def calculate_correlation(traces, data_bytes):
|
|
90
|
+
"""
|
|
91
|
+
计算轨迹(traces)与明文字节(plaintext_bytes)之间的相关系数
|
|
92
|
+
|
|
93
|
+
参数:
|
|
94
|
+
traces: numpy数组,形状为(n_traces, n_samples),包含功率轨迹数据
|
|
95
|
+
data_bytes: numpy数组,形状为(n_traces, n_bytes),包含明文字节数据
|
|
96
|
+
|
|
97
|
+
返回:
|
|
98
|
+
correlations: numpy数组,形状为(n_bytes, n_samples),包含每个字节位置与每个样本点的相关系数
|
|
99
|
+
"""
|
|
100
|
+
# 确保输入是numpy数组
|
|
101
|
+
traces = np.asarray(traces)
|
|
102
|
+
data_bytes = np.asarray(data_bytes)
|
|
103
|
+
|
|
104
|
+
# 检查输入维度是否匹配
|
|
105
|
+
if traces.shape[0] != data_bytes.shape[0]:
|
|
106
|
+
raise ValueError("轨迹数量与明文数量不匹配")
|
|
107
|
+
|
|
108
|
+
n_traces, n_samples = traces.shape
|
|
109
|
+
n_bytes = data_bytes.shape[1]
|
|
110
|
+
|
|
111
|
+
# 初始化相关系数结果数组
|
|
112
|
+
correlations = np.zeros((n_bytes, n_samples))
|
|
113
|
+
|
|
114
|
+
# 对每个字节位置计算相关系数
|
|
115
|
+
for byte_idx in range(n_bytes):
|
|
116
|
+
# 提取当前字节数据
|
|
117
|
+
byte_data = data_bytes[:, byte_idx]
|
|
118
|
+
|
|
119
|
+
# 对每个样本点计算相关系数
|
|
120
|
+
for sample_idx in range(n_samples):
|
|
121
|
+
# 提取当前样本点的轨迹数据
|
|
122
|
+
trace_data = traces[:, sample_idx]
|
|
123
|
+
|
|
124
|
+
if np.std(byte_data) == 0:
|
|
125
|
+
correlations[byte_idx, sample_idx] = 0 # 或者 np.nan
|
|
126
|
+
else:
|
|
127
|
+
correlations[byte_idx, sample_idx] = np.corrcoef(byte_data, trace_data)[0, 1]
|
|
128
|
+
|
|
129
|
+
return correlations
|
|
130
|
+
|
|
131
|
+
def perform_analysis(self, *analyzer_params: AnalysisParams, persist: bool=False) -> np.ndarray:
|
|
132
|
+
correlation_matrix_array = []
|
|
133
|
+
for analyzer_param in analyzer_params:
|
|
134
|
+
correlation_matrix_array.append(self.single_perform_analysis(**vars(analyzer_param)))
|
|
135
|
+
|
|
136
|
+
correlation_matrix = np.vstack(correlation_matrix_array)
|
|
137
|
+
|
|
138
|
+
if persist:
|
|
139
|
+
store = zarr.DirectoryStore(self.output_path)
|
|
140
|
+
root = zarr.group(store=store, overwrite=True)
|
|
141
|
+
# 存储结果
|
|
142
|
+
root.create_dataset(
|
|
143
|
+
'/0/0/correlation',
|
|
144
|
+
data=correlation_matrix,
|
|
145
|
+
chunks=(16, 1000)
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
# 添加元数据
|
|
149
|
+
root.attrs.update({
|
|
150
|
+
"analysis_metadata": {
|
|
151
|
+
"sample_range": self.sample_range,
|
|
152
|
+
"trace_count": self.sel_num_traces,
|
|
153
|
+
"model_type": "hamming_weight"
|
|
154
|
+
}
|
|
155
|
+
})
|
|
156
|
+
|
|
157
|
+
return correlation_matrix
|
|
158
|
+
|
|
159
|
+
def single_perform_analysis(self, data_type="plaintext", data_width=1, start: int = 0, count: int = None):
|
|
160
|
+
"""
|
|
161
|
+
执行相关系数分析(使用明文字节的汉明重量作为模型值)
|
|
162
|
+
"""
|
|
163
|
+
# 获取处理后的轨迹数据
|
|
164
|
+
processed_traces = self.t[:, self.sample_range[0]:self.sample_range[1]]
|
|
165
|
+
|
|
166
|
+
if data_type == "plaintext":
|
|
167
|
+
# 获取明文字节并计算汉明重量
|
|
168
|
+
if count is None:
|
|
169
|
+
plaintext = self.plaintext[:self.sel_num_traces, start:]
|
|
170
|
+
else:
|
|
171
|
+
plaintext = self.plaintext[:self.sel_num_traces, start:start+count]
|
|
172
|
+
hw_matrix = self.hamming_weight(plaintext, data_width * 8)
|
|
173
|
+
elif data_type == "ciphertext":
|
|
174
|
+
if count is None:
|
|
175
|
+
ciphertext = self.ciphertext[:self.sel_num_traces, start:]
|
|
176
|
+
else:
|
|
177
|
+
ciphertext = self.ciphertext[:self.sel_num_traces, start:start+count]
|
|
178
|
+
hw_matrix = self.hamming_weight(ciphertext, data_width * 8)
|
|
179
|
+
elif data_type == "key":
|
|
180
|
+
if count is None:
|
|
181
|
+
key = self.key[:self.sel_num_traces, start:]
|
|
182
|
+
else:
|
|
183
|
+
key = self.key[:self.sel_num_traces, start:start+count]
|
|
184
|
+
hw_matrix = self.hamming_weight(key, data_width * 8)
|
|
185
|
+
elif data_type == "extended":
|
|
186
|
+
if count is None:
|
|
187
|
+
extended = self.extended[:self.sel_num_traces, start:]
|
|
188
|
+
else:
|
|
189
|
+
extended = self.extended[:self.sel_num_traces, start:start+count]
|
|
190
|
+
hw_matrix = self.hamming_weight(extended, data_width * 8)
|
|
191
|
+
else:
|
|
192
|
+
print(f"data_type error: [{data_type}].")
|
|
193
|
+
return
|
|
194
|
+
|
|
195
|
+
# 计算相关系数矩阵
|
|
196
|
+
correlation_matrix = self.calculate_correlation(
|
|
197
|
+
traces=processed_traces,
|
|
198
|
+
data_bytes=hw_matrix
|
|
199
|
+
)
|
|
200
|
+
|
|
201
|
+
return correlation_matrix
|