示例#1
0
def encrypt_check(_ct, _ct_l, _key1, _key2, _nonce, _ad):
	ct_bkl = _ct_l // BLOCKLEN

	aes1 = AES.new(_key1, AES.MODE_ECB)
	aes2 = AES.new(_key2, AES.MODE_ECB)

	bks1 = [aes1.encrypt(l2b((b2l(_nonce) << 32) + 2 + i, 16)) for i in range(ct_bkl)]
	bks2 = [aes2.encrypt(l2b((b2l(_nonce) << 32) + 2 + i, 16)) for i in range(ct_bkl)]

	full_ct = [0]*_ct_l
	ks1 = [0]*_ct_l
	ks2 = [0]*_ct_l
	for i in range(_ct_l):
		ks1[i] = bks1[i//16][i % 16]
		ks2[i] = bks2[i//16][i % 16]
		full_ct[i] = _ct[i//16][i % 16]

	plaintxt1 = xor(bytes(full_ct), bytes(ks1))
	plaintxt2 = xor(bytes(full_ct), bytes(ks2))

	encrypted1,tag1 = gcm_encrypt(_key1, _nonce, plaintxt1,_ad)
	encrypted2,tag2 = gcm_encrypt(_key2, _nonce, plaintxt2,_ad)

	assert encrypted1 == encrypted2 and tag1 == tag2
	return encrypted1, tag1
示例#2
0
def collide(_key1, _key2, _nonce, _plain, _ad, DEBUG=False, _blockidx=-1):
	ct_l = len(_plain)
	ct_bkl = ct_l // BLOCKLEN
	ct_bl = 8 * ct_l

	ad_bl = 8*len(_ad)

	print("blocks:", ct_bkl)
	print()
	aes1 = AES.new(_key1, AES.MODE_ECB)
	aes2 = AES.new(_key2, AES.MODE_ECB)

	authkey1 = aes1.encrypt(all_zeros)
	authkey2 = aes2.encrypt(all_zeros)

	coeffs = getCoeffs(authkey1, authkey2, ad_bl//128 + ct_bkl+1)

	pad1 = aes1.encrypt(l2b((b2l(_nonce) << 32) | 1, 16))
	pad2 = aes2.encrypt(l2b((b2l(_nonce) << 32) | 1, 16))
	pads = ifAdd(pad1, pad2)

	keystream1 = [aes1.encrypt(l2b((b2l(_nonce) << 32) + 2 + i, 16)) for i in range(ct_bkl)]

	ct = [ifAdd(_plain[16*i:16*(i+1)], keystream1[i]) for i in range(ct_bkl)]
	assert len(ct) == ct_bkl

	coef = binascii.hexlify(coeffs[ct_bkl+1-_blockidx])
	sum_ = getSum(_ad, coeffs, pads, ct, _blockidx)

	ct[_blockidx] = ifMul(l2b(getInverse(coef), 16), sum_)

	encrypted, tag = encrypt_check(ct, ct_l, _key1, _key2, _nonce, _ad)

	return encrypted,tag
示例#3
0
def analysis(key, diff):
    print("key: {:032x}".format(b2l(key)))
    keys, sbox = expand_key(key, 16)
    colorama.init()
    bits = [0 for _ in range(16*8)]
    sample = 5000
    for s in trange(sample):
        diff_sqrd = []
        #diff = b2l(os.urandom(16))
        x, y = b2l(os.urandom(16)), b2l(os.urandom(16))
        for i in (x, y):
            a = b2l(encrypt_block(l2b(i), keys, sbox, 16))
            b = b2l(encrypt_block(l2b(i ^ diff), keys, sbox, 16))
            diff_sqrd.append(a ^ b)
            if s == 0:
                print("\r{:032x}->{:032x}  ".format(i, a))
                print("{:032x}->{:032x}  ".format(i ^ diff, b))
                print("{:032x}->{:032x}  ".format(diff, a ^ b))
                print("-"*66)

        r = diff_sqrd[0] ^ diff_sqrd[1]
        if s == 0:
            print("{:032x}".format(r).rjust(66, ' '))
            print('\r')

        #r = encrypt_block(os.urandom(16), keys, sbox, 16)
        r = '{:0128b}'.format(r)
        bits = [x+int(y, 2) for x, y in zip(bits, r)]

    from colorama import Fore
    green, yellow, red = Fore.GREEN, Fore.YELLOW, Fore.RED
    reset = colorama.Style.RESET_ALL
    tests = []
    for x in bits:
        t = binom_test(x, sample, 0.5)
        x = "%.2E" % t
        if len(x) > 8:
            x = red+"0"*5+reset
            tests.append(x)
            continue
        x = re.sub(r"\.|E|-|\+", "", x)
        if t <= 0.1 and t >= 0.01:
            x = yellow+x+reset
        elif t < 0.01:
            x = red+x+reset
        tests.append(x)
    print("\r\nProbability that each bit is equally likely 0 or 1")
    print('format: XYYZZ = X.YYE-ZZ')
    print('\n'.join(chunks(tests, 8, m=' '.join)))
    print("Overall: ", end='')
    final = binom_test(sum(bits), sample*len(bits), 0.5)
    print((red if final <= 0.05 else green) + "%.4E" % final + reset)
示例#4
0
def main():
    c = 3082489874584540355861976440154957444349802968606358209180310319846045010290428219945114844043901302597650924982910286231671337430936664185809669066762817535499514756463968189674472801536320141026694560204079394058935377378137004712487812117718010360346278762378192809353855702825349327607244514852447790414426389507325928721778099789473656709278135098915643867190345991798884214391389207351837734104494534915592459046635480167584016281186038004020937047971991512996625468347184973943467542720967761335734799148698672931984386755418194996569343120441376243026639952906891084792796113007934063427372263145841708494015
    e = 65537
    n = 4835750187736017002199910402633824276307631898091000077771942652114774929553132338780864979244300002934950340799255707706719068807452407480611171357191437808195657961280485410190950021251938036710663784185407986885413060120305830667265752106891991907683349203859430029804970061705163529856022394765039070626284349963490115392327176993981111921903099443600754324722527818078282290124479202829123212555658572674854964849787146566576353289029751920324001899153487870430173605050309512383603908334958874100463419711909679461073160404554664143408055364570826428967757690953156967295496007885336849722190950712736684455537
    factor_list = fermat_factorization(n)
    print(factor_list)
    [X1, Y1] = factor_list[0]
    [X2, Y2] = factor_list[1]
    
    assert X1 * Y1 == n    
    assert X2 * Y2 == n

    #p1 = GCD(X1, X2)
    #p2 = X1 / p1
    #q1 = GCD(Y1, Y2)
    #q2 = Y1 / q1

    p1 = GCD(X1,X2)
    q1 = X1//p1
    p2 = GCD(Y1,Y2)
    q2 = Y1//p2

    phi = (p1 - 1) * (q1 - 1) * (p2 - 1) * (q2 - 1)
    d = inverse(e, phi)
    flag = l2b(pow(c, d, n))

    print(flag)
示例#5
0
def main():
    c = 5333020300559057627358629150444779517927607675346073210522985591749203153560945527905471617055390862832090724275674301850841328746015818539999254106959583022492771703624475944141387595460858005483478153896882057074736219148307775833908988111821196571444363406298895482129627722808797729608415039516568435053064741173178431954979628184113077609472474158501321140759120865933591449468716625271915315192237652960416609140093720936411488882176262245872088399590046010317722025560167003681009206835834580085250672176381127010208394234527481235534697123574687573506314887709574961111534684456158044614521548036760981001130
    e = 65537
    n = 7661893861079288704612324056824281971553256849386803241531603299789846141029329254547934930958439426559413588181586850979797598156981380154181904473913556755982046171992133300178070732688527462379925496142741944410278173915503007594075131197019636352126219973024134086516300904590025630353490746964989205729428932590318185431652353310237407006739807162337887502047657095011822728581616805184689818928930804574318013115689430260450572839060904176023480504876807310962105063058782417722431654669730509157358979892491644691833798706704808468441748166558510311296180338934849110001861689206816856832238128874896790516637
    factor_list = fermat_factorization(n)
    print(factor_list)
    [X1, Y1] = factor_list[0]
    [X2, Y2] = factor_list[1]
    assert X1 * Y1 == n
    assert X2 * Y2 == n

    #p1 = GCD(X1, X2)
    #p2 = X1 / p1
    #q1 = GCD(Y1, Y2)
    #q2 = Y1 / q1

    p1 = GCD(X1, X2)
    q1 = X1 / p1
    p2 = GCD(Y1, Y2)
    q2 = Y1 / p2

    phi = (p1 - 1) * (q1 - 1) * (p2 - 1) * (q2 - 1)
    d = inverse(e, phi)
    flag = l2b(pow(c, d, n))

    print(flag)
示例#6
0
def apply_sbox_inv_key(b, key, block_size):
    #fix keys
    key = [b2l(l2b(x)*block_size) for x in key]
    #extract upper and lower halfs
    uh, c = b & int('f0'*block_size, 16), b & int('0f'*block_size, 16)
    uh = uh ^ (c << 4)
    return conditional_apply(uh, c, key, block_size)
示例#7
0
def apply_sbox(b: int, key: list, block_size: int = 16):
    #fix keys
    key = [b2l(l2b(x)*block_size) for x in key]
    #extract upper and lower halfs
    uh, lh = b & int('f0'*block_size, 16), b & int('0f'*block_size, 16)
    c = lh | (lh << 4)
    return conditional_apply(uh, c, key, block_size)
示例#8
0
 def decrypt(self, e, privkey):
     e, privkey = self.S(e), self.S(privkey)
     temp = map(Integer, list(privkey * e))
     temp = [t - self.q if t > self.q // _sage_const_2  else t for t in temp]
     temp = [t % self.p for t in temp]
     pt_encoded = [t - self.p if t > self.p // _sage_const_2  else t for t in temp]
     pt = l2b(self.decode(pt_encoded))
     return pt
示例#9
0
def getKS(key, nonce, bCount, initCount=0):  # initCount = 2 for GCM, 0 for CTR
    aesECB = AES.new(key, AES.MODE_ECB)
    stream = b"".join([
        aesECB.encrypt(l2b((nonce << 32) + initCount + i, 16))
        for i in range(bCount + 1)
    ])
    assert len(stream) == 16 * (bCount + 1)
    return stream
示例#10
0
def check(n):
    sys.stdout.write('\rMODULUS: {:x} '.format(n))
    resp = requests.get('http://127.0.0.1:5000/?cmd={}'.format(
        b64enc(l2b(n)).decode()))
    if 'Ciphertext too large' in resp.text:
        return True
    if 'Ciphertext with incorrect length' in resp.text:
        return True
    return False
示例#11
0
def getSum(_ad, _coeffs, _pads, _ct, _idx):
	ct_bl = 8 * len(_ct) * 16
	ct_bkl = len(_ct)
	ad_bl = 8*len(_ad)

	sum_ = ad_sum(_ad, _coeffs, ad_bl//128 + ct_bkl + 1)

	lenblock = l2b(ad_bl, 8) + l2b(ct_bl, 8)
	lenblock_term = ifMul(_coeffs[1], lenblock)
	sum_ = ifAdd(sum_, lenblock_term)
	sum_ = ifAdd(sum_, _pads)
	for i in range(len(_ct)):
		if not i == _idx:
			block = _ct[i]
			coeff = _coeffs[ct_bkl+1-i]
			sum_ = ifAdd(sum_, ifMul(block, coeff))

	return sum_
示例#12
0
 def substitute(self, b):
     assert len(b) % self.BOX_SIZE == 0
     res = list()
     blocks = self.nsplit(b, self.BOX_SIZE)
     for i in range(len(blocks)):
         block = blocks[i]
         inBOX = b2l(self.bitarray_to_bytes(block, 1))
         val = self.SBox[inBOX]
         res += self.bytes_to_bitarray(l2b(val), 8)
     return res
示例#13
0
def expand_key(key: bytes, num_keys: int = 7):
    random.seed(b2l(key))
    sbox_key = gen_box_key(num_keys)
    keys = b''
    for i in range(num_keys):
        keys += encrypt_block(
            key,
            l2b(i).rjust(len(key), b'\x00')*num_keys,
            sbox_key,
            len(key)
        )
    return keys, sbox_key
示例#14
0
文件: solve.py 项目: yen102/write-up
def dec(t):
    mp = modular_sqrt(t, p)
    mq = modular_sqrt(t, q)
    _, yp, yq = egcd(p, q)
    r = (yp * p * mq + yq * q * mp) % n
    s = (yp * p * mq - yq * q * mp) % n
    ms = [r, s, n - r, n - s]
    for m in ms:
        if check(m):
            flag = l2b(m)
            assert flag == "d4rk{r3p3t1t1v3_r4b1n_1s_th4_w0rs7_3vaaaaaar!}code"
            print(flag)
            exit()
    for m in ms:
        dec(m)
示例#15
0
def dec(t):
    mp = modular_sqrt(t, p)
    mq = modular_sqrt(t, q)
    _, yp, yq = egcd(p, q)
    r = (yp * p * mq + yq * q * mp) % n
    s = (yp * p * mq - yq * q * mp) % n
    ms = [r, s, n - r, n - s]
    for m in ms:
        if check(m):
            flag = l2b(m)
            print(flag)
            raw_input()
            exit()
    for m in ms:
        dec(m)
示例#16
0
def getInverse(_coef):
	global invert_data
	print("Coef to be inverted: %s" % b2a(_coef), end = '')
	if _coef in INVERTS:
		print(" (already computed)")
		inverse = INVERTS[_coef]
	else:
		print(" (not present)")
		print("Inverting the coefficient (takes a few mins)...")
		inverse = ifInvert(binascii.unhexlify(_coef))
		a, b = repr(_coef)[2:-1], repr(binascii.hexlify(l2b(inverse, 16)))[2:-1]
		print("New invert:", a, b)
		with open(invertsfn, "w") as f:
			invert_data += ["\n%s %s" % (a, b)]
			f.write("".join(invert_data))
	return inverse
示例#17
0
def getCoeffs(_H1, _H2, _pows, DEBUG=False):
	print("Computing", _pows, "coefficients.")

	retval = [l2b(1, 16), ifAdd(_H1,_H2)]
	prev_H1 = _H1
	prev_H2 = _H2
	for i in range(2, _pows+1):
		prev_H1 = ifMul(prev_H1, _H1)
		prev_H2 = ifMul(prev_H2, _H2)
		retval.append(ifAdd(prev_H1, prev_H2))

	# sanity check
	assert retval[1] == ifAdd(_H1, _H2)
	assert retval[2] == ifAddL(ifSquare(_H1), ifSquare(_H2))
	assert retval[3] == ifAddL(ifCube(_H1), ifCube(_H2))

	return retval
示例#18
0
def decrypt_round(
    c: bytes,
    key: bytes, sbox_inv: bytes,
    block_size: int
):
    m, key = b2l(c), b2l(key)
    #non-linear addition
    m = (m - int('01'*block_size*4, 2)) % (1 << (block_size*8))
    #shuffle
    mask = int('f0'*block_size, 16)
    uh, lh = m & mask, m & (mask >> 4)
    m = uh | ror(lh, 8*7, block_size*8)
    #sbox
    m = apply_sbox_inv_key(m, sbox_inv, block_size)
    #key
    m ^= key
    return l2b(m)
示例#19
0
def main():
    factor_list = fermat_factorization(n)
    [X1, Y1] = factor_list[0]
    [X2, Y2] = factor_list[1]
    assert X1 * Y1 == n
    assert X2 * Y2 == n

    p1 = GCD(X1, X2)
    p2 = X1 / p1
    q1 = GCD(Y1, Y2)
    q2 = Y1 / q1

    phi = (p1 - 1) * (q1 - 1) * (p2 - 1) * (q2 - 1)
    d = inverse(e, phi)
    flag = l2b(pow(c, d, n))
    assert flag == "ISITDTU{C0ngratu1ati0ns_Attack_RSA_Multi_prim3!!!!}"

    print(flag)
示例#20
0
def encrypt_round(
    m: bytes,
    key: bytes, sbox_key: bytes,
    block_size: int
):
    logger.debug("%032x, %032x, %08x", b2l(m), b2l(key), b2l(sbox_key))
    #format inputs
    c, key = b2l(m), b2l(key)
    #mix in the key
    c ^= key
    #apply sbox
    c = apply_sbox(c, sbox_key)
    #lower halfs shuffle
    m = int('f0'*block_size, 16)
    uh, lh = c & m, c & (m >> 4)
    c = uh | rol(lh, 8*7, block_size*8)
    #c = uh | rol(lh, 8*(round_num+1), block_size*8)
    #non-linear addition to every byte
    c += int('01010101'*(block_size), 2)
    c = c & int('ff'*block_size, 16)
    #format result
    return l2b(c)
示例#21
0
	args = parser.parse_args()

	fnmix = args.polyglot
	fnpoc = args.output
	key1, key2 = args.keys
	ad = args.additional_data
	blockidx = args.block_index
	nonce = args.nonce

	key1 = pad16(unhextry(key1)).encode()
	key2 = pad16(unhextry(key2)).encode()
	assert not key1 == key2

	noncei = int(nonce)
	nonceb = l2b(int(nonce),12)
	ad = unhextry(ad).encode()
	ad = pad(ad, BLOCKLEN)

	# fnmix should come from Mitra and
	# has a naming convention like "P(14-89)-ID3v2[Zip].4d01e2fb.mp3.zip"
	swaps = [int(i, 16) for i in fnmix[fnmix.find("(") + 1:fnmix.find(")")].split("-")]
	exts = fnmix[-9:].split(".")[-2:]
	

	with open(fnmix, "rb") as file:
		dIn = file.read()
	dIn = pad(dIn, BLOCKLEN) # the padding will break with formats not supporting appended data

	assert len(dIn) % 16 == 0
	bCount = len(dIn) // 16
示例#22
0
def find_shortest_vector(matrix):
    for col in matrix.columns():
        if col[0] == 0 and is_target_value(col[1:]):
            return col
        else:
            continue


pub = eval(open("pubkey.txt", "r").read())
c = int(open("ciphertext.txt", "r").read())

m = create_matrix(pub, c)
lllm = m.transpose().LLL().transpose()

shortest_vector = find_shortest_vector(lllm)

print shortest_vector

x = ""
for v in shortest_vector[1:]:
    if v == 1:
        x += "1"
    elif v == -1:
        x += "0"

flag = l2b(int(x[::-1], 2))

print flag

# lenstra_and_lovasz_liked_lattices
示例#23
0
文件: solve.py 项目: yen102/write-up
from config import c, n, t, z, factors
from Crypto.Util.number import long_to_bytes as l2b
from operator import mul

# factor by factordb
assert n == reduce(mul, factors)
phin = reduce(mul, [p - 1 for p in factors])
l = pow(2, pow(2, t, phin), n)
m = c ^ l ^ z
flag = l2b(m)

assert flag == "CCTF{_______________________________________________Happy_Birthday_LCS______________________________________________}"
print(flag)
示例#24
0
    args = parser.parse_args()

    fnmix = args.polyglot
    fnpoc = args.output
    key1, key2 = args.keys
    ad = args.additional_data
    blockidx = args.block_index
    nonce = args.nonce

    key1 = pad16(unhextry(key1)).encode()
    key2 = pad16(unhextry(key2)).encode()
    assert not key1 == key2

    noncei = int(nonce)
    nonceb = l2b(int(nonce), 12)
    ad = unhextry(ad).encode()
    ad = pad(ad, BLOCKLEN)

    # fnmix should come from Mitra and
    # has a naming convention like "P(14-89)-ID3v2[Zip].4d01e2fb.mp3.zip"
    swaps = [
        int(i, 16)
        for i in fnmix[fnmix.find("(") + 1:fnmix.find(")")].split("-")
    ]
    exts = fnmix[-9:].split(".")[-2:]

    with open(fnmix, "rb") as file:
        dIn = file.read()

    def BruteNonce(fn):
示例#25
0
def ifMul(_a1, _a2):
	old_product = gf_2_128_mul(b2l(_a1),b2l(_a2))
	return l2b(old_product, 16)
示例#26
0
def ifAdd(_a1, _a2):
	return l2b(b2l(_a1) ^ b2l(_a2), 16)
示例#27
0
def ifAddL(_a1,_a2):
	return l2b(_a1 ^ _a2, 16)
示例#28
0
    # SCTF{You_really_
    p.interactive()
elif stage == 2:
    p = remote('saltydsa.eatpwnnosleep.com', 12345)
    p.recvuntil('1) register 2) login 3) exit\n')
    p.sendline('1')
    p.recvuntil('name as hex encoded string.\n')
    p.sendline(hexlify(TMP_ID))
    p.recvuntil('Plz keep it secret.\n')
    r0, s0 = map(int, p.recvline().strip().split())

    # salt + 'A'*36 + md5(x)
    # k = s^-1 * (m + xr)
    md5_status = l2b(int(Integer(s0).inverse(server1['q']) *
                         (Integer(b2l(md5(TMP_ID).digest())) + server1['x'] * Integer(r0)) %
                         server1['q']))

    # 8a6ed196cf0342aed5e65039ef6b92e7
    # use https://github.com/s1fr0/md5-tunneling
    print hexlify(md5_status)

    status_arr = [
        u32(md5_status[0:4]),
        u32(md5_status[4:8]),
        u32(md5_status[8:12]),
        u32(md5_status[12:16]),
    ]

    print ' '.join(map(lambda n: '0x%08x' % n, status_arr))
elif stage == 3:
blkIns.transactions[0]

# tsc = sc.TriggerSmartContract()
# tsc.ParseFromString(blkIns.transactions[0].raw_data.contract[0].parameter.value)

blockDB = plyvel.DB("/data2/20210425/output-directory/database/block")
blockIt = blockDB.iterator()
k, v = next(blockIt)
print(k)
print(v)
print(binascii.hexlify(k))
vs = Tron_pb2.Block()
vs.ParseFromString(v)

# blockIndexDB = plyvel.DB("/data2/20210425/output-directory/database/block-index")
v = blockIndexDB.get(l2b(20000000))
print(v)
print(binascii.hexlify(v))
myBlock = blockDB.get(v)
print(v)

import core.contract.balance_contract_pb2 as balance_contract

c1 = balance_contract.TransferContract()
c1.ParseFromString(vs.transactions[1].raw_data.contract[0].parameter.value)

import core.contract.asset_issue_contract_pb2 as asset_issue_contract

c2 = asset_issue_contract.TransferAssetContract()
c2.ParseFromString(vs.transactions[2].raw_data.contract[0].parameter.value)
示例#30
0
from Crypto.Util.number import long_to_bytes as l2b
import pickle

val = pickle.load(open('enc.pickle', 'rb'))


def atk(val, nbit):
    A = Matrix(ZZ, nbit + _sage_const_1, nbit + _sage_const_1)
    for i in range(nbit):
        A[i, i] = _sage_const_2
        A[i, nbit] = val['pbkey'][i]
        A[nbit, i] = _sage_const_1
    A[nbit, nbit] = val['cip']
    return A.LLL()


nbit = len(val['pbkey'])
res = atk(val, nbit)
for i in range(nbit):
    if all([
            j in range(-_sage_const_2, _sage_const_2)
            for j in res[i][_sage_const_1:-_sage_const_1]
    ]):
        print(res[i])
        msg = int(
            ''.join([
                '1' if i <= -_sage_const_1 else '0'
                for i in res[i][:-_sage_const_1][::-_sage_const_1]
            ]), _sage_const_2)
        print(l2b(msg))