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
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
def decrypt_block(b, k): result = b2l(b) for i in range(ROUNDS - 1, -1, -1): key = b2l(k[i * BLOCK_LEN:(i + 1) * BLOCK_LEN]) key_odd = key | 1 result = result * pow(key_odd, -1, 2**64) % 2**64 result = g(result) result ^= key return hex(result).lstrip('0x').rstrip('L').zfill(BLOCK_LEN * 2)
def encrypt_block(b, k): result = b2l(b) for i in range(ROUNDS): key = b2l(k[i * BLOCK_LEN:(i + 1) * BLOCK_LEN]) key_odd = key | 1 result ^= key result = g(result) result = (result * key_odd) % (1 << 64) return hex(result).lstrip('0x').rstrip('L').zfill(BLOCK_LEN * 2)
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)
def enc(self, text): if self.checkHexEncoded(text): text = text.decode('hex') else: return "Input must Hex Encoded" if len(text) % self.BLOCK_SIZE != 0: pad_len = self.BLOCK_SIZE - (len(text) % self.BLOCK_SIZE) text += pad_len * chr(pad_len) assert len(text) % self.BLOCK_SIZE == 0 out = '' blocks = self.nsplit(text, self.BLOCK_SIZE) for block in blocks: ba_block = self.bytes_to_bitarray(block, self.BLOCK_SIZE * 8) for _round in range(self.ROUNDS - 1): ba_block = self.keyXor(ba_block, self.keys[_round]) ba_block = self.substitute(ba_block) ba_block = self.permutation(ba_block) #last round is not permuted ba_block = self.keyXor(ba_block, self.keys[self.ROUNDS - 1]) ba_block = self.substitute(ba_block) ba_block = self.keyXor(ba_block, last_XOR_key) out += '%016x' % b2l(self.bitarray_to_bytes(ba_block, 8)) return out
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)
def encry(message,key,p,q,e): k1,k2 = key[random.randint(0,127)],key[random.randint(0,127)] x = p**2 * (p + 3*q - 1 ) + q**2 * (q + 3*p - 1) y = 2*p*q + p + q z = k1 + k2 c = pow(b2l(message),e,p*q) return x * c + y * c + z
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)
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)
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
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
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)
def main(): start = datetime.datetime.now() i = 0 with open(trc20_in_file) as rf: r_csv = csv.reader(rf) with open(trc20_out_file, "w") as wf: w_csv = csv.writer(wf) conv_start = datetime.datetime.now() read_time = (conv_start - start).total_seconds() print("读取耗时 {} 微秒, {} 秒".format(read_time * 10**6, read_time)) for rline in r_csv: # print("src data: ", rline) rline[3] = addressFromBytes( bytes.fromhex("41" + rline[3][-40:])) rline[4] = addressFromBytes( bytes.fromhex("41" + rline[4][-40:])) rline[5] = b2l(bytes.fromhex(rline[5])) # print("dst data: ", rline) w_csv.writerow(rline) i += 1 if i % 100000 == 0: wf.flush() end = datetime.datetime.now() conv_time = (end - conv_start).total_seconds() print("解析 {} 条 总耗时 {} 微秒, {} 秒".format( i, conv_time * 10**6, conv_time)) print("单条耗时 {} 微秒, 解析 {} 条预计耗时 {} 秒, {} 分钟".format( conv_time * 10**6 / i, total, (conv_time / i) * total, (conv_time / i) * total / 60, )) # if i == 10: # break wf.flush() end = datetime.datetime.now() conv_time = (end - conv_start).total_seconds() print("解析 {} 条 总耗时 {} 微秒, {} 秒".format(total, conv_time * 10**6, conv_time)) print("单条耗时 {} 微秒, 解析 {} 条预计耗时 {} 秒, {} 分钟".format( conv_time * 10**6 / total, total, (conv_time / total) * total, (conv_time / total) * total / 60, ))
def encode(m): m = list("{:b}".format(b2l(m))) m = list(map(int, m)) m = m[::-1] m += (8 - len(m) % 8) * [0] extended = m oriLen = len(m) extended = (k - len(extended) % k) * [0] + extended extendedBits = extended oriLenBits = list("{:b}".format(oriLen)) oriLenBits = list(map(int, oriLenBits)) oriLenBits = (k - len(oriLenBits) % k) * [0] + oriLenBits extendedOriLenBits = oriLenBits finalBits = extendedOriLenBits + extendedBits finalBits = finalBits[::-1] return finalBits
def main(): start = datetime.datetime.now() i = 0 count = 10 with open(usdt_in_file) as rf: r_csv = csv.reader(rf) with open(usdt_out_file, "w") as wf: w_csv = csv.writer(wf) conv_start = datetime.datetime.now() read_time = (conv_start - start).total_seconds() print("读取耗时 {} 微秒, {} 秒".format(read_time * 10**6, read_time)) for rline in r_csv: print("src data: ", rline) rline[2] = addressFromBytes( bytes.fromhex("41" + rline[2][-40:])) rline[3] = addressFromBytes( bytes.fromhex("41" + rline[3][-40:])) rline[4] = b2l(bytes.fromhex(rline[4])) / 1000000 print("dst data: ", rline) w_csv.writerow(rline) i += 1 if i % 1000 == 0: wf.flush() if i == 10: break wf.flush() end = datetime.datetime.now() conv_time = (end - conv_start).total_seconds() print("解析 {} 条 总耗时 {} 微秒, {} 秒".format(count, conv_time * 10**6, conv_time)) print("单条耗时 {} 微秒, 解析 68678330 条预计耗时 {} 秒, {} 分钟".format( conv_time * 10**6 / count, (conv_time / count) * 68678330, (conv_time / count) * 68678330 / 60, ))
def le_bv(_input_ba): longval_a1 = b2l(_input_ba) bv_a1 = bv.BitVector(intVal=longval_a1, size=128) return bv.BitVector(bitstring=str(bv_a1)[::-1])
def ifAdd(_a1, _a2): return l2b(b2l(_a1) ^ b2l(_a2), 16)
def ifCube(_a1): return gf_2_128_mul(gf_2_128_mul(b2l(_a1),b2l(_a1)),b2l(_a1))
def ifSquare(_a1): return gf_2_128_mul(b2l(_a1),b2l(_a1))
with open('server_1_priv.pem') as f: server1 = import_key(f.read()) with open('server_2_pub.pem') as f: server2 = import_key(f.read()) if len(sys.argv) < 2: print ('Usage: %s <stage>' % sys.argv[0]) exit(0) BLOCK = 512 // 8 TMP_ID = 'qwaz' mx = 'admin' hx = b2l(md5(mx).digest()) stage = int(sys.argv[1]) if stage == 1: k = 123 rx = Integer(pow(int(server1['g']), k, int(server1['p']))) % server1['q'] sx = Integer(k).inverse(server1['q']) * (Integer(hx) + server1['x'] * rx) % server1['q'] p = remote('saltydsa.eatpwnnosleep.com', 12345) p.recvuntil('1) register 2) login 3) exit\n') p.sendline('2') p.recvuntil('name as hex encoded string.\n') p.sendline(hexlify(mx)) p.recvuntil('format.\n') p.sendline('%d %d' % (rx, sx))
transHisIt = transHisStore.iterator() k, v = next(transHisIt) print(k) print(v) print(binascii.hexlify(k)) vs = Tron_pb2.TransactionInfo() vs.ParseFromString(v) print(binascii.hexlify(vs.id)) tranCacheIT = transCacheStore.iterator() while True: k, v = next(tranCacheIT) print("k: {}".format(k)) print("k dec: {}".format(b2hs(k))) print("v: {}".format(b2l(v))) # print("v hex: {}".format(bytes.decode(b2hs(v)))) # print("v base: {}".format(addressFromBytes(v))) print("========================================\n") time.sleep(0.4) transRetIt = transRetStore.iterator() # i = 0 # while True: k, v = next(transRetIt) # i += 1 # print(i) # print("k: {}".format(k)) print("k dec: {}".format(b2l(k)))
long_to_bytes as l2b, ) from itertools import combinations from base64 import b64encode FILENAME = "love_letter.txt" KEY_SIZE = 2048 e = 0x10001 data = open(FILENAME, "rb").read() chunk_size = len(data) // 3 + (3 - len(data) % 3) assert chunk_size <= KEY_SIZE // 8 - 11 data += b"\x00" * (chunk_size * 3 - len(data)) chunks = [data[i * chunk_size:(i + 1) * chunk_size] for i in range(3)] primes = [getPrime(KEY_SIZE // 2) for _ in range(3)] cipher = "" for c, pair in enumerate(combinations(primes, 2)): p, q = pair n = p * q phi = (p - 1) * (q - 1) enc = b64encode(l2b(pow(b2l(chunks[c]), e, n))).decode() cipher += f"{n}:{enc}\n" open(FILENAME, "w").write(cipher)
from Crypto.Util.number import getPrime from Crypto.Util.number import long_to_bytes as l2b from Crypto.Util.number import bytes_to_long as b2l from gmpy import next_prime from secret import flag FLAG = b2l(flag) def prime(): while True: prime = getPrime(512) if(prime > FLAG): return prime p = prime() q = prime() r = prime() while True: s = prime() if(s>p and s>q and s>r): break t = next_prime(s) assert p > FLAG assert q > FLAG assert r > FLAG assert s > FLAG n = p*q*r*s*t
def ifMul(_a1, _a2): old_product = gf_2_128_mul(b2l(_a1),b2l(_a2)) return l2b(old_product, 16)
#!/usr/bin/env python3 from Crypto.Util.number import long_to_bytes as l2b from Crypto.Util.number import bytes_to_long as b2l dummy = b'zer0pts{********CENSORED********}' dummy += (-len(dummy) % 8) * b'\x00' data = [0, 0x410A4335494A0942, 0x0B0EF2F50BE619F0, 0x4F0A3A064A35282B, 0] flag = b'' for i in range(len(dummy) // 8): temp = b2l(dummy[8 * i:8 * (i + 1)][::-1]) + b2l(l2b(data[i])) temp &= (1 << 64) - 1 flag += l2b(temp)[::-1] flag = flag.rstrip(b'\x00').decode() assert flag == 'zer0pts{l3ts_m4k3_4_DETOUR_t0d4y}' print(flag)
def generate_collision(file1, file2): img1 = file1 img2 = file2 # Check JPEG format if b2l(img1[:2]) != 0xffd8 or b2l(img2[:2]) != 0xffd8: print "Image is not JPEG format." sys.exit(1) size1 = Image.open(io.BytesIO(img1)).size size2 = Image.open(io.BytesIO(img2)).size print "Image size:", size1 # Resize the image if different sizes if size1 != size2: tmpIO = io.BytesIO() new = Image.open(io.BytesIO(img2)).resize(size1) new.save(tmpIO, format= 'JPEG') img2 = tmpIO.getvalue() print "Resized:", "file2" pdf_header = l2b(0x255044462D312E330A25E2E3CFD30A0A0A312030206F626A0A3C3C2F57696474682032203020522F4865696768742033203020522F547970652034203020522F537562747970652035203020522F46696C7465722036203020522F436F6C6F7253706163652037203020522F4C656E6774682038203020522F42697473506572436F6D706F6E656E7420383E3E0A73747265616D0A) jpg_header = l2b(0xFFD8FFFE00245348412D3120697320646561642121212121852FEC092339759C39B1A1C63C4C97E1FFFE01) # Collision blocks (This is the only part of the files which is different) collision_block1 = l2b(0x7F46DC93A6B67E013B029AAA1DB2560B45CA67D688C7F84B8C4C791FE02B3DF614F86DB1690901C56B45C1530AFEDFB76038E972722FE7AD728F0E4904E046C230570FE9D41398ABE12EF5BC942BE33542A4802D98B5D70F2A332EC37FAC3514E74DDC0F2CC1A874CD0C78305A21566461309789606BD0BF3F98CDA8044629A1) collision_block2 = l2b(0x7346DC9166B67E118F029AB621B2560FF9CA67CCA8C7F85BA84C79030C2B3DE218F86DB3A90901D5DF45C14F26FEDFB3DC38E96AC22FE7BD728F0E45BCE046D23C570FEB141398BB552EF5A0A82BE331FEA48037B8B5D71F0E332EDF93AC3500EB4DDC0DECC1A864790C782C76215660DD309791D06BD0AF3F98CDA4BC4629B1) prefix1 = pdf_header + jpg_header + collision_block1 prefix2 = pdf_header + jpg_header + collision_block2 data = '' data += b'\x00' * 242 data += jpeg_comment(8 + len(img1[2:])) data += b'\x00' * 8 data += img1[2:] data += img2[2:] data += b'endstream\nendobj\n\n' # Cross-reference Table xref = b'xref\n' xref += b'0 13 \n' xref += b'0000000000 65535 f \n' xref += b'0000000017 00000 n \n' xref += b'%010d 00000 n \n' % len(prefix1+data) # width data += b'2 0 obj\n%010d\nendobj\n\n' % size1[0] xref += b'%010d 00000 n \n' % len(prefix1+data) # height data += b'3 0 obj\n%010d\nendobj\n\n' % size1[1] xref += b'%010d 00000 n \n' % len(prefix1+data) data += b'4 0 obj\n/XObject\nendobj\n\n' xref += b'%010d 00000 n \n' % len(prefix1+data) data += b'5 0 obj\n/Image\nendobj\n\n' xref += b'%010d 00000 n \n' % len(prefix1+data) data += b'6 0 obj\n/DCTDecode\nendobj\n\n' xref += b'%010d 00000 n \n' % len(prefix1+data) data += b'7 0 obj\n/DeviceRGB\nendobj\n\n' xref += b'%010d 00000 n \n' % len(prefix1+data) # JPEG size data += b'8 0 obj\n%010d\nendobj\n\n' % len(img1+img2) xref += b'%010d 00000 n \n' % len(prefix1+data) data += b'9 0 obj\n<<\n /Type /Catalog\n /Pages 10 0 R\n>>\nendobj\n\n' xref += b'%010d 00000 n \n' % len(prefix1+data) data += b'10 0 obj\n<<\n /Type /Pages\n /Count 1\n /Kids [11 0 R]\n>>\nendobj\n\n' xref += b'%010d 00000 n \n' % len(prefix1+data) data += b'11 0 obj\n<<\n /Type /Page\n /Parent 10 0 R\n /MediaBox [0 0 %010d %010d]\n /CropBox [0 0 %010d %010d]\n /Contents 12 0 R\n /Resources\n <<\n /XObject <</Im0 1 0 R>>\n >>\n>>\nendobj\n\n' % (size1[0], size1[1], size1[0], size1[1]) xref += b'%010d 00000 n \n' % len(prefix1+data) data += b'12 0 obj\n<</Length 49>>\nstream\nq\n %010d 0 0 %010d 0 0 cm\n /Im0 Do\nQ\nendstream\nendobj\n\n' % (size1[0], size1[1]) xref_pos = len(prefix1 + data) data += xref trailer = b'\ntrailer << /Root 9 0 R /Size 13>>\n\nstartxref\n%010d\n%%%%EOF\n' % xref_pos data += trailer outfile1 = prefix1 + data outfile2 = prefix2 + data # Check SHA-1 collision assert sha1(outfile1).hexdigest() == sha1(outfile2).hexdigest() print "Successfully Generated Collision PDF !!!" return outfile1, outfile2
from Crypto.Util.number import bytes_to_long as b2l def randstr(n): from string import printable from random import choice return "".join(choice(printable) for _ in range(n)) length = 270 - 4 flag_message = 'Y' * length flag_message = randstr(length) message = Message(id=0, msg=flag_message) print message m1 = message.SerializeToString() print len(m1) print b2l(m1).bit_length() print m1.encode('hex') ct1 = encrypt(message.SerializeToString()) message.id = 1 print message m2 = message.SerializeToString() print len(m2) print b2l(m2).bit_length() print m2.encode('hex') # diff is always constant print 'diff =' diff = b2l(m2) - b2l(m1) print diff
def addressFromBytes(addr): return tronapi.common.account.Address().from_hex(bytes.decode(b2hs(addr))) # 会遇到问题 UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb6 in position 3: invalid start byte # db = plyvel.DB("/data2/20210425/output-directory/database/trans") blockIndexDB = plyvel.DB( "/data2/20210425/output-directory/database/block-index") blockDB = plyvel.DB("/data2/20210425/output-directory/database/block") blockIndexIT = blockIndexDB.iterator() k, v = next(blockIndexIT) k = b2l(k) print(k) vs = binascii.hexlify(v) print(vs) blockIndexITrev = blockIndexDB.iterator(reverse=True) k, v = next(blockIndexITrev) k = b2l(k) print(k) vs = binascii.hexlify(v) print(vs) blk = blockDB.get(v) blkIns = Tron_pb2.Block() blkIns.ParseFromString(blk)
def bytes_to_bitarray(self, s, size): out = bin(b2l(s)).replace('0b', '').replace('L', '') if len(out) < size: out = '0' * (size - len(out)) + out assert (len(out) == size) return list([int(x) for x in out])