道隐于小成,言隐于荣华

UTCTF 2019 Crypto Write Up

该部分为本科期间wp备份。

由于UTCTF Challege的所有内容禁止下载,所以本WP的所有提及的题目文件将由官方的git库提供。

UTCTF题目附件:https://github.com/UTISSS/UTCTF

[basics] crypto

问题

Can you make sense of this file? by balex

binary.txt

解题过程

打开binary.txt文件之后,发现是个二进制文本。
用python写个脚本,先将bin转str并保存到res.txt中:

import os
f=open("binary.txt","r")
str1=f.read()
str1=str1.split(" ")
hex1=''
for i in str1:
    sum=0
    k=1
    for j in i[::-1]:
        if j=='1':
            sum+=k
        k*=2
    hex1+=chr(sum)
f=open("res.txt","w")
f.write(hex1)
f.close()

跑出来的结果如下:

Uh-oh, looks like we have another block of text, with some sort of special encoding. Can you figure out what this encoding is? (hint: if you look carefully, you'll notice that there only characters present are A-Z, a-z, 0-9, and sometimes / and +. See if you can find an encoding that looks like this one.)
TmV3IGNoYWxsZW5nZSEgQ2FuIHlvdSBmaWd1cmUgb3V0IHdoYXQncyBnb2luZyBvbiBoZXJlPyBJdCBsb29rcyBsaWtlIHRoZSBsZXR0ZXJzIGFyZSBzaGlmdGVkIGJ5IHNvbWUgY29uc3RhbnQuIChoaW50OiB5b3UgbWlnaHQgd2FudCB0byBzdGFydCBsb29raW5nIHVwIFJvbWFuIHBlb3BsZSkuCmt2YnNxcmQsIGl5ZSdibyBrdnd5Y2QgZHJvYm8hIFh5ZyBweWIgZHJvIHBzeGt2IChreG4gd2tpbG8gZHJvIHJrYm5vY2QuLi4pIHprYmQ6IGsgY2VsY2RzZGVkc3l4IG1zenJvYi4gU3ggZHJvIHB5dnZ5Z3N4cSBkb2hkLCBTJ2ZvIGRrdW94IHdpIHdvY2NrcW8ga3huIGJvenZrbW9uIG9mb2JpIGt2enJrbG9kc20gbXJrYmttZG9iIGdzZHIgayBteWJib2N6eXhub3htbyBkeSBrIG5zcHBvYm94ZCBtcmtia21kb2IgLSB1eHlneCBrYyBrIGNlbGNkc2RlZHN5eCBtc3pyb2IuIE1reCBpeWUgcHN4biBkcm8gcHN4a3YgcHZrcT8gcnN4ZDogR28gdXh5ZyBkcmtkIGRybyBwdmtxIHNjIHF5c3hxIGR5IGxvIHlwIGRybyBweWJ3a2QgZWRwdmtxey4uLn0gLSBncnNtciB3b2t4YyBkcmtkIHNwIGl5ZSBjb28gZHJrZCB6a2Rkb2J4LCBpeWUgdXh5ZyBncmtkIGRybyBteWJib2N6eXhub3htb2MgcHliIGUsIGQsIHAsIHYgaywga3huIHEga2JvLiBJeWUgbWt4IHpieWxrbHZpIGd5YnUgeWVkIGRybyBib3drc3hzeHEgbXJrYmttZG9iYyBsaSBib3p2a21zeHEgZHJvdyBreG4gc3hwb2Jic3hxIG15d3d5eCBneWJuYyBzeCBkcm8gT3hxdnNjciB2a3hxZWtxby4gS3h5ZHJvYiBxYm9rZCB3b2RyeW4gc2MgZHkgZWNvIHBib2Flb3htaSBreGt2aWNzYzogZ28gdXh5ZyBkcmtkICdvJyBjcnlnYyBleiB3eWNkIHlwZG94IHN4IGRybyBrdnpya2xvZCwgY3kgZHJrZCdjIHpieWxrbHZpIGRybyB3eWNkIG15d3d5eCBtcmtia21kb2Igc3ggZHJvIGRvaGQsIHB5dnZ5Z29uIGxpICdkJywga3huIGN5IHl4LiBZeG1vIGl5ZSB1eHlnIGsgcG9nIG1ya2JrbWRvYmMsIGl5ZSBta3ggc3hwb2IgZHJvIGJvY2QgeXAgZHJvIGd5Ym5jIGxrY29uIHl4IG15d3d5eCBneWJuYyBkcmtkIGNyeWcgZXogc3ggZHJvIE94cXZzY3Igdmt4cWVrcW8uCnJnaG54c2RmeXNkdGdodSEgcWdmIGlzYWsgY3RodHVpa2UgZGlrIHprbnRoaGt4IHJ4cWxkZ254c2xpcSByaXN5eWtobmsuIGlreGsgdHUgcyBjeXNuIGNneCBzeXkgcWdmeCBpc3hlIGtjY2d4ZHU6IGZkY3lzbnszaHJ4cWxkMTBoXzE1X3IwMHl9LiBxZ2YgdnR5eSBjdGhlIGRpc2QgcyB5Z2QgZ2MgcnhxbGRnbnhzbGlxIHR1IHBmdWQgemZ0eWV0aG4gZ2NjIGRpdHUgdWd4ZCBnYyB6c3V0ciBiaGd2eWtlbmssIHNoZSB0ZCB4a3N5eXEgdHUgaGdkIHVnIHpzZSBzY2RreCBzeXkuIGlnbGsgcWdmIGtocGdxa2UgZGlrIHJpc3l5a2huayE=

根据hint以及结尾结构,我们猜测base编码加密,采取base64解密,得到以下内容:

New challenge! Can you figure out what's going on here? It looks like the letters are shifted by some constant. (hint: you might want to start looking up Roman people).
kvbsqrd, iye'bo kvwycd drobo! Xyg pyb dro psxkv (kxn wkilo dro rkbnocd...) zkbd: k celcdsdedsyx mszrob. Sx dro pyvvygsxq dohd, S'fo dkuox wi wocckqo kxn bozvkmon ofobi kvzrklodsm mrkbkmdob gsdr k mybboczyxnoxmo dy k nsppoboxd mrkbkmdob - uxygx kc k celcdsdedsyx mszrob. Mkx iye psxn dro psxkv pvkq? rsxd: Go uxyg drkd dro pvkq sc qysxq dy lo yp dro pybwkd edpvkq{...} - grsmr wokxc drkd sp iye coo drkd zkddobx, iye uxyg grkd dro mybboczyxnoxmoc pyb e, d, p, v k, kxn q kbo. Iye mkx zbylklvi gybu yed dro bowksxsxq mrkbkmdobc li bozvkmsxq drow kxn sxpobbsxq mywwyx gybnc sx dro Oxqvscr vkxqekqo. Kxydrob qbokd wodryn sc dy eco pboaeoxmi kxkvicsc: go uxyg drkd 'o' crygc ez wycd ypdox sx dro kvzrklod, cy drkd'c zbylklvi dro wycd mywwyx mrkbkmdob sx dro dohd, pyvvygon li 'd', kxn cy yx. Yxmo iye uxyg k pog mrkbkmdobc, iye mkx sxpob dro bocd yp dro gybnc lkcon yx mywwyx gybnc drkd cryg ez sx dro Oxqvscr vkxqekqo.
rghnxsdfysdtghu! qgf isak cthtuike dik zknthhkx rxqldgnxsliq risyykhnk. ikxk tu s cysn cgx syy qgfx isxe kccgxdu: fdcysn{3hrxqld10h_15_r00y}. qgf vtyy cthe disd s ygd gc rxqldgnxsliq tu pfud zftyethn gcc ditu ugxd gc zsutr bhgvykenk, she td xksyyq tu hgd ug zse scdkx syy. iglk qgf khpgqke dik risyykhnk!

观察发现应该为对称加密,因此先尝试凯撒密码,其函数定义如下:

# https://stackoverflow.com/questions/3269686/short-rot13-function-python
def rot(n):
  from string import ascii_lowercase as lc, ascii_uppercase as uc, maketrans
  lookup = maketrans(lc + uc, lc[n:] + lc[:n] + uc[n:] + uc[:n])
  return lambda s: s.translate(lookup)

当尝试rot16的时候得到另一段密文,结果如下:

alright, you're almost there! Now for the final (and maybe the hardest...) part: a substitution cipher. In the following text, I've taken my message and replaced every alphabetic character with a correspondence to a different character - known as a substitution cipher. Can you find the final flag? hint: We know that the flag is going to be of the format utflag{...} - which means that if you see that pattern, you know what the correspondences for u, t, f, l a, and g are. You can probably work out the remaining characters by replacing them and inferring common words in the English language. Another great method is to use frequency analysis: we know that 'e' shows up most often in the alphabet, so that's probably the most common character in the text, followed by 't', and so on. Once you know a few characters, you can infer the rest of the words based on common words that show up in the English language. hwxdnitvoitjwxk! gwv yiqa sjxjkyau tya padjxxan hngbtwdnibyg hyiooaxda. yana jk i soid swn ioo gwvn yinu asswntk: vtsoid{3xhngbt10x_15_h00o}. gwv ljoo sjxu tyit i owt ws hngbtwdnibyg jk fvkt pvjoujxd wss tyjk kwnt ws pikjh rxwloauda, ixu jt naioog jk xwt kw piu istan ioo. ywba gwv axfwgau tya hyiooaxda!

根据提示,我们知道后面加密方式为移位代换密码。尝试词频分析,得到如下内容:

congratulations! you have finished the beginner cryptography challenge. here is a flag for all your hard efforts: utflag{3ncrypt10n_15_c00l}. you will find that a lot of cryptography is just building off this sort of basic knowledge, and it really is not so bad after all. hope you enjoyed the challenge!

flag为:utflag{3ncrypt10n_15_c00l}

Jacobi’s Chance Encryption

问题

Public Key :569581432115411077780908947843367646738369018797567841 Can you decrypt Jacobi's encryption?

by asper

flag.enc

def encrypt(m, pub_key):

    bin_m = ''.join(format(ord(x), '08b') for x in m)
    n, y = pub_key

    def encrypt_bit(bit):
        x = randint(0, n)
        if bit == '1':
            return (y * pow(x, 2, n)) % n
        return pow(x, 2, n)

    return map(encrypt_bit, bin_m)

解题过程

本题提供了加密后的enc文件以及public key、encrypt.py,从encrypt(m,public_key)中可以知道:

  1. y*pow(x,2,n)%n的值趋近于bit 0
  2. pow(x, 2, n)趋近于bit 1

因此,根据encrypt.py后面部分,先将flag .enc文件的map对应的bit位进行翻转操作,即将bit1转化成bit0,bit1转化成bit0

from pwn import *
f = open('flag.enc', 'r')
l = f.read()
final = ''
for m in l.strip().split(','):
    if not m:
        final+=''
    if m != '0':
        final+='0'
    else:
        final+='1'
print unbits(final)

得到结果:

utflag

注意:pwntools要求linux系统库支持,因此请在虚拟机中安装。

Tale of Two Cities

问题

Looks like this book got a little messed up... there are some weird characters in there.
by balex

Hint:hOpEfully thIS hint will help you!

A000788

tale-of-two-cities.txt

解题过程:

首先,我们找到一份附件修改来源的狄更斯原版《Tale of Two Cities》电子书。
之后,根据linux中的diff命令,我们可以找到不同内容:

$ diff tale-of-two-cities.txt 98-0.txt 
197c197
< up long rows of miscellaneous criminals; n hanging a housebreaker on
---
> up long rows of miscellaneous criminals; now, hanging a housebreaker on
311c311
< I say a horse at a canter coming up, Joe.�㐻
---
> I say a horse at a canter coming up, Joe.
482c482
< turn the leaves of this dear book that I loved, and vainly hope in ti
---
> turn the leaves of this dear book that I loved, and vainly hope in time
645c645,646
< last night when the horses were unyoked; beyond, a quiet coppice-wood,n which many leaves of burning red and golden yellow still remained
---
> last night when the horses were unyoked; beyond, a quiet coppice-wood,
> in which many leaves of burning red and golden yellow still remained
812c813
< It was a large, dark room, furnished in a funereal mannerth black
---
> It was a large, dark room, furnished in a funereal manner with black
931c932
< Our relations were business relations, but confidential. I wat that
---
> Our relations were business relations, but confidential. I was at that
1014c1015
< A daughter. A-atter of business--don't be distressed. Miss, if the
---
> A daughter. A-a-matter of business--don't be distressed. Miss, if the
1085c1086
< and memoranda, are all comprehended in the one line, 'Recalled to㐄fe;'
---
> and memoranda, are all comprehended in the one line, 'Recalled to Life;'
1199c1200,1201
woden shoes. The hands of the man who sawed the wood, left red marksany
---
> stained many hands, too, and many faces, and many naked feet, and many
> wooden shoes. The hands of the man who sawed the wood, left red marks
1255c1257
< broke off abruptly at the doors. The kennel, make amends, ran down
---
> broke off abruptly at the doors. The kennel, to make amends, ran down
1277c1279,1281
There, his eyes happening to catch the tall joker writing up his joke,
---
> another.
> 
> There, his eyes happening to catch the tall joker writing up his joke,
1463c1467
< uncorrupted, seemed tocape, and all spoilt and sickly vapours seemed
---
> uncorrupted, seemed to escape, and all spoilt and sickly vapours seemed
1568c1572
< Rendered in a manner perate, by her state and by the beckoning of
---
> Rendered in a manner desperate, by her state and by the beckoning of
1657c1661
< from direct light and air,ded down to such a dull uniformity of
---
> from direct light and air, faded down to such a dull uniformity of
1854c1858
< out--she had a fear of mying, though I had none--and when I was
---
> out--she had a fear of my going, though I had none--and when I was
2037c2041
< Under the over-swinging lamps--swinging ever brighter in the bet
---
> Under the over-swinging lamps--swinging ever brighter in the better
2199c2203
< After hailing the morn with this secosalutation, he threw a boot at
---
> After hailing the morn with this second salutation, he threw a boot at
2349c2353
< door-keeper this n for Mr. Lorry. He will then let you in.
---
> door-keeper this note for Mr. Lorry. He will then let you in.
2467c2471,2472
en or afterwards, seemed to be concentrated on the ceiling of thet him
---
> in his pockets, whose whole attention, when Mr. Cruncher looked at him
> then or afterwards, seemed to be concentrated on the ceiling of the
2635c2640
< whereat the jury's countenances displayed a guilty conscious㐇s that
---
> whereat the jury's countenances displayed a guilty consciousness that
2775c2780
< myself--timorous of highwaymen,d the prisoner has not a timorous
---
> myself--timorous of highwaymen, and the prisoner has not a timorous
2974c2979
< Have you no rememOffset: 0x3400asion?”
---
> Have you no remembrance of the occasion?”

观察以上内容,可以发现出现了一些怪异的汉字,同时末尾有个奇怪的hex值:0x3400,我们猜测这可能是个偏移量。所有这些汉字字符属于CJK Unicode。但我们查询这个hex以及相关字符,发现这些字符其实全包含在CJK Unified Ideographs Extension A中。

接下来,我们把出现的汉字进行串联一起:

㐾㐻㐌㐟㐀㐏㑖㐄㐓㐀㐴㐀㐄㐻㐉㐴㐷㐻㐾㐇㑎㑟

我们根据CJK Unified Ideographs Extension A,把对应字符的指标以deminal形式,写成数字列表:

[62, 59, 12, 31, 0, 15, 86, 4, 19, 0, 52, 0, 4, 59, 9, 52, 55, 59, 62, 7, 78, 95]

显然,ASCII码直接转换并不是flag的结果。(注意里面有0哟,XD)这时候考虑hint:A000788
通过搜索,我们发现这指向了[OEIS](http://oeis.org/A000788),一个整数数列在线大全网站。

查询得到的整数数列为:

[0, 1, 2, 4, 5, 7, 9, 12, 13, 15, 17, 20, 22, 25, 28, 32, 33, 35, 37, 40, 42, 45, 48, 52, 54, 57, 60, 64, 67, 71, 75, 80, 81, 83, 85, 88, 90, 93, 96, 100, 102, 105, 108, 112, 115, 119, 123, 128, 130, 133, 136, 140, 143, 147, 151, 156, 159, 163, 167, 172, 176, 181, 186]

到了开脑洞的时候,我们先看下已知的:俩数列、flag前几个字符utflag{。在字母表中u的位置为第20位,而此处在A00788序列中为0。我们发现:第一个数列中的62,可以看成20+42,而42在数列中排序正好是第20位。因此,我们需要创建个字典,将字母映射到对应的字母位置加上数列中同样位置的值的和。

python脚本如下:

# -*- encoding: utf-8 -*-

mand=u"㐾㐻㐌㐟㐀㐏㑖㐄㐓㐀㐴㐀㐄㐻㐉㐴㐷㐻㐾㐇㑎㑟"
codepts =[]

offset = 0x3400

for m in mand:
    ans = int(hex(ord(m)),16) - offset
    codepts.append(ans)
#密文数列
hashmap_char= {
    'a':0,
    'b':1,
    'c':2,
    'd':3,
    'e':4,
    'f':5,
    'g':6,
    'h':7,
    'i':8,
    'j':9,
    'k':10,
    'l':11,
    'm':12,
    'n':13,
    'o':14,
    'p':15,
    'q':16,
    'r':17,
    's':18,
    't':19,
    'u':20,
    'v':21,
    'w':22,
    'x':23,
    'y':24,
    'z':25,
    '{':26,
    '|':27,
    '}':28
}
#原始字母表
oeis = [ 0, 1, 2, 4, 5, 7, 9, 12, 13, 15, 17, 20, 22, 25, 28, 32, 33, 35, 37, 40, 42, 45, 48, 52, 54, 57, 60, 64, 67, 71, 75, 80, 81, 83, 85, 88, 90, 93, 96, 100, 102, 105, 108, 112, 115, 119, 123, 128, 130, 133, 136, 140, 143, 147, 151, 156, 159, 163, 167, 172, 176, 181, 186]

f_dict = {}
#密文字母字典
for k,v in hashmap_char.items():
    f_dict[k] = v + oeis[v]
#根据第二个数列得到密文字母字典
flag=""

for i in range(0, len(codepts)):
    flag+=list(f_dict.keys())[list(f_dict.values()).index(codepts[i])]
print(flag)
#得到flag

flag为:

utflag

Alice sends Bob a Meme

本题云复现XD

问题

Eve is an Apple Employee who has access to the iMessage keystore (because there is nothing stopping them). They know Alice and Bob use iMessage instead of Signal, therefore they decrypted their messages and see that Alice has sent Bob a meme. Eve suspects more is going on. Can you confirm their suspicions?

We included a screenshot of the message, and the actual files sent in the iMessage chat.

by asper

meme.png bobresponse.png screenshot.jpg

解题过程

第一张图片meme.png提供的是一个丢番图方程。本题的解决是把本题内容转化为ECC问题进行解决。

问题描述可以看成:

a/(b+c) + b/(c+a) + c/(a+b) = N

N(a+b)(b+c)(c+a) = a(c+a)(a+b) + b(b+c)(a+b) + c(b+c)(c+a)

本题根据《An unusual cubic representation problem》这篇论文,可以转化成ECC模型:

avatar

我们先看给出的sage XD:

sage: 413^2+1213-3

829

sage: 32*(13+3)

512

因此,我们可以知道曲线为:

y2=x3+829x^2+512x

从图片中,我们用binwalk提取出两个文件:alice.txtbob.txt。这提醒我们这是关于ECDH密钥交换的题。我们使用sagemath进行如下操作:

对于alice:

sage: (x,y)=(88610873236405736097813831550942828314268128800347374801890968111325912062058, 76792255969188554519144464321650537182337412449605253325780015124
....: 365585152539)
sage: M=108453893951105886914206677306984937223705600011149354906282902016584483568647
sage: (x**3 + 829*x**2 + 512*x) % M
34396641751505811655185387280465330637221522808091140769874333846906504394141
sage: (y**2)%M
34396641751505811655185387280465330637221522808091140769874333846906504394141

对于bob:

sage: (x,y)= (27543889954945113502256551007964501073506795938025836235838339960818915950890, 7592296957398702158364168521744128483246795405529527250535718582
....: 4478295962572)
sage: (x**3 + 829*x**2 + 512*x) % M
44457576863253255146857212842604584291668416287701298166721667908962751007374
sage: (y**2)%M
44457576863253255146857212842604584291668416287701298166721667908962751007374

得到的模数M的确是素数;如果在有限域上我们定义曲线,则可以找到曲线上的一个点,其中M是在GF(M)域内的。

sage: EE.gens()
((79218731191285575388815722542324414947282033006078108723420202919633596945165 : 82434376497957979363301482120254426339107668701491715933015661496473414628997 : 1),)

请注意:EE是我们在有限域上定义的椭圆曲线。之后我们要判断曲线的group order是否等于有限域,即素数模数判断。

如果发生这种情况,那么存在一种线性算法来解决迹线1的曲线的DLP。参考论文《The Discrete Logarithm Problem
on Elliptic Curves of Trace One
》。

sage: EE.order()
108453893951105886914206677306984937224124703598890507204412378872931154667424
sage: M
108453893951105886914206677306984937223705600011149354906282902016584483568647

然而这并不行之有效。我们检查下order:

sage: is_prime(EE.order())
False

order是个合数,因此:

sage: ee.order().factor()
2^5 * 3^2 * 617 * 1031 * 460919 * 1284352459083875752760636625085191848403737033002118694776855821

这意味着:Pohlig-Hellman攻击在解决本问题时,可能有效。现在的问题变成:Q = nP形式,其中P,Q是已知的。此外,根据题意我们也知道:n<84442469965344,
我们使用 Pollard’s Lambda / Pollard’s Kangaroo解决问题
sage脚本如下:

max_val = 84442469965344
M = 108453893951105886914206677306984937223705600011149354906282902016584483568647
# long weierstrass format
EE = EllipticCurve(GF(M),[0,829,0,512,0]) 
P = EE((88610873236405736097813831550942828314268128800347374801890968111325912062058, 76792255969188554519144464321650537182337412449605253325780015124365585152539))
# Q = Pn
Pn = EE((27543889954945113502256551007964501073506795938025836235838339960818915950890, 75922969573987021583641685217441284832467954055295272505357185824478295962572))
order = EE.order()
subresults = []
factors = []
modulus = 1
# Find partial solutions per each factor
for prime, exponent in factor(order):
        if prime > 10**9:
                break
        _factor = prime ** exponent
        factors.append(_factor)
        P2 = P*(order//_factor)
        Pn2 = Pn*(order//_factor)
        subresults.append(discrete_log_lambda(Pn2, P2, (0,_factor), '+'))
        modulus *= _factor

# Join partial solutions
n = crt(subresults,factors)
while n < max_val:
        if P*n==Pn:
                print("n=%d"%n)
                break
        n+=modulus

得到结果为:

1213123123131

因此flag为:1213123123131

Airport Security

本题依旧云复现,因为题目端口关了orz(准确说是翻译XD,量子力学打扰了

问题

nc quantumbomb.live 1337

You have a bomb and will receive a random qubit to query the bomb. You’re allowed to apply any unitary matrix to this query, and it’ll query the bomb in superposition of whether or not it’s a bomb. ��If the bomb measures |1>, it will explode. If the bomb measures |0>, it does nothing. ’ Nothing is measured if there is no bomb.

gates are inputed as:

numbers = np.matrix([[complex(numbers[0]), complex(numbers[1])], [ complex(numbers[2]), complex(numbers[3])]])

解题过程

本题涉及到的是量子力学的一个实验:伊利泽-威德曼炸弹测试问题Elitzur-Vaidman bomb testing problem)(中文维基需要梯子)。

程序提供给我们一个随机的表单量子位a|0> + b|1>,我们被告知炸弹可能是假的可能是真的,因此我们需要通过测量来确定哪些是假爆炸弹,哪些是真爆炸弹。

我们借助一个单一门应用到量子位,然后立即将量子应用到炸弹中。这其实就是:我们先用个门给量子位,然后获得一个新的量子位,同时叠加上去。

因此,如果炸弹是真的,它将能在|0> |1>基本位上测量出来,从而将状态折叠为01。如果量子位测量结果为0,我们不能测量到炸弹。如果测量的量子位为1,如果这时候还测量炸弹并且该炸弹为真的那炸弹就爆炸了。因此重要的是确定炸弹是假的,就不用任何针对量子位的测量了且结果依旧是叠加的。否则就是折叠到|0> |1>基本位。

由 Elitzur和Vaidman描述的技术是开始用|0>量子位,并且反复应用到一个非常小的旋转门(准确地说是π/(2x)时间内改变基本位到|1>)。

[cos(x), -sin(x)]
[sin(x),  cos(x)]

如果炸弹是真的,我们反复测量量子位并且这将由大概率测量到|0>,因此不会测量到炸弹。

如果炸弹是假的,我们不用测量量子位,并且它将能在叠加中反转,直到它接近于|1>

之后我们能测量量子位来决定炸弹是真还是假。(如果它是真的,我们希望出现大概率测量到|0>,反之亦然。)

这里还需要注意的是在问题中有个小瑕疵,因为量子位是随机生成的量子比特。因此,我们第一个门需要标准化量子比特为|0>进入,以便于不会意外地测量到炸弹。

提供给的量子比特:a|0> + b|1>,我们用门初始化得到如下结果:

[1/a, 0]
[0,   0]

来自dcua的aaditya_purani大佬的python解题代码如下:

from pwn import *
import math
import cmath

# Credits to my colleague for the automation.

r = remote("quantumbomb.live", 1337)
#连接提供的端口
def apply_gate(a1, a2, b1, b2):
    r.readuntil("Measure and decide\n")[:-1]
    r.writeline("1")
    print r.readuntil("4, .4j\n")[:-1]
    r.writeline(",".join([str(a1),str(b1),str(a2),str(b2)]))
    print r.readline()[:-1]
#门应用函数

def apply_rotation(div):
    angle = math.pi/(2*div)
    a1 = math.cos(angle)
    b1 = -math.sin(angle)*1j
    a2 = -math.sin(angle)*1j
    b2 = math.cos(angle)
    apply_gate(a1, a2, b1, b2)
#反转处理的函数

def apply_initial(c1, c2):
    a1 = 1 / c1
    b1 = 0
    a2 = 0
    b2 = 0 / c2
    apply_gate(a1, a2, b1, b2)
#初始化量子比特函数

for i in range(1, 36):
    r.readline()[:-1]
    print r.readuntil("This is bomb "+str(i)+"\n")[:-1]
    qubit_line = r.readline()[:-1]
    splt = qubit_line.split(': ')[1].split(' + ')

    # angle = 22.5/365 * 2 * math.pi

    n1 = eval(splt[0][:-4])
    n2 = eval(splt[1][:-4])
    print qubit_line
    apply_initial(n1, n2)
    trial = 32
    for rrr in range(1,trial):
        apply_rotation(trial)
    print r.readuntil("Measure and decide\n")[:-1]
    r.writeline("2")
    ss = r.readline()[:-1]
    print r.readline()[:-1]
    print ss
    if "[[1.]] |0>" in ss:
        print "y"
        r.writeline("y")
    else:
        print "n"
        r.writeline("n")

r.interactive()

参考

  1. aaditya_purani
  2. Sice Squad
posted @ 2022-05-06 16:26  FrancisQiu  阅读(21)  评论(0)    收藏  举报