def distribute_data(self, data: bytes, final_chunk=False): ''' nodeA = chunk0 + chunk2 nodeB = chunk1 + chunk3 nodeC = chunk0 xor chunk1 + chunk2 xor chunk3 nodeE = chunk2 xor chunk1 + chunk0 xor (chunk3 xor chunk3) ''' # chunks = [(data[i], data[i + 1], data[i + 2 ] # chunk_range = range(self.chunk_size, len(data) + self.chunk_size, self.chunk_size) # chunks = [data[y-self.chunk_size:y] for y in chunk_range] # connected_count = 0 ##data = print('distribute data ') if final_chunk: chunks = util.process_chunks(data, chunk_size) else: chunks = util.cut_chunks(data) logger.debug(f'chunks prepared: {chunks}') (self.data_nodes[0].socket).sendall(chunks[0] + chunks[2]) logger.debug(f'A xor B node') (self.data_nodes[1].socket).sendall(chunks[1] + chunks[3]) logger.debug(f'A xor C node') (self.data_nodes[2].socket).sendall( util.xor(chunks[0], chunks[1]) + util.xor(chunks[2], chunks[3])) logger.debug(f'A xor D node') (self.data_nodes[3].socket).sendall( util.xor(chunks[2], chunks[1]) + util.xor(chunks[0], util.xor(chunks[2], chunks[3]))) logger.debug(f'B xor d node') return
def find_last_byte(cipher_text): cipher_text = bytearray(base64.b64decode(cipher_text)) # print"cipher_text" # print cipher_text # print "" blocks = split_blocks(cipher_text) # print "blocks" # print blocks # print "" arr = [b for b in blocks[0]] print arr c_prime = bytearray([b for b in blocks[0]]) # print c_prime # print "" plain_text_bytes = bytearray([0 for _ in range(16)]) for i in range(16): expected_padding = bytearray([0 for _ in range(16 - i)] + [(i + 1) for _ in range(i)]) ep = [0 for _ in range(16 - i)] + [(i + 1) for _ in range(i)] print ep # print [0 for _ in range( 16 - i)] + [(i+1) for _ in range(i)] c_prime = util.xor(util.xor(expected_padding, plain_text_bytes), blocks[0]) # print c_prime for byte in range(blocks[0][15 - i] + 1, 256) + range( 0, blocks[0][15 - i] + 1): c_prime[15 - i] = byte to_test = base64.b64encode(str(c_prime + blocks[1])) try: global_cipher.decrypt(to_test) print global_cipher.decrypt(to_test) print " At i == " + str(i) + " encode found at byte = " + str( byte) #print global_cipher.decrypt(to_test) plain_text_bytes[15 - i] = (byte ^ (i + 1) ^ blocks[0][15 - i]) break except: pass return "PO Attack Decryption: " + "".join( [chr(b) for b in plain_text_bytes])
def decrypt(cipher_text, key, iv): cipher_blocks = to_blocks(cipher_text) plain_blocks = [] aes = AES.new(key, AES.MODE_ECB) for block in cipher_blocks: xored = aes.decrypt(block) plain = xor(xored, iv) plain_blocks.append(plain) iv = xor(plain, block) return b"".join(plain_blocks)
def gain_admin(): desired = 'admin=true' actual = 'userdata=' pad_len = len(desired) - len(actual) ct, nonce = oracle('a' * pad_len) #get enc(comment1= .... ;userdate=a;comment2=...) ct_diff = util.xor(desired, actual + 'a' * pad_len) prefix_pad_len = len(prefix) - len(actual) sufix_pad_len = len(ct) - len(ct_diff) - prefix_pad_len return util.xor('\0' * prefix_pad_len + ct_diff + '\0' * sufix_pad_len, ct), nonce
def ARK(message, key): new_message = "" message = util.hex_to_bin(message) key = util.hex_to_bin(key) new_message = util.xor(message, key) new_message = util.bin_to_hex(new_message) return new_message
def add(a, b): c = "" a = util.hex_to_bin(a) b = util.hex_to_bin(b) c = util.xor(a, b) c = util.bin_to_hex(c) return c
def secretbox_xsalsa20poly1305_open(c, n, k): if len(c) < 16: raise ValueError('Too short for XSalsa20Poly1305 box') s = stream_xsalsa20(32, n, k) if not onetimeauth_poly1305_verify(c[:16], c[16:], s): raise ValueError('Bad authenticator for XSalsa20Poly1305 box') s = stream_xsalsa20(16 + len(c), n, k) return xor(c[16:], s[32:])
def secretbox_salsa20hmacsha512_open(c, n, k): if len(c) < 32: raise ValueError('Too short for Salsa20HMACSHA512 box') s = stream_salsa20(32, n, k) if not auth_hmacsha512_verify(c[:32], c[32:], s): raise ValueError('Bad authenticator for Salsa20HMACSHA512 box') s = stream_salsa20(len(c), n, k) return xor(c[32:], s[32:])
def crypto_secretbox_salsa20hmacsha512_open(c, n, k): if len(c) < 32: raise ValueError('Too short for Salsa20HMACSHA512 box') s = crypto_stream_salsa20(32, n, k) if not crypto_auth_hmacsha512_verify(c[:32], c[32:], s): raise ValueError('Bad authenticator for Salsa20HMACSHA512 box') s = crypto_stream_salsa20(len(c), n, k) return xor(c[32:], s[32:])
def CBCdecrypt(key, IV, ciphertext): plaintext = "" for x in range(32,len(ciphertext)+32,32): plaintext += util.xor(IV, set1.AESinECBdecrypt(key,util.b16decode(ciphertext[x-32:x]))) IV = util.b16decode(ciphertext[x-32:x]) return plaintext
def _decrypt_cbc_block(block, key, previous_block): partial_decryption = decrypt_ecb(block, key) # This is the 'chain' part of CBC. Simple XOR to previous block, doesn't necessarily have to # be the decrypted value of previous block. full_decrypt = xor(partial_decryption, previous_block) return full_decrypt
def CBCencrypt(key, IV, plaintext): bytes = util.b16encode(plaintext) ciphertext = "" for x in range(32,len(plaintext)+32,32): IV = set1.AESinECBencrypt(key, util.xor(IV, util.b16decode(bytes[x-32:x]))) ciphertext += IV return ciphertext
def test_solve(): """Test always passes; check STDOUT instead.""" with open("files/20.txt") as f: cts = create_cts(f.read()) ks = find_keystream(cts) for ct in cts: print(util.xor(ct, ks)) assert True
def collide_hash(target): # Put comment after target to hide everything after while True: base = target + '//' + os.urandom(4) t1 = cbc_mac.cbc_mac_tag(base, k, iv) preimage = aes.add_pkcs7_padding(base) + util.xor(t1, m[:16]) + m[16:] assert (cbc_mac.cbc_mac_tag(preimage, k, iv) == tag) if "\n" not in preimage[:-(len(m) - 16)]: return preimage print("newline in padding :(")
def encrypt(self, plaintext): plaintext = self._add_padding(bytearray(plaintext)) plaintext_blocks = self._split_blocks(plaintext) #initiatilization vector iv = get_random_bytes(16) cipher_blocks = [] for i, block in enumerate(plaintext_blocks): if (i == 0): cipher_blocks.append(iv) cipher_blocks.append( self._cipher.encrypt(str(util.xor(iv, block)))) else: cipher_blocks.append( self._cipher.encrypt(str(util.xor(cipher_blocks[i], block)))) return base64.b64encode(''.join(cipher_blocks))
def decrypt(text, key): """ XOR 1 byte of decrypted text with a single byte key. Returns the decrypted text. """ result = "" # 1 byte is represented by 2 hex digits for b in range(0, len(text), 2): result += chr(util.xor(text[b:b+2],key,16,16)) return result
def mixer(binary_string, key): assert (len(binary_string) == 64 ), "Binary string is not 64 bits long- {}: mixer".format( len(binary_string)) assert (len(key) == 48), "Key is not 48 bits long- {}: mixer".format( len(key)) left = binary_string[:32] right = binary_string[32:] R = des_func(right, key) L = xor(left, R) L = format(L, '0>32b') mixed = L + right return mixed
def decrypt(self, ciphertext): ciphertext = bytearray(base64.b64decode(ciphertext)) ciphertext_blocks = self._split_blocks(ciphertext) plaintext_blocks = [] for i, block in enumerate(ciphertext_blocks): if i == 0: continue plaintext_blocks.append( str( util.xor(self._cipher.decrypt(str(block)), ciphertext_blocks[i - 1]))) return self._strip_and_check_padding(''.join(plaintext_blocks))
def SBXdecipher(cipherText): plaintext = [] scores = [] # All Letters, Numbers, and Symbols for key in range(32,127): # XOR cipherText against ascii chars plaintext.append(util.xor(str(unichr(key)), cipherText)) scores.append(letterFrequency(plaintext[key-32])) # return item with highest score idx = min(enumerate(scores), key=itemgetter(1))[0] + 32 # returns (plaintext, score, key) return (plaintext[idx-32], scores[idx-32], str(unichr(idx)))
def route(start, dest, dimension, faultyLinks): faultyNodes = set() routingStack = [] currentNode = start routingStack.append(start) while currentNode != dest: routingTag = util.xor(currentNode,dest, dimension) currentNode,faultNodes,routingStack = util.getNextNode(currentNode,routingTag, faultyLinks, faultyNodes, routingStack) print "Add " + currentNode +" to routingStack" routingStack.append(currentNode) print "============================================" print "" print "Arrived at Destination: " + currentNode return routingStack
def __king_hardness(self, move_str: str): # 玉の硬さを計算して結果を格納する k_b = BitBoard() # 動かした駒が大文字なら先手番 is_teban_black = True if move_str.isupper() else False k_ndarray = k_b.king25(self.pass_of_K[-1]) if is_teban_black else k_b.king25(self.pass_of_k[-1]) king25list = np.where(np.logical_and((self.nowBoard.ban != 0), k_ndarray)) # nowBoardは1手先の局面だが実用上はこれでも問題ないだろう king_hardness = 0 for x, y in zip(np.nditer(king25list[0]), np.nditer(king25list[1])): piece_str = reverse_piece[self.nowBoard.ban[x][y]] # 現在の盤面の駒位置を直接参照して駒文字を求める piece_val = get_piece_value(piece_str) # 対応する駒の価値(常に正の値)を求める if xor(is_teban_black, piece_str.isupper()): # ここがTrueなら動かした駒と盤面の駒が逆であるということ piece_val *= -1 # 逆側の駒価値として符号を反転する king_hardness += piece_val if is_teban_black: self.stat_black_king_hardness.append(king_hardness) else: self.stat_white_king_hardness.append(king_hardness)
def route(start, dest, dimension, faultyLinks): faultyNodes = set() routingStack = [] currentNode = start routingStack.append(start) while currentNode != dest: routingTag = util.xor(currentNode, dest, dimension) currentNode, faultNodes, routingStack = util.getNextNode( currentNode, routingTag, faultyLinks, faultyNodes, routingStack) print "Add " + currentNode + " to routingStack" routingStack.append(currentNode) print "============================================" print "" print "Arrived at Destination: " + currentNode return routingStack
def get_key(): ct = oracle() blocks = aes.splitBlocks(ct) #send oracle c_0 || 00..0 || c_0 # = aes(iv ^ p_0) || 00..0 || aes(iv ^ p_0) # = aes(key ^ p_0) || 00..0 || aes(key ^ p_0) #This decrypts to: # p_0' || p_1' || p_2' = p_0 || aes_dec(00...) ^ c_0 || key ^ p_0 #==> key = p_0' ^ p_2' parts = [blocks[0], '\0' * 16, blocks[0]] parts.extend(blocks[3:]) ctp = ''.join(parts) try: #p_1' = aes_dec(00...0) is non ascii with high probability #so we should get error with returned plaintext consume_ct(ctp) except NonAscii as e: blocks = aes.splitBlocks(e.args[0]) return util.xor(blocks[0], blocks[2])
def secretbox_salsa20hmacsha512(m, n, k): s = stream_salsa20(len(m) + 32, n, k) c = xor(m, s[32:]) a = auth_hmacsha512(c, s[:32]) return a + c
def generate_transaction(from_id, to_id, amount): m = 'from=%d&to=%d&amount=%d' % (from_id, to_id, amount) iv = urandom(16) return m, iv, cbc_mac_tag(m, key, iv) def print_balances(heading='Balances:'): print heading for n, i in sorted(name_to_id.items()): print '%s: $%d' % (n, balances[i]) print '' if __name__ == '__main__': print_balances('Initial balances:') #Alice carries out legitimate transaction m, iv, tag = generate_transaction(0, 1, 250) handle_transaction(m, iv, tag) print_balances() #Malice takes Alice's transaction and changes the to field to Malice m_mal = m.replace('to=1', 'to=2') iv_mal = xor(iv, xor(m[:16], m_mal[:16])) handle_transaction(m_mal, iv_mal, tag) print_balances('After Malice is evil')
#!/bin/env python import array import util import sys # python challenge2.py string1 string2 c = array.array('B', sys.argv[1].decode('hex')) k = array.array('B', sys.argv[2].decode('hex')) print util.xor(k, c).tostring().encode('hex')
# parse as Parser a -> [a] -> Maybe (RoseTree a [Char]) parse = lambda p:lambda la:p(Accept([],Node("__ROOT__",[]),la))( Nothing, lambda _,d,__:Just(d) ) # type parser a is ParserState a -> ParserState a # empty as parser a empty = I # term as [a] -> Bool -> parser a term = lambda ll, f: lambda ps: ps( I, lambda v,p,d: (Fail if not xor(d[0] in ll,f) else ( p( Const(Fail), lambda a,ls: Accept([],Node(a,ls+[Leaf(d[0])]),d[1:]) ) )) if len(d)>0 else Fail ) # noTerm as [Char] -> parser a -> parser a noTerm = lambda n,pp:lambda ps: ps( ps, # lambda v,p,d: Fail if n in v else ( lambda v,p,d: Fail if len(list(filter(lambda x:x==n,v))) > 1 else ( let(pp(Accept(v+[n],Node(n,[]),d)),lambda ps1: ps1( ps1, lambda v,p1,d1: Accept(v,
def crypt(self, m): return util.xor(m, self._keystream())
def whitener(binary_string, key, size=48): res = xor(binary_string, key) spec = '0>{}b'.format(size) return format(res, spec)
in_1_str = "1c0111001f010100061a024b53535009181c" in_2_str = "686974207468652062756c6c277320657965" out_str = "746865206b696420646f6e277420706c6179" from util import xor, raw_2_hex, hex_2_raw print('input 1 : [{}]'.format(in_1_str)) print('input 2 : [{}]'.format(in_2_str)) print('expected output : [{}]'.format(out_str)) print('real output : [{}]'.format( raw_2_hex(xor(hex_2_raw(in_1_str), hex_2_raw(in_2_str))).decode('utf-8')))
#!/bin/env python import util import array import sys # python challenge5.py key plaintext.txt key = array.array('B', sys.argv[1]) with open(sys.argv[2], 'rb') as f: plaintext = array.array('B', f.read().rstrip()) ciphertext = array.array('B') keylen = len(key) print util.xor(key, plaintext).tostring().encode("hex")
print('input : [{}]'.format(in_str)) max_score = -1 max_entry = None for i in range(pow(2, 8)): # For each char c = i.to_bytes(1, 'big') # Pad to input string length padded = c * int(len(in_str) * (4 / 8)) print("##### char : {} ##### padded : {}".format(padded)) continue # XOR to get result result = raw_2_base64(xor(padded, hex_2_raw(in_str))) # print result print("result : {}".format(result)) # Create Frequency ordered dict freq = freq_dict(result) ordered_entries_list = sorted(freq.items(), key=lambda x: x[1], reverse=True) print(ordered_entries_list) # Compare result with normal frequency score = freq_distance(ordered_entries_list[:4]) print(score) if (score > max_score):
def recover(ct): keystream = edit(ct, 0, '\0' * len(ct)) return util.xor(ct, keystream)
def stream_salsa20_xor(m, n, k): return xor(m, stream_salsa20(len(m), n, k))
# print input data = base64.standard_b64decode(input) # print data # Doing it automatically iv = '\x00' * 16 aes = AES.new('YELLOW SUBMARINE', AES.MODE_CBC, iv) decrypted = aes.decrypt(data) # print decrypted # Doing it by hand aes = AES.new('YELLOW SUBMARINE', AES.MODE_ECB) prevBlock = iv blockSize = 16 encBlocks = [] for i in range(0, len(decrypted), blockSize): block = decrypted[i:i + blockSize] block = xor(block, prevBlock) encBlock = aes.encrypt(block) # print encBlock encBlocks.append(encBlock) prevBlock = encBlock encData = ''.join(encBlocks) print encData == data
def edit(self, ct, pt, offset): tmp = bytearray(ct) tmp[offset:offset + len(pt)] = util.xor(pt, self._keystream(offset)) return bytes(tmp)
def secretbox_xsalsa20poly1305(m, n, k): s = stream_xsalsa20(32 + len(m), n, k) c = xor(m, s[32:]) a = onetimeauth_poly1305(c, s[:32]) return a + c
def pad(c): return xor(chr(c) * 128, k + '\0' * 96)
def crypto_stream_xsalsa20_xor(m, n, k): return xor(m, crypto_stream_xsalsa20_xor(len(m), n, k))
ciphertext = array.array('B', base64.decodestring(f.read())) for keysize in range(2, 41): scores[keysize] = util.normalized_hamming(ciphertext, keysize) chosen_keysize = min(scores, key=scores.get) print "Min Hamming score: %s for keysize: %i" % (scores[chosen_keysize], chosen_keysize) #for (ks, hs) in sorted(scores.items(), key=operator.itemgetter(1)): # print "%02i: %f" % (ks, hs) #chosen_keysize = int(raw_input("Which keysize? ")) blocks = defaultdict(util.default_array) for i in range(0, len(ciphertext)): blocks[i % chosen_keysize].append(ciphertext[i]) key = array.array('B') for k in blocks: key.append(util.predict_single_xor(blocks[k])['key']) print "Predicted key: %s" % key.tostring() #chosen_key = array.array('B', raw_input("Enter key [leave blank to use found key]: ")) #if len(chosen_key) == 0: # chosen_key = key print "Decrypted text:\n" print util.xor(key, ciphertext).tostring()
b = (1 - Z * Z) return (a * b).sum(axis=0) def cross_entropy(self, T, Y): e = T * np.log(Y) + (1 - T) * np.log(1 - Y) return -np.sum(e) def classification_rate(self, Y, P): return np.mean(Y == P) if __name__ == '__main__': X, Y = xor() X, Y = shuffle(X, Y) T = np.zeros((len(Y), len(set(Y)))) idx_row = np.arange(len(Y)) idx_col = Y.astype(int) T[idx_row, idx_col] = 1 N = len(Y) // 2 Xtrain = X[:N] Ytrain = Y[:N] T_train = T[:N] Xtest = X[N:] Ytest = Y[N:] T_test = T[N:] D = X.shape[1] M = 5 K = len(set(Y))
def pad(c): return xor(chr(c) * 128, k + '\0' * 96) m = hash_sha512(pad(0x36) + m)