照烟照烟
WP

0xGame-2026-week2

ez_chain

源码

一条私有以太坊测试链上已经部署好了一个 Greeter 合约。

让它的 isSolved() 返回 true,flag 就是你的。

服务地址说明

判题服务

自行启动动态容器获取

创建账户、部署题目合约、查看合约源码、领取 flag 私链

RPC

http://chain.challenge.ctfplus.cn: 11890

与链上合约交互(Chain ID: 35541)

测试币水龙头

http://chain.challenge.ctfplus.cn: 14824

每次可领 1 ETH,同一地址每分钟限领一次

提示

  1. 先用 nc 连接判题服务,按菜单创建账户并部署合约,拿到属于你的合约地址;菜单里可以直接查看合约源码。
  2. 链上操作需要 gas,先去水龙头给自己的地址领一点测试币。
  3. 推荐使用 Remix 配合 MetaMask:
    1. MetaMask 添加自定义网络:RPC URL 填上面的私链 RPC 地址
    2. 打开 Remix 的 Deploy & Run Transactions 面板,在 ENVIRONMENT 中选择 Browser Extension(浏览器扩展钱包),选择 MetaMask 连接(旧版 Remix 中这个叫 Injected Provider - MetaMask)。
  4. 在 Remix 中粘贴合约源码并完成编译(编译器选 0.8.x)后,在 Deployed Contracts 区域点击 Add Contract,填入你的合约地址即可加载合约进行交互(旧版 Remix 中此功能叫 At Address)。
  5. 仔细读一读 isSolved() 的实现,它在等待一句什么样的问候?

分析

Misc 的区块链,让我品鉴一下

区块链是一种底层技术,不等同于比特币(后者建立在前者的基础之上),也不等于以太坊(支持智能合约执行的区块链平台)。发生在其上的交易被组织进区块,每个区块通过引用前一个区块的哈希形成链式结构,从而防止恶意篡改。

区块链上可以执行智能合约(本质是由区块链节点执行的程序,而非人工智能,通常使用 Solidity 编写)。合约会按照事前交易者约定的规则自动执行,不需要第三方机构仲裁结果,常用于在有限信任第三方的场景进行多方交易。编写智能合约的语言语法与 JS 类似,有变量、函数等,但是想要修改程序数据必须借由交易实现(因为上文说过,合约不是本地的,修改之后需要让所有人都知道你做了这次更改,所以程序更改只能借由同样被广播的交易传播),而不能凭空修改(但是可以随时读取,即使不交易)。一次交易的流程大概是:

  1. 确保账户拥有足够的 ETH 来支付 Gas
  2. 使用私钥对交易签名
  3. 通过 RPC(Remote Procedure Call,远程过程调用)将交易广播到区块链网络
  4. 节点验证交易并执行智能合约
  5. 交易被打包进区块
  6. 合约状态正式发生改变

首先 netcat 到靶机创建账户:

1
2
3
4
5
6
7
8
9
10
Can you make the isSolved() function return true?

[1] - Create an account which will be used to deploy the challenge contract
[2] - Deploy the challenge contract using your generated account
[3] - Get your flag once you meet the requirement
[4] - Show the contract source code
[-] input your choice: 1
[+] deployer account: 0x5e5Cc8cffC3C31BCd0C64Ed5d786aeeFb0EE03D5
[+] token: v4.local.bBA9NexLXB0-hmtWfKQQHuRu4rW9irIVA4rD7CFkhHFglFNtmgHbvpF-2GkQtspfeL4TjVYpxP0EyMdMziyndGN-jBiKUYpaBEEAVn5TbrOlqnjdQ28nto-nugrxH3AMiQ2VU0xFODs-ODFUCigZZ1p1sQJfBMI9cebIRAZZ69Gw_Q.R3JlZXRlcg
[+] please transfer more than 0.001 test ether to the deployer account for next step

得到我们的账户地址和 token,接下来去领测试币(填入自己的 account)

领到钱之后去部署合约(合约的默认模板是一个 Greeter,输入 4 可以查看这个模板的源码,这里部署的过程相当于把这个模板实例化):

1
2
[+] contract address: 0x9218616823aF4626A6b086D08698DAD5cbd85484
[+] transaction hash: 0xd0dd3fc5580c8c6833f8f9a3782a4fec3a2ee82ea100d14f82cac0c1d8f2a117

模板源码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
contracts/Example.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.9;

contract Greeter {
string greeting;

constructor(string memory _greeting) {
greeting = _greeting;
}

function greet() public view returns (string memory) {
return greeting;
}

function setGreeting(string memory _greeting) public {
greeting = _greeting;
}

function isSolved() public view returns (bool) {
string memory expected = "HelloChainFlag";
return keccak256(abi.encodePacked(expected)) == keccak256(abi.encodePacked(greeting));
}
}

其中 constructor() 是构造函数,只在部署合约时执行,用于初始化变量 greeting,greet() 用于读取当前问候语(view 表示该函数承诺不修改链上状态,可以在只读状态下调用),setGreeting() 用于修改问候语(这个函数没有检验调用者是不是部署者,也就是任意知道合约地址且有 ETH 的账户都能调用),isSolved() 比较字符串 greeting 是否已经被修改为了 "HelloChainFlag",是则返回 true。

使用 Python 发送一笔交易请求后,我们得以调用函数来修改字符串。修改完毕后领 flag。

注意,创建的账户没有私钥,所以要一步做完注册+领钱+交易的全流程

EXP

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import time, uuid, urllib.request, urllib.error
from web3 import Web3
from eth_account import Account

RPC = "http://chain.challenge.ctfplus.cn:11890"
FAUCET = "http://chain.challenge.ctfplus.cn:14824/api/claim"

w3 = Web3(Web3.HTTPProvider(RPC))
acct = Account.create()

while True:
b = uuid.uuid4().hex
body = f'--{b}\r\nContent-Disposition: form-data; name="address"\r\n\r\n{acct.address}\r\n--{b}--\r\n'.encode()
req = urllib.request.Request(
FAUCET,
data=body,
headers={"Content-Type": f"multipart/form-data; boundary={b}"},
)
try:
_ = urllib.request.urlopen(req, timeout=20).read().decode().strip()
break
except urllib.error.HTTPError:
time.sleep(20)

while w3.eth.get_balance(acct.address) < 10**15:
time.sleep(2)

CONTRACT = "0x37F4918D06E73D336Fe06B503FABC9dE2Cba9f5A"
ABI = [
{
"inputs": [{"name": "_greeting", "type": "string"}],
"name": "setGreeting",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function",
}
]
c = w3.eth.contract(address=Web3.to_checksum_address(CONTRACT), abi=ABI)
tx = c.functions.setGreeting("HelloChainFlag").build_transaction(
{
"from": acct.address,
"nonce": w3.eth.get_transaction_count(acct.address),
"gas": 100000,
"gasPrice": w3.eth.gas_price,
"chainId": w3.eth.chain_id,
}
)
h = w3.eth.send_raw_transaction(acct.sign_transaction(tx).raw_transaction)
print("Done")

之后登录后选择 3 领取 flag。

命运石之门

源码

时间线.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
from Crypto.Cipher import AES
from base64 import b64decode

KEY = bytes.fromhex("185608cdb3409b141aa6812757d41cc9")
IV = bytes.fromhex("2d1aed23dff9f1f2e30836642237a752")

conditions = {
8: 85,
30: 108,
41: 50,
63: 122,
67: 115,
91: 75,
104: 103,
122: 90,
143: 52,
}

try:
c2 = b64decode(input("c2.encode('base64')=").strip(), validate=True)

if len(c2) != 256:
raise ValueError

m2 = AES.new(KEY, AES.MODE_CBC, IV).decrypt(c2)

if not all(m2[pos] == value for pos, value in conditions.items()):
raise ValueError

from secret import flag

print(flag)

except Exception:
print("失败了失败了失败了...")

1.048596

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
####*####*####*####Game Start####*####*####*####
# '#' for conditions
# '@' for questions
####@####
# c1=aes_cbc_encode(password,iv,m1)
# c1.encode('base64')=78k8daGvSR3MgT/oq6f/ysaYJTIPJGwgHmPkyiUmZbe+fekHTMi0iw8lEC8jOtBVI+nNiJtIXgOi
xXibyYXBNJys8Cx350Be7noECiSlvzx5ScG7smEQ+Lu2k2ehSo0xnN3nsyXY0gxQOXiTzjkFdD2Z
soKbxGLTHCaRyeTtm2Sl2W0xeslLN/6Ro7ANlL0eUciX9zVp21ps6cIjjEZvU6cl0nByaOr2Wo+Y
uwtgVlGfNfYs7HURVjoxU2W0DKHzqQd6FdplZrRFRaRCA6sp2TYizKWCs97Mv+dWmJ90XgF6BRgy
kV49XT6FyZEvDDLuZEKPtjrVKqrgfulLx7rFsQ==
# m1.encode('base64')=eUZRY2Q4Zjhzc31Mbi1LQmZLMzZ5V3hHdjh3SjNBMWw1OWVoZEFXa194Si1rZUlCZmtSVVlJa29i
ak9Ba0NtZGl9TH1SSEtuU2ZwcjJPQ0xrcE9Bbn1YfVNJWE05bFI5SklyYzN2R3JuQzFLa0RrR2lR
azN3Z19pUER2ekgzbEdxWS10czI1ejJjQnFRNnBnSG1WaUswRjBMSkN5eUV3Z3p7R0lmWHY4VV9p
LWhrRGxWTEJ5SHNGYTY3cmhua3dpUFZTTHI3YnhFenJBS29ELXVZX31pUkpCOUw3M2R4SmgzVzhS
dG5RaGs2UFpwMGszVWNHb09qejJ5RFhqUVNCWQ==
# m2=aes_cbc_decode(password,iv,c2)
# m2[8]=U
# m2[30]=l
# m2[41]=2
# m2[63]=z
# m2[67]=s
# m2[91]=K
# m2[104]=g
# m2[122]=Z
# m2[143]=4

分析

连接靶机后要求我们提交一个字节长度为 256 的 c2(若其被指定的 key 解密后指定的位置是指定的字节则打印 flag)

由于 key 和 iv 硬编码在附件中,所以直接随意加密一个字节串 b"A" * 256,再把指定的位置替换成要求的字节,最后加密编码后发送即可,还是非常简单的。

EXP

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from Crypto.Cipher import AES
from base64 import b64encode

KEY = bytes.fromhex("185608cdb3409b141aa6812757d41cc9")
IV = bytes.fromhex("2d1aed23dff9f1f2e30836642237a752")
CONDS = {8: 85, 30: 108, 41: 50, 63: 122, 67: 115, 91: 75, 104: 103, 122: 90, 143: 52}

data = bytearray(b"A" * 256)
for idx, val in CONDS.items():
data[idx] = val
data = bytes(data)

print(b64encode(AES.new(key=KEY, iv=IV, mode=AES.MODE_CBC).encrypt(data)))
'''
b'ADLk72Qd3J3AW65aw+M+I4OSkvdmR47UadPYwvcXERvh1Ic5JqwcSlAF/+us8DEzjpBZYnq/zXJZDao97wjcGx+spAo7j7Abn5WauYDX55kT61D9txuLAXUbusAHhiSySOEw1klysjUIO6ssbO1UAuURPzJxrz8CeNRkAVuAZmnUXE+M2G327lu4XlHF6qxZ/TDG3NyHJfqEQ0TEZ/njJU23G3pt6YMET4QweWRydOCPkZrm6wv8WlPuPtkQoNJv1P1DboiZKB2RgLM6mf+65Bp0XdTr3QmJaGkMZ3l0tu9fxy6eN/H9Ix7z66Uc+FxTEUiZ5UlBje4o97g1usIjbQ=='
'''
# 0xGame{th15 15 my v1ct0ry}

契约之吻

源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
from random import randrange
from secret import f_coeffs, s_coeffs, error

d = 64
scale = 2^44
n = 24
p = 2147483647

secret = vector(ZZ, [f_coeffs[i] if i < len(f_coeffs) else (1 if i == n else 0) for i in range(d)])
mt = matrix(ZZ, [[randrange(0, scale) for _ in range(d)] for _ in range(d)])
mt[0] = [i for i in secret]

new_mt = matrix(ZZ, d)
for i in range(d):
row = random_vector(ZZ, d, x=257)
for j in range(i):
row[j] = 0
row[i] = 1
new_mt[i] = row * mt

H = new_mt

R.<x> = PolynomialRing(ZZ)
F = x^n + sum(f_coeffs[i] * x^i for i in range(len(f_coeffs)))
A = vector(ZZ, [1624513444, 7887634, 1850144002, 1333320193, 1148549154, 28619938, 1601341874, 353058494, 224962944, 1491387826, 612016532, 1078815215, 1270428426, 748164318, 1219377558, 1238933391, 1824650003, 469831872, 712295407, 559376837, 1804640269, 1147167506, 818193445, 1043390130])
a = sum(A[i] * x^i for i in range(n))
M_A = matrix(ZZ, n, n)
for j in range(n):
col = (a * x^j) % F
for i in range(n):
M_A[i, j] = col[i]

B = (M_A * vector(ZZ, s_coeffs) + vector(ZZ, error)).apply_map(lambda v: v % p)
1
2
3
4
5
6
H = Matrix(ZZ, ...)
n = 24
p = 2147483647
A = vector(ZZ, [1624513444, 7887634, 1850144002, 1333320193, 1148549154, 28619938, 1601341874, 353058494, 224962944, 1491387826, 612016532, 1078815215, 1270428426, 748164318, 1219377558, 1238933391, 1824650003, 469831872, 712295407, 559376837, 1804640269, 1147167506, 818193445, 1043390130])
B = vector(ZZ, [1584629395, 1775945163, 1784920680, 799777832, 190375877, 1042203276, 130885455, 818709477, 2028856523, 1432265309, 1955415028, 1803349034, 1700209324, 76905918, 1310746310, 1196867964, 1074607924, 1450755954, 1835977834, 274603389, 985245801, 1531212267, 786452925, 307078336])
error_bound = 3

分析

题目首先生成一个长为 64 的向量 secret,前 24 项是隐秘多项式的系数 f_coeffs,第 25 位为 1,后面为 0,被嵌在随机 64x64 矩阵 mt 的第一行。接着隐蔽地生成了一个神秘矩阵,将其与前述的随机矩阵相乘:

1
2
3
4
5
6
7
8
9
new_mt = matrix(ZZ, d)
for i in range(d):
row = random_vector(ZZ, d, x=257)
for j in range(i):
row[j] = 0
row[i] = 1
new_mt[i] = row * mt

H = new_mt

线代中矩阵相乘( C=A⋅B )的本质就是 C[i]=A[i]⋅B ,因此这段实际就是两矩阵相乘。细看这个矩阵的结构,是一个上三角矩阵,形如:

U=(1r0,1r0,2⋯r0,d−101r1,2⋯r1,d−1001⋯r2,d−1⋮⋮⋮⋱⋮000⋯1)

行列式为的上三角矩阵称为幺模矩阵,在格中具有特殊的地位(其在整数域上可逆,且行列式为 ±1 ,不改变格结构,相当于对之前的 mt 做了线性变换),因此原矩阵的第一行 secret 依然是格中的短向量,使得我们可以直接对 new_mt 做格约简得到 secret。目标向量的长度显著短于普通向量,LLL 足够了。

加上 xn ,得到隐蔽多项式:

F(x)=x24+2x3+2x+4

后续 MA 的计算完全可以在本地进行。得到 MA 后,我们面临 LWE 问题 B≡MA⋅s+e(modp) 。

去除模运算后有 MA⋅s−B+p⋅k=−e ,构造 49x49 的分块矩阵:

M=(I24MAT00p⋅I2400BT1)

基向量为 (−sT,kT,1) ,左乘会得到目标向量 (−sT,eT,1) ,约简得到 s_coeffs。

EXP

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
from sage.all import *
from params import *

f_coeffs = [abs(x) for x in list(H.LLL()[0])]
f_coeffs = f_coeffs[: f_coeffs.index(1) + 1]

R = PolynomialRing(ZZ, "x")
x = R.gen()
F = x**n + sum(f_coeffs[i] * x**i for i in range(n))

a = sum(A[i] * x**i for i in range(n))
M_A = matrix(ZZ, n, n)
for j in range(n):
col = (a * x**j) % F
for i in range(n):
M_A[i, j] = col[i]

I_n = identity_matrix(ZZ, n)
zero_n = zero_matrix(ZZ, n, n)
p_I = p * I_n
M = block_matrix(
ZZ,
[
[I_n, M_A.transpose(), zero_matrix(ZZ, n, 1)],
[zero_n, p_I, zero_matrix(ZZ, n, 1)],
[zero_matrix(ZZ, 1, n), matrix(ZZ, [B]), matrix(ZZ, [[1]])],
],
)
L = M.LLL()
print(L[0])
# (-48, -120, -71, -97, -109, -101, -123, -107, -105, -115, -115, -32, -116, -104, -101, -110, -32, -107, -105, -108, -108, -125, 0, 0, 1, 1, 3, -3, -1, 1, 3, -1, -3, -2, 3, 0, 1, -2, -2, 2, -2, 0, 0, -3, -2, -3, -1, -3, 1)

s_coeffs = [-48, -120, -71, -97, -109, -101, -123, -107, -105, -115, -115, -32, -116, -104, -101, -110, -32, -107, -105, -108, -108, -125]
print("".join(chr(abs(x)) for x in s_coeffs))
# 0xGame{kiss then kill}

老师傅的波纹

源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from secrets import flag
from Crypto.Util.number import getPrime
BITS = 80
a = int(flag[5:-1], 16)
p = getPrime(BITS)
while True:
A = ZZ(randrange(1, p))
B = ZZ(randrange(1, p))
if (4 * A^3 + 27 * B^2) % p == 0:
continue
E = EllipticCurve(GF(p), [A, B])
n = E.order()
if is_prime(n) and n != p and n != p + 1:
break
G = E.random_point()
Q = a * G
print(f"p = {p}")
print(f"A = {A}")
print(f"B = {B}")
print(f"n = {n}")
print(f"G = ({ZZ(G.xy()[0])}, {ZZ(G.xy()[1])})")
print(f"Q = ({ZZ(Q.xy()[0])}, {ZZ(Q.xy()[1])})")
# p = 1208925819614629174270411
# A = 183150304136760995950581
# B = 794569627338707454052582
# n = 1208925819612932406971299
# G = (181528231928396052728802, 1540136182689226613050)
# Q = (339758143822552101710854, 503250777866725616991088)

分析

没有任何技巧的 ECDLP…

让 AI 用 c 写了个爆破程序,跑两个小时

EXP

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
// rho80.c — Parallel Pollard rho (distinguished points) for ECDLP on short
// Weierstrass curves y^2 = x^3 + A x + B over GF(p) with p < 2^80.
//
// Given base point G of prime order n and Q = a*G, finds a.
//
// Random walk: P -> P + T [h(x(P))] over a fixed table of 32 points;
// 16 entries are d_j *G, 16 are Q + d_j* G. Each walk tracks (c, alpha) with
// state = alpha *Q + c* G (mod n). A distinguished-point collision between two
// different lineages yields alpha_diff * a == c_diff (mod n) (or the negated
// variant, distinguished by the y parity bit), solved via one inversion mod n
// and verified by an independent scalar multiplication.
//
// Arithmetic: 2x64-bit limbs, Montgomery representation with R = 2^128.
// Hot loop: batched affine additions with Montgomery-trick batch inversion.
//
// Usage: ./rho80 <instance.txt> <threads> [dpbits] [walks_per_thread]
// ./rho80 selftest <instance.txt>
// Instance line: <name> <p> <n> <A> <B> <gx> <gy> <qx> <qy> <secret_hex_or_0>
// (all numbers hex, no 0x prefix; secret optional, used only to check result)

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <pthread.h>
#include <stdatomic.h>
#include <time.h>
#include <unistd.h>
#include <inttypes.h>
#include <math.h>

typedef unsigned __int128 u128;
typedef struct { uint64_t a0, a1; } u80; /* value = a0 + a1*2^64 < 2^80 */

static inline uint64_t splitmix64(uint64_t *s) {
uint64_t z = (*s += 0x9E3779B97F4A7C15ULL);
z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ULL;
z = (z ^ (z >> 27)) * 0x94D049BB133111EBULL;
return z ^ (z >> 31);
}

static inline int u80_ge(u80 a, u80 b) {
return a.a1 > b.a1 || (a.a1 == b.a1 && a.a0 >= b.a0);
}
static inline int u80_eq(u80 a, u80 b) {
return a.a0 == b.a0 && a.a1 == b.a1;
}

/* ---------------- Montgomery field (generic over modulus) ---------------- */

typedef struct { u80 m; uint64_t mp0; u80 R2; } Fld;

static inline u80 f_subraw(u80 a, u80 b) {
uint64_t br = (a.a0 < b.a0);
u80 r = { a.a0 - b.a0, a.a1 - b.a1 - br };
return r;
}
static inline u80 f_add(const Fld *F, u80 a, u80 b) {
uint64_t lo = a.a0 + b.a0;
uint64_t c = (lo < a.a0);
uint64_t hi = a.a1 + b.a1 + c;
u80 s = { lo, hi };
return u80_ge(s, F->m) ? f_subraw(s, F->m) : s;
}
static inline u80 f_sub(const Fld *F, u80 a, u80 b) {
if (u80_ge(a, b)) return f_subraw(a, b);
/* m - b (0 < b < m guaranteed at all call sites) */
uint64_t br = (F->m.a0 < b.a0);
u80 nb = { F->m.a0 - b.a0, F->m.a1 - b.a1 - br };
return f_add(F, a, nb);
}
static inline u80 f_mul(const Fld *F, u80 a, u80 b) {
u128 t0 = (u128)a.a0 * b.a0; /* < 2^128 */
u128 t1 = (u128)a.a0 * b.a1; /* < 2^80 */
u128 t2 = (u128)a.a1 * b.a0; /* < 2^80 */
u128 t3 = (u128)a.a1 * b.a1; /* < 2^32 */
uint64_t r0 = (uint64_t)t0;
u128 xs = (t0 >> 64) + (uint64_t)t1 + (uint64_t)t2; /* < 2^66 */
uint64_t r1 = (uint64_t)xs;
uint64_t r2 = (uint64_t)((xs >> 64) + (t1 >> 64) + (t2 >> 64) + t3); /* < 2^33 */
/* two REDC iterations: T <- (T + m *k)/2^64 with k = mp0* T_lo */
for (int it = 0; it < 2; it++) {
uint64_t k = r0 * F->mp0;
u128 pl = (u128)F->m.a0 * k; /* < 2^128 */
u128 ph = (u128)F->m.a1 * k; /* < 2^80 */
uint64_t pl0 = (uint64_t)pl, pl1 = (uint64_t)(pl >> 64);
uint64_t ph0 = (uint64_t)ph, ph1 = (uint64_t)(ph >> 64);
uint64_t c0 = (r0 + pl0 < r0);
u128 mid = (u128)r1 + pl1 + ph0 + c0; /* < 2^66 */
uint64_t nr1 = (uint64_t)mid;
uint64_t nr2 = r2 + ph1 + (uint64_t)(mid >> 64);
r0 = nr1; r1 = nr2; r2 = 0;
}
u80 res = { r0, r1 }; /* < 2m */
return u80_ge(res, F->m) ? f_subraw(res, F->m) : res;
}
static void fld_init(Fld *F, u80 m) {
F->m = m;
uint64_t inv = m.a0;
for (int i = 0; i < 6; i++) inv *= 2 - m.a0 * inv;
F->mp0 = 0ULL - inv;
u80 r = { 1, 0 };
for (int i = 0; i < 256; i++) r = f_add(F, r, r);
F->R2 = r;
}
static inline u80 f_tomont(const Fld *F, u80 a) { return f_mul(F, a, F->R2); }
static inline u80 f_frommont(const Fld *F, u80 a) { return f_mul(F, a, (u80){1, 0}); }
static u80 f_pow(const Fld *F, u80 base, u80 e) {
u80 r = f_tomont(F, (u80){1, 0});
for (int i = 79; i >= 0; i--) {
r = f_mul(F, r, r);
int bit = (i < 64) ? (int)((e.a0 >> i) & 1) : (int)((e.a1 >> (i - 64)) & 1);
if (bit) r = f_mul(F, r, base);
}
return r;
}
static inline u80 f_inv(const Fld *F, u80 a) {
return f_pow(F, a, f_sub(F, F->m, (u80){2, 0}));
}

/* ---------------- curve points (affine, Montgomery domain) ---------------- */

typedef struct { u80 x, y; int inf; } Pt;

static Fld FP, FN; /* GF(p) and Z/n */
static u80 A_m, B_m, THREE_M; /* curve params in mont form */
static Pt Gp, Qp;
static Pt PT_INF;

static Pt pt_add(const Fld *F, Pt P, Pt T) {
if (P.inf) return T;
if (T.inf) return P;
if (u80_eq(P.x, T.x)) {
if (u80_eq(P.y, T.y)) {
if ((P.y.a0 | P.y.a1) == 0) return PT_INF; /* 2-torsion: n prime, unreachable */
u80 num = f_add(F, f_mul(F, f_mul(F, P.x, P.x), THREE_M), A_m);
u80 den = f_add(F, P.y, P.y);
u80 lam = f_mul(F, num, f_inv(F, den));
u80 x3 = f_sub(F, f_mul(F, lam, lam), f_add(F, P.x, P.x));
u80 y3 = f_sub(F, f_mul(F, lam, f_sub(F, P.x, x3)), P.y);
Pt r = { x3, y3, 0 };
return r;
}
return PT_INF;
}
u80 lam = f_mul(F, f_sub(F, T.y, P.y), f_inv(F, f_sub(F, T.x, P.x)));
u80 x3 = f_sub(F, f_sub(F, f_mul(F, lam, lam), P.x), T.x);
u80 y3 = f_sub(F, f_mul(F, lam, f_sub(F, P.x, x3)), P.y);
Pt r = { x3, y3, 0 };
return r;
}

static Pt pt_mul(const Fld *F, Pt P, u80 k) {
Pt R = PT_INF;
for (int i = 79; i >= 0; i--) {
R = pt_add(F, R, R);
int bit = (i < 64) ? (int)((k.a0 >> i) & 1) : (int)((k.a1 >> (i - 64)) & 1);
if (bit) R = pt_add(F, R, P);
}
return R;
}

/* ---------------- walk table ---------------- */

#define NT 32 /* 0..15: d_j *G (alpha+0); 16..31: Q + d_j* G (alpha+1) */
static u80 Tx[NT], Ty[NT];
static u80 Td[NT]; /* mont form mod n */

/* random-ish value in [1, n): u80 draw reduced mod n (tiny bias irrelevant
* for walk seeds; rejection on the full 2^80 range would hang for small n) */
static u80 rand_mod_n(uint64_t *rng) {
u128 v = (u128)splitmix64(rng) << 64 | splitmix64(rng);
u128 m = ((u128)FN.m.a1 << 64) | FN.m.a0;
u128 r = v % m;
u80 out = { (uint64_t)r, (uint64_t)(r >> 64) };
if (!out.a0 && !out.a1) out.a0 = 1;
return out;
}

static void tbl_init(void) {
uint64_t rng = 0xDEADBEEFCAFEBABEULL;
for (int j = 0; j < NT; j++) {
u80 d = rand_mod_n(&rng);
Pt T = pt_mul(&FP, Gp, d);
if (j >= 16) T = pt_add(&FP, T, Qp);
Tx[j] = T.x; Ty[j] = T.y;
Td[j] = f_tomont(&FN, d);
}
}

/* ---------------- distinguished-point table ---------------- */

#define TBITS 18
#define TSIZE (1u << TBITS)
typedef struct {
uint64_t xlo, xhi; /* mont x */
uint64_t clo, chi; /* c, mont mod n */
uint64_t al; /* alpha */
uint8_t ypar; /* parity of mont y */
uint8_t used;
} DEnt;

static DEnt *dtab;
static pthread_mutex_t tabmux = PTHREAD_MUTEX_INITIALIZER;

static atomic_int won;
static atomic_ullong total_hops;
static uint64_t dp_mask;
static long double expected_total;
static u80 a_solved;

static void print_u80_hex(const char *tag, u80 v) {
if (v.a1) printf("%s%llx%016llx\n", tag, (unsigned long long)v.a1, (unsigned long long)v.a0);
else printf("%s%llx\n", tag, (unsigned long long)v.a0);
}

static void try_dp(u80 x, u80 y, u80 c, uint64_t al) {
uint8_t ypar = (uint8_t)(y.a0 & 1);
uint64_t h = x.a0 * 0x9E3779B97F4A7C15ULL ^ x.a1 * 0xC2B2AE3D27D4EB4FULL;
uint64_t idx = (h >> 44) & (TSIZE - 1);
pthread_mutex_lock(&tabmux);
for (int probes = 0; probes < 4096; probes++, idx = (idx + 1) & (TSIZE - 1)) {
DEnt *e = &dtab[idx];
if (!e->used) {
e->xlo = x.a0; e->xhi = x.a1;
e->clo = c.a0; e->chi = c.a1;
e->al = al; e->ypar = ypar; e->used = 1;
break;
}
if (e->xlo == x.a0 && e->xhi == x.a1) {
if (e->al != al || e->clo != c.a0 || e->chi != c.a1) {
u80 c1 = { e->clo, e->chi };
uint64_t al1 = e->al;
int ok = 0;
u80 a;
if (e->ypar == ypar) {
/* (al1 - al) * a == c - c1 (mod n) */
int64_t d = (int64_t)al1 - (int64_t)al;
if (d != 0) {
u80 den = (d > 0) ? (u80){ (uint64_t)d, 0 }
: f_sub(&FN, FN.m, (u80){ (uint64_t)(-d), 0 });
u80 num = f_sub(&FN, c, c1);
a = f_frommont(&FN, f_mul(&FN, num, f_inv(&FN, f_tomont(&FN, den))));
ok = 1;
}
} else {
/* (al1 + al) * a == -(c + c1) (mod n) */
uint64_t s = al1 + al;
if (s != 0) {
u80 num = f_sub(&FN, FN.m, f_add(&FN, c, c1));
a = f_frommont(&FN, f_mul(&FN, num, f_inv(&FN, f_tomont(&FN, (u80){ s, 0 }))));
ok = 1;
}
}
if (ok) {
Pt R = pt_mul(&FP, Gp, a);
if (!R.inf && u80_eq(R.x, Qp.x) && u80_eq(R.y, Qp.y)) {
a_solved = a;
atomic_store(&won, 1);
printf("\n*** SOLVED ***\n");
print_u80_hex("a_hex = ", a);
fflush(stdout);
}
}
}
break;
}
}
pthread_mutex_unlock(&tabmux);
}

/* ---------------- workers ---------------- */

typedef struct { int tid; int W; } TArg;

static void *worker(void *varg) {
TArg *arg = (TArg *)varg;
const int W = arg->W;
const Fld F = FP; /* local copies for register allocation */
const Fld Fn = FN;
uint64_t rng = 0x243F6A8885A308D3ULL ^ ((uint64_t)arg->tid * 0x13198A2E03707344ULL)
^ ((uint64_t)time(NULL) * 0xA4093822299F31D0ULL);

u80 *X = malloc(W * sizeof(u80));
u80 *Y = malloc(W * sizeof(u80));
u80 *C = malloc(W * sizeof(u80));
u80 *dx = malloc(W * sizeof(u80));
u80 *dy = malloc(W * sizeof(u80));
u80 *iv = malloc(W * sizeof(u80));
u80 *pre = malloc(W * sizeof(u80));
uint64_t *AL = malloc(W * sizeof(uint64_t));
int *idx = malloc(W * sizeof(int));

for (int w = 0; w < W; w++) {
u80 cw = rand_mod_n(&rng);
Pt S = pt_mul(&F, Gp, cw);
if (S.inf) { w--; continue; }
X[w] = S.x; Y[w] = S.y;
C[w] = f_tomont(&Fn, cw);
AL[w] = 0;
}

uint64_t since = 0;
while (!atomic_load_explicit(&won, memory_order_relaxed)) {
for (int w = 0; w < W; w++) {
/* index bits 32..36: present for any modulus >= 2^40, and disjoint
* from the DP bits (0..dpbits, dpbits <= 26) */
int j = (int)((X[w].a0 >> 32) & 31u);
idx[w] = j;
dx[w] = f_sub(&F, Tx[j], X[w]);
dy[w] = f_sub(&F, Ty[j], Y[w]);
}
/* batch invert dx [] */
pre[0] = dx[0];
for (int w = 1; w < W; w++) pre[w] = f_mul(&F, pre[w - 1], dx[w]);
u80 acc = f_inv(&F, pre[W - 1]);
for (int w = W - 1; w >= 1; w--) {
iv[w] = f_mul(&F, acc, pre[w - 1]);
acc = f_mul(&F, acc, dx[w]);
}
iv[0] = acc;
/* apply step */
for (int w = 0; w < W; w++) {
int j = idx[w];
u80 lam = f_mul(&F, dy[w], iv[w]);
u80 x3 = f_sub(&F, f_sub(&F, f_mul(&F, lam, lam), X[w]), Tx[j]);
u80 y3 = f_sub(&F, f_mul(&F, lam, f_sub(&F, X[w], x3)), Y[w]);
X[w] = x3; Y[w] = y3;
C[w] = f_add(&Fn, C[w], Td[j]);
AL[w] += (uint64_t)(j >> 4);
if ((X[w].a0 & dp_mask) == 0) try_dp(X[w], Y[w], C[w], AL[w]);
}
since += (uint64_t)W;
if (since >= (1ULL << 24)) {
atomic_fetch_add_explicit(&total_hops, since, memory_order_relaxed);
since = 0;
}
}
atomic_fetch_add_explicit(&total_hops, since, memory_order_relaxed);

free(X); free(Y); free(C); free(dx); free(dy); free(iv); free(pre); free(AL); free(idx);
return NULL;
}

/* ---------------- instance / helpers ---------------- */

static u80 parse80(const char *s) {
u128 v = 0;
for (const char *c = s; *c; c++) {
int d;
if (*c >= '0' && *c <= '9') d = *c - '0';
else if (*c >= 'a' && *c <= 'f') d = *c - 'a' + 10;
else if (*c >= 'A' && *c <= 'F') d = *c - 'A' + 10;
else break;
v = (v << 4) | (u128)d;
}
u80 r = { (uint64_t)v, (uint64_t)(v >> 64) };
return r;
}

typedef struct {
char name[64];
u80 p, n, A, B, gx, gy, qx, qy, secret;
} Inst;

static int load_inst(const char *path, Inst *I) {
FILE *f = fopen(path, "r");
if (!f) { perror("open"); return 0; }
char line[4096];
if (!fgets(line, sizeof line, f)) { fclose(f); return 0; }
fclose(f);
char *tok[12];
int nt = 0;
for (char *t = strtok(line, " \t\r\n"); t && nt < 12; t = strtok(NULL, " \t\r\n"))
tok[nt++] = t;
if (nt < 9) { fprintf(stderr, "bad instance (need >=9 tokens)\n"); return 0; }
snprintf(I->name, sizeof I->name, "%s", tok[0]);
I->p = parse80(tok[1]);
I->n = parse80(tok[2]);
I->A = parse80(tok[3]);
I->B = parse80(tok[4]);
I->gx = parse80(tok[5]);
I->gy = parse80(tok[6]);
I->qx = parse80(tok[7]);
I->qy = parse80(tok[8]);
I->secret = nt >= 10 ? parse80(tok[9]) : (u80){0, 0};
return 1;
}

static int on_curve(const Fld *F, u80 x, u80 y) {
u80 lhs = f_mul(F, y, y);
u80 rhs = f_add(F, f_add(F, f_mul(F, f_mul(F, x, x), x),
f_mul(F, A_m, x)), B_m);
return u80_eq(lhs, rhs);
}

static int selftest(const Inst *I) {
fld_init(&FP, I->p);
fld_init(&FN, I->n);
A_m = f_tomont(&FP, I->A);
B_m = f_tomont(&FP, I->B);
THREE_M = f_tomont(&FP, (u80){3, 0});
PT_INF.inf = 1;
int fail = 0;
uint64_t rng = 1;
/* field ops against u128 reference (small operands) */
for (int i = 0; i < 500; i++) {
u80 a = { splitmix64(&rng) >> 24, 0 };
u80 b = { splitmix64(&rng) >> 24, 0 };
if (u80_ge(a, FP.m) || u80_ge(b, FP.m)) { i--; continue; }
u128 prod = (u128)a.a0 * b.a0;
u128 mod = ((u128)FP.m.a1 << 64) | FP.m.a0;
u128 ref = prod % mod;
u80 got = f_frommont(&FP, f_mul(&FP, f_tomont(&FP, a), f_tomont(&FP, b)));
u80 refu = { (uint64_t)ref, (uint64_t)(ref >> 64) };
if (!u80_eq(got, refu)) { printf("MUL FAIL %d\n", i); fail = 1; break; }
/* add/sub */
u128 sum = (u128)a.a0 + b.a0;
u128 refa = sum % mod;
u80 gota = f_add(&FP, a, b);
u80 refua = { (uint64_t)refa, (uint64_t)(refa >> 64) };
if (!u80_eq(gota, refua)) { printf("ADD FAIL %d\n", i); fail = 1; break; }
u80 gotb = f_add(&FP, f_sub(&FP, a, b), b);
if (!u80_eq(gotb, a)) { printf("SUB FAIL %d\n", i); fail = 1; break; }
}
printf("field selftest: %s\n", fail ? "FAIL" : "PASS");
/* curve checks */
Gp.x = f_tomont(&FP, I->gx); Gp.y = f_tomont(&FP, I->gy); Gp.inf = 0;
Qp.x = f_tomont(&FP, I->qx); Qp.y = f_tomont(&FP, I->qy); Qp.inf = 0;
printf("G on curve: %d\n", on_curve(&FP, Gp.x, Gp.y));
printf("Q on curve: %d\n", on_curve(&FP, Qp.x, Qp.y));
Pt nG = pt_mul(&FP, Gp, I->n);
printf("n*G == O: %d\n", nG.inf);
return !fail && on_curve(&FP, Gp.x, Gp.y) && on_curve(&FP, Qp.x, Qp.y) && nG.inf;
}

int main(int argc, char **argv) {
if (argc < 3) {
fprintf(stderr, "usage: %s <instance> <threads> [dpbits] [W] | %s selftest <instance>\n",
argv[0], argv[0]);
return 1;
}
Inst I;
if (!load_inst(argv[argc - 1 < 2 ? 1 : (strcmp(argv[1], "selftest") == 0 ? 2 : 1)], &I))
return 1;
if (strcmp(argv[1], "selftest") == 0) {
return selftest(&I) ? 0 : 1;
}
int threads = atoi(argv[2]);
if (threads < 1) threads = 1;
int W = (argc >= 5) ? atoi(argv[4]) : 256;
if (W < 8) W = 8;

fld_init(&FP, I.p);
fld_init(&FN, I.n);
A_m = f_tomont(&FP, I.A);
B_m = f_tomont(&FP, I.B);
THREE_M = f_tomont(&FP, (u80){3, 0});
PT_INF.inf = 1;
Gp.x = f_tomont(&FP, I.gx); Gp.y = f_tomont(&FP, I.gy); Gp.inf = 0;
Qp.x = f_tomont(&FP, I.qx); Qp.y = f_tomont(&FP, I.qy); Qp.inf = 0;

if (!on_curve(&FP, Gp.x, Gp.y) || !on_curve(&FP, Qp.x, Qp.y)) {
fprintf(stderr, "instance failed on-curve check\n");
return 1;
}

long double nld = (long double)I.n.a1 * 18446744073709551616.0L + (long double)I.n.a0;
expected_total = sqrtl(3.14159265358979323846L * nld / 2.0L);

int dpbits = (argc >= 4) ? atoi(argv[3]) : 0;
if (dpbits <= 0) {
dpbits = (int)(log2l(expected_total)) - 14;
if (dpbits < 8) dpbits = 8;
if (dpbits > 26) dpbits = 26;
}
dp_mask = (1ULL << dpbits) - 1;

tbl_init();
dtab = calloc(TSIZE, sizeof(DEnt));

printf("instance=%s threads=%d W=%d dpbits=%d\n", I.name, threads, W, dpbits);
print_u80_hex("p = ", I.p);
print_u80_hex("n = ", I.n);
printf("expected hops ~ %.4Le\n", (long double)expected_total);
fflush(stdout);

pthread_t *th = malloc(threads * sizeof(pthread_t));
TArg *args = malloc(threads * sizeof(TArg));
time_t t0 = time(NULL);
for (int i = 0; i < threads; i++) {
args[i].tid = i; args[i].W = W;
pthread_create(&th[i], NULL, worker, &args[i]);
}
unsigned long long last = 0;
while (!atomic_load(&won)) {
sleep(30);
if (atomic_load(&won)) break;
unsigned long long h = atomic_load(&total_hops);
double el = (double)(time(NULL) - t0);
double rate = el > 0 ? h / el : 0;
double eta = rate > 0 ? (expected_total - (double)h) / rate : -1;
printf("[t=%5.0fs] hops=%.4Le rate=%.3Le/s progress=%.2f%% eta=%.0fs\n",
el, (long double)h, (long double)rate,
100.0 * (double)h / (double)expected_total, eta);
fflush(stdout);
(void)last;
}
for (int i = 0; i < threads; i++) pthread_join(th[i], NULL);
unsigned long long h = atomic_load(&total_hops);
printf("done in %.0fs, total hops %llu\n", (double)(time(NULL) - t0), h);
print_u80_hex("a_hex = ", a_solved);
if (I.secret.a0 || I.secret.a1)
printf("check vs secret: %s\n", u80_eq(a_solved, I.secret) ? "MATCH" : "MISMATCH!!");
return 0;
}

charlotte

源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from math import prod
from Crypto.Util.number import bytes_to_long

n = p * q
phi = (p - 1) * (q - 1)

d0, d1, d2 = private_exponents


e0 = pow(d0, -1, phi)
e1 = pow(d1, -1, phi)
e2 = pow(d2, -1, phi)
assert (
len(e0.to_bytes((e0.bit_length() + 7) // 8, "big"))
== len(e1.to_bytes((e1.bit_length() + 7) // 8, "big"))
== len(e2.to_bytes((e2.bit_length() + 7) // 8, "big"))
)


fingerprint_1 = pow(e1, 3, n)
fingerprint_2 = pow(e2, 3, n)

E = e0 * e1 * e2
c = pow(bytes_to_long(flag), E, n)

分析

做了个小工具用来看损坏的 pem der crt 等文件:

1
https://github.com/zha0y3n/pemrescue

对得到的三份 pem 文件分析:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
modulus (n)  128 字节
d1925db05989bd088ed9631782f21ab83539c07facfccadd7c9e93b7d114ecbf3705bfc32f797e5dd35f3c1f17f025513086c728f4f15127b81efcd2d6cd9d8e003cc3aee5a650efb0ae42db395b41f9944326cc1a4485363ab53ee066262102b519a984b87fe31cfcdc83af7d0897e072e9e00d60ffcdaa42cffb151d185707
publicExponent (e) ⚠ 96/128 字节
298933e98aafcca4e8e69e3ce982eb100a5955b6365084c6e52f6e08226e698b9395bf7b9af2793874dc9d13470cbc31d511a92110c24ca7e2188211062598052b53e371b2bb4c33db0a12c6835aad3f7c3fbb7bf0d502afc03719ee4df722e2

modulus (n) 128 字节
d1925db05989bd088ed9631782f21ab83539c07facfccadd7c9e93b7d114ecbf3705bfc32f797e5dd35f3c1f17f025513086c728f4f15127b81efcd2d6cd9d8e003cc3aee5a650efb0ae42db395b41f9944326cc1a4485363ab53ee066262102b519a984b87fe31cfcdc83af7d0897e072e9e00d60ffcdaa42cffb151d185707
publicExponent (e) ⚠ 96/128 字节
393f78c4bbef679d186d8df01eb49ba11d8afaf423ff25fe90ebcaa469d3cfce248ee908c9273031947ba42cb8842106feab0a95e7b559bfe7ab7f41109e7bd11873f36c1eabc6cbe95c2a73619e5477908cec02242bda65590f5eedce4326a1

modulus (n) 128 字节
d1925db05989bd088ed9631782f21ab83539c07facfccadd7c9e93b7d114ecbf3705bfc32f797e5dd35f3c1f17f025513086c728f4f15127b81efcd2d6cd9d8e003cc3aee5a650efb0ae42db395b41f9944326cc1a4485363ab53ee066262102b519a984b87fe31cfcdc83af7d0897e072e9e00d60ffcdaa42cffb151d185707
publicExponent (e) 128 字节
34953cf008e4d99ab74ad2a5356e583cf9a3eae2227c7582a04246d92b2dbc98b70b860e8eab5446649a3dbee74b329f4502b9ce8727872e36ab6b1cd41d539dfdb5b80dabfb4f1c951dd346bb9490265184ee92e1826cf1d529632a0465ee597246183a2731242968831a9153808647e8a061544033829abfb71d15588f0cc9

发现三份模数相同,且前两份的公钥指数是缺了 32 字节的。再看给出的 fingerprint:

1
2
fingerprint_1 = 117621280447918956283798935355235757929776352599339931163286329028682288672928741296937650952747752164593075018079028467934679452946461204759555416978276173572349600240326984045009804232377138973495099451743567280873976580203792736765439561418352263559096298617341483219124316753620841386349210989125279314842
fingerprint_2 = 39329072771123843841472391585293227954224412823311391442958322610173321736884077961544300334756676692058523958855671814128654378389736884837669229612690790592451391611463044331025427743215976335544181395997619074049060029702945823017674337670737757740219953460965325772553356128080668320929608609852645125536

fp=e3modn 。缺失的 32 字节对应 256 位,那么有方程

f(x)=(H⋅2256+x)3−fp≡0(modn)

由 copper 知小根的理论上界是 n1/3 ,大约为 341 比特,大于未知的 256 比特,所以做两次 copper 就能恢复 e1,e2 。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
PR = PolynomialRing(Zmod(n), "x")
x = PR.gen()


def recover(e_high, fp):
f = (e_high * 2**256 + x) ** 3 - fp
for sol in f.monic().small_roots(X=2**256, beta=1.0, epsilon=1 / 25):
e = int(sol) + e_high * 2**256
if pow(e, 3, n) == fp:
return e
return None


print(recover(e1_high, fingerprint_1))
print(recover(e2_high, fingerprint_2))
'''
29167534856209040944013015837210291545850677991090249582121668961685345022880267152323979496231417863714431871469204661311468761766895411193558424365593218535204028439097484868454583792085851535249063291501106982194676504356101091017673817364820162591726112868636931467505624386956203462073543788863064018171
40200868158879409014834223061548283940354398476233783099488862205769098587076668162571983970671187790811297239091672879694093090133562575046818767167084780411583591213495863883586251461449974439510410596826715087610633854614617118971344882097629563586890023578486567937692768090614767128595991309974127400297
'''

接下来就是本题的重点。在常规 RSA 中,当解密指数 d<N0.25 时有维纳攻击; d<N0.292 时有 Boneh-Durfee 攻击。但是这道题中 private_exponent_bits = 384, δ=384/1024=0.375 ,只能使用 HGS 攻击(当拥有 k 个同模数的解密指数时攻击界限可以大幅扩展),攻击界限如下:

攻击方法 解密指数的典型攻击范围
传统 Wiener (d < N^{1/4}/3)
Howgrave-Graham–Seifert(两个指数) (d_1, d_2 < N^{5/14}),启发式
Sarkar–Maitra(两个指数) 约 (N^{0.416})
Takayasu–Kunihiro((k) 个指数) (d_i < N^{1-\sqrt{2/(3k+1)}})

下面使用 HGS 三指数八维格攻击,其界限为 δ<0.4 。

在 RSA 中,私钥方程是 eidi−aiφ(N)=1 (其中 ai 是由模运算产生的未知系数)。由于 di 较小,而 ai 的大小经过推导可被证明为和 di 大致相同(即 di,ai<Nδ ),因此我们虽然不知道 di ,但有以下两个技巧:

  1. 由于 φ(N) 和 N 的大小相近。记误差项 s=p+q−1 ,于是有 φ(N)=N−s 。将这个式子代入到私钥方程,有 eidi−aiN+ais=1 。将包含已知数 N,ei 与未知数 di,ai 的项移到左侧,将仅含误差项的表达式移到右侧,记这个代数式为 Wi (Wiener 型关系式):

    Wi=eidi−aiN=1−ais

    在代数式中, eidi≈N⋅Nδ=N1+δ , aiN≈Nδ⋅N=N1+δ ,但二者的差值约为 ai⋅s≈Nδ+0.5 ,远小于模数 N (也即由公开数据 (ei,−N) 造出的格基中能够找到一个显著短的向量)

  2. 两个密钥方程之间交叉相乘并相减,可以消去 φ(N) 。假设我们有两组来自同一个模数 N 的公私钥对 (ei,di) 和 (ej,dj) ,分别有:

    eidi=1+aiφ(N)ejdj=1+ajφ(N)

    试着将方程一两边同乘 aj ,方程二两边同乘 ai 后相减以消去 aiajφ(N) ,就有 ajeidi−aiejdj=aj−ai ,将这个差值记为 Gij (Guo 型关系式):

    Gij=ajeidi−aiejdj=aj−ai

    左侧两项的大小都为 Nδ⋅N⋅Nδ=N2δ+1 ,但二者差值 |aj−ai|≤max(ai,aj)=O(Nδ) 。

观察到 Guo 型关系式的消去方式明显更好:数值大小显著小于前者( Nδ<Nδ+0.5 ),并且没有任何近似误差(前者使用 N 代替 φ(N) ),那为什么在实际造格子的过程中不能只用后者?原因是后者只能造出齐次方程,没有锚定模数 N ,使得格基向量退化。因此在实际的造格中,二者是相辅相成的(前者引入模数 N 以提供坐标约束;后者拉低范数上限,使得约简更迅速)

对于 k=3 ,HGS 构造一个 8 维格。对于每个 i ,选择 ai 或 di 中的一个,再将三者相乘以构造系数向量:

x=(a1a2a3,d1a2a3,a1d2a3,…,d1d2d3)T

在正式造格之前,我们先声明 8 个关系式:

F1=a1a2a3F2=a2a3W1F3=a3G12F4=a3W1W2F5=a2G13F6=W1G23F7=W2G13F8=W1W2W3

需要让他们成为目标向量的 8 个元素。对于 F1 ,直接配凑出格基第一列为 (1,0,0,0,0,0,0,0)T ;对于 F2 , F2=a2a3(e1d1−a1N)=e1(d1a2a3)−N(a1a2a3)=e1x2−Nx1 ,故格基第二列为 (−N,e1,0,0,0,0,0,0)T 。由此类推,得到格基 B3 :

B3=(1−N0N2000−N30e1e1−e1Ne10−e1Ne1N200−e2−e2N0−e2N0e2N2000e1e20e1e2e1e2−e1e2N0000−e3e3Ne3Ne3N200000−e1e30−e1e3N000000−e2e3−e2e3N0000000e1e2e3)

但原始目标向量中元素大小并不同(例如 F1=|a1a2a3|=O(N3δ) ,而 F8=W1W2W3=|∏i=13(1−ais)|=O(N3δ+3/2) ),因此还需要进行缩放。定义对角缩放矩阵:

D3=diag(N3/2,N,Nδ+3/2,N1/2,Nδ+3/2,Nδ+1,Nδ+1,1)

用缩放矩阵和原始矩阵相乘,即可得到最终格基:

B3′=B3D3

最后讲约化后如何恢复私钥。得到正确目标向量后先撤销缩放( v=v′D3−1 ),再求解 B3Tx=v ,就能得到系数向量 x=(a1a2a3,d1a2a3,a1d2a3,…,d1d2d3)T 。

提取 x1=a1a2a3 和 x2=d1a2a3 ,二者相除得到 a1/d1 。由 e1d1−a1φ(N)=1 ,有:

e1φ(N)=a1d1+1d1φ(N)

代入即可恢复 φ(N) ,本题也就完美解决。

EXP

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import base64, json, re
from itertools import combinations
from math import isqrt, prod
from sage.all import *
from params import *


def construct_relation(N, monomial, xs):
"""Guo 方程 (x_i - x_j) 与 Wiener 方程 (x_i - N) 的乘积关系"""
vs = monomial.variables()
l = [xs[i] for i in range(xs.index(vs[-1]) + 1)]
R, u, v = 1, 0, 0
i = len(vs)
for var in vs:
if var != xs[0] and var < l[0] and len(l) >= 2 * i:
R *= l[0] - var # Guo: e_i k_j - e_j k_i 型关系
l.pop(0)
v += 1
else:
R *= var - N # Wiener: e_i d_i - k_i N 型关系
u += 1
l.remove(var)
i -= 1
return R, u, v


def hgs_factor(N, es, alpha):
k = len(es)
pr = ZZ[",".join(f"x{i}" for i in range(k))]
xs = pr.gens()
monomials = [1]
for i, xi in enumerate(xs):
monomials.append(xi)
for j in range(i):
for comb in combinations(xs[:i], j + 1):
monomials.append(prod(comb) * xi)
L = matrix(ZZ, len(monomials))
exp_a, exp_b = [k], [0]
for col, mon in enumerate(monomials):
if col == 0:
L[0, 0] = 1
continue
R, u, v = construct_relation(N, mon, xs)
for row, m2 in enumerate(monomials):
if row == 0:
L[0, col] = R.constant_coefficient()
else:
L[row, col] = R.monomial_coefficient(m2) * m2(*es)
exp_a.append(k - v)
exp_b.append(u / 2)
print(f"[.] monomials: {len(monomials)}, lattice {L.nrows()}x{L.ncols()}")
ma, mb = max(exp_a), max(exp_b)
D = diagonal_matrix(
ZZ, [int(RR(N) ** ((ma - a) * alpha + (mb - b))) for a, b in zip(exp_a, exp_b)]
)
Ls = L * D
print("[.] running LLL...")
Lr = Ls.LLL()
b = Ls.solve_left(Lr[0])
phi = round(b[1] / b[0] * es[0])
# 由 phi 分解 N: p+q = N+1-phi
s = N + 1 - ZZ(phi)
p = ZZ((s - isqrt(s ^ 2 - 4 * N)) // 2)
q = ZZ((s + isqrt(s ^ 2 - 4 * N)) // 2)
return (p, q) if p * q == N else None


pq = hgs_factor(n, es, RR(384 / n.nbits()))
assert pq, "HGS failed"
p, q = pq
phi = (p - 1) * (q - 1)
print(f"[+] p = {p}\n[+] q = {q}")

dE = inverse_mod(e0 * e1 * e2, phi)
m = power_mod(c, dE, n)
flag = int(m).to_bytes((int(m).bit_length() + 7) // 8, "big")
print(flag.decode())