Example #1
0
    def str(self):
        """Return the pkt contents in printable form"""
        try:
            parts = []
            sync_code = self._pkt_buf[:CASESPkt.SYNC_BYTE_3 + 1]
            parts.append('  sync code = %s' % utils.bytes_to_hex(sync_code))
            if sync_code == CASESPkt.SYNC_CODE_STR:
                parts.append(' (valid)\n')
            else:
                parts.append(' (NOT valid)\n')
            parts.append('  length = %s' % str(self.get_len()))
            if len(self._pkt_buf) == self.get_pkt_len():
                parts.append(' (valid)\n')
            else:
                parts.append(' (NOT valid)\n')
            parts.append('  type = %s' % str(self.get_type()))
            parts.append(''.join([' (', self.type_str(), ')\n']))

            parts.append(''.join(['  ', self.data_str(), '\n']))

            pkt_len = self.get_len() + 10
            parts.append('  checksum = %s' % \
                    utils.bytes_to_hex(self._pkt_buf[pkt_len - 2:]))
            if (self.cksum_is_valid()):
                parts.append(' (valid)')
            else:
                parts.append(' (NOT valid)')
            return ''.join(parts)
        except IndexError:
            print 'IndexError in CASESPkt.str()'
            return ''
Example #2
0
 def to_raw(self):
     return {
         'txOutId': bytes_to_hex(self.tx_out_id),
         'txOutIndex': self.tx_out_index,
         'address': bytes_to_hex(self.address),
         'amount': self.amount
     }
def decode_last_char(c_text, block_size):
    """
    Toma un texto cifrado, y tamaño de bloque
    Retorna el último byte del mensaje original del texto cifrado
    :param c_text: byte-like message
    """
    error_mssg = "pkcs7"                                    # Prefijo de error típico de padding
    blocks_array = utils.split_blocks(c_text, block_size//8)# Get cyphered text as an bytearray
    n = len(blocks_array)                                   # Cantidad n de bloques
    b = block_size//8                                       # Cantidad b de bytes por bloque
    
    m_n1 = bytearray(b)                                     # Crea bytearray de largo 128//8 = 16 bytes
    for i in range(0, b - 1):                               # Copia del byte 0 al 15
        m_n1[i] = blocks_array[n-2][i]                      # Obtener M[n-1] copiando de C[n-1]

    i = 1                                                   # De 0 a 256
    # print("Decode last char", flush = True)
    ant_mn1 = m_n1[b-1] 
    while True:
        if (ant_mn1 == i):
            pass
        else:
            #print(i, flush=True)
            m_n1[b-1] = i                                       # M[n-1][BlockSize-1] = i
            blocks_array[n-2] = m_n1                            # Sobrescribimos el blocks_Array[n-2] por el M[n-1]
            modified_c_text = utils.bytes_to_hex(utils.join_blocks(blocks_array)) # Joinblocks and then cast to hex
            resp = utils.send_message(sock_B_input, sock_B_output, modified_c_text) # Send to sock_B
            #print(resp, flush=True)
            if not resp.startswith(error_mssg):                 # Check if there is not a padding error, we have a candidate
                                                                  # Validar: Asegurar que texto plano termina en 0x01
                #print("Validando... ")
                ant = m_n1[b-2]                                 # M[n-1][b-2] penúltimo valor antiguo
                m_n1[b-2] = (ant+125) % 256                       # Cambiar a otro valor
                blocks_array[n-2] = m_n1                        # Modificamos M[n-2]
                modified_c_text = utils.bytes_to_hex(utils.join_blocks(blocks_array))   # Joinblocks and then cast to hex
                resp = utils.send_message(sock_B_input, sock_B_output, modified_c_text) # Acá tenemos que el texto descifrado es del estilo [.....[0xfe][0x01]]

                if resp.startswith(error_mssg):                          # Si no validó estamos en un caso donde podríamos haber encontrado un falso positivo, ej: que el último byte descifrado fuera [0x02] y el byte anterior cifrado [0x02]. Ahora da [...[0xfe][0x02]] y no pasa
                    #print("No valida, falso positivo encontrado, valor encontrado para M[n-1][b-1] incosistente, buscando otro valor ...")
                    m_n1[b-2] = ant                             # Always Revert al valor C[n-1][b-2] original
                    blocks_array[n-2] = m_n1
                    modified_c_text = utils.bytes_to_hex(utils.join_blocks(blocks_array))
                else:
                    m_n1[b-2] = ant                             # Always Revert
                    blocks_array[n-2] = m_n1
                    modified_c_text = utils.bytes_to_hex(utils.join_blocks(blocks_array))
                    break                                       # Pasó validación, encontramos M[n-1][b-1]
        
        if(i == 0):
            print("Se han probado los 256 valores de padding sin éxito")
            exit(1)

        i = (i+1)%256
    
    i_n = i^1 # XOR para obtener I_[n][b-1]. i = M[n-1][b-1], 1 = 0x01
    c_n1_b1 = utils.split_blocks(c_text, block_size//8)[n-2][b-1] # Get clean C[n-2][b-1]
    #print(i_n^c_n1_b1)
    return i_n, i_n^c_n1_b1 # XOR para obtener B_[n][b-1]
Example #4
0
 def to_raw(self):
     return {
         'txOutId':
         bytes_to_hex(self.tx_out_id),
         'txOutIndex':
         self.tx_out_index,
         'signature':
         bytes_to_hex(self.signature)
         if self.signature is not None else None
     }
Example #5
0
 def data_str(self):
     """Return a printable string containing the first 16 bytes of pkt data"""
     data_len = self.get_data_len()
     max_disp_data_len = 16
     if data_len > max_disp_data_len:
         return ('first %s bytes of data = %s' %
                 (str(max_disp_data_len),
                  utils.bytes_to_hex(self.get_data()[:max_disp_data_len])))
     else:
         return ('data = %s' %
                 utils.bytes_to_hex(self.get_data()[:data_len]))
Example #6
0
 def get_block_with_hash(self, hash):
     block = next((block for block in self.blocks if block.hash == hash),
                  None)
     if not block:
         raise NotFoundError('block not found',
                             {'hash': bytes_to_hex(hash)})
     return block
Example #7
0
 def get_transaction_with_id(self, transaction_id):
     transaction = next((tx for block in self.blocks
                         for tx in block.data if tx.id == transaction_id),
                        None)
     if not transaction:
         raise NotFoundError('transaction not found',
                             {'id': bytes_to_hex(transaction_id)})
     return transaction
Example #8
0
    def str(self):
        """Return the pkt contents in printable form"""
        try:
            parts = []
            parts.append('ProxyPkt:\n')
            sync_code = self._pkt_buf[:ProxyPkt.SYNC_BYTE_3 + 1]
            parts.append('  sync code = %s' % utils.bytes_to_hex(sync_code))
            if sync_code == ProxyPkt.SYNC_CODE_STR:
                parts.append(' (valid)\n')
            else:
                parts.append(' (NOT valid)\n')
            parts.append('  length = %s' % str(self.get_len()))
            if len(self._pkt_buf) == self.get_len():
                parts.append(' (valid)\n')
            else:
                parts.append(' (NOT valid)\n')
            type = self.get_type()
            parts.append('  type = %s' % str(type))
            if type == ProxyPkt.PASSTHROUGH:
                parts.append(' (passthrough)\n')
            elif type == ProxyPkt.ICCID_REQ:
                parts.append(' (ICCID request)\n')
            elif type == ProxyPkt.ICCID:
                parts.append(' (ICCID)\n')
            elif type == ProxyPkt.CONNECT:
                parts.append(' (CONNECT)\n')
            elif type == ProxyPkt.DISCONNECT:
                parts.append(' (DISCONNECT)\n')
            else:
                parts.append(' (unknown type)\n')

            parts.append('  data = %s\n' % utils.bytes_to_hex(self.get_data()))
            pkt_len = self.get_len()
            parts.append('  checksum = %s' % \
                    utils.bytes_to_hex(self._pkt_buf[pkt_len - 2:]))
            if (self.cksum_is_valid()):
                parts.append(' (valid)\n')
            else:
                parts.append(' (NOT valid)\n')
            return ''.join(parts)
        except IndexError:
            print 'IndexError in ProxyPkt.str()'
            return ''
Example #9
0
 def validate(self, transaction, unspent_tx_outs):
     condition = lambda uTxO: uTxO.tx_out_id == self.tx_out_id and uTxO.tx_out_index == self.tx_out_index
     referenced_uTxO = next(
         (uTxO for uTxO in unspent_tx_outs if condition(uTxO)), None)
     if not referenced_uTxO:
         print('referenced tx_out not found: {}'.format(self.__dict__))
         return False
     address = referenced_uTxO.address
     vk = ecdsa.VerifyingKey.from_string(address)
     result = False
     print('validating tx_in signature: {}\naddress: {}\ndata: {}'.format(
         bytes_to_hex(self.signature), bytes_to_hex(address),
         bytes_to_hex(transaction.id)))
     try:
         if self.signature:
             result = vk.verify(self.signature, transaction.id)
     except ecdsa.BadSignatureError:
         print('bad signature for tx_in: {}'.format(self))
         pass
     return result
def create_p2pkh_transaction(utxosets, outputs, custom_pushdata=False):

    version = VERSION_1
    lock_time = LOCK_TIME
    # sequence = SEQUENCE
    hash_type = HASH_TYPE
    unspents = [Unspent.from_dict(utxo) for utxo in utxosets]
    input_count = int_to_varint(len(unspents))
    output_count = int_to_varint(len(outputs))

    output_block = construct_output_block(outputs,
                                          custom_pushdata=custom_pushdata)

    # Optimize for speed, not memory, by pre-computing values.
    inputs = []
    for unspent in unspents:
        txid = hex_to_bytes(unspent.txid)[::-1]
        txindex = unspent.txindex.to_bytes(4, byteorder='little')
        amount = unspent.amount.to_bytes(8, byteorder='little')

        inputs.append(TxIn('', 0, txid, txindex, amount))

    hashPrevouts = double_sha256(b''.join([i.txid + i.txindex
                                           for i in inputs]))
    hashSequence = double_sha256(b''.join([SEQUENCE for i in inputs]))
    hashOutputs = double_sha256(output_block)

    # scriptCode_len is part of the script.
    for i, txin in enumerate(inputs):
        private_key = bsv(wif=utxosets[i]['PrivateKey'])
        public_key = bytes.fromhex(private_key.public_key)
        public_key_len = len(public_key).to_bytes(1, byteorder='little')

        scriptCode = (OP_DUP + OP_HASH160 + OP_PUSH_20 +
                      address_to_public_key_hash(private_key.address) +
                      OP_EQUALVERIFY + OP_CHECKSIG)
        scriptCode_len = int_to_varint(len(scriptCode))
        to_be_hashed = (version + hashPrevouts + hashSequence + txin.txid +
                        txin.txindex + scriptCode_len + scriptCode +
                        txin.amount + SEQUENCE + hashOutputs + lock_time +
                        hash_type)
        hashed = sha256(to_be_hashed)  # BIP-143: Used for Bitcoin SV

        # signature = private_key.sign(hashed) + b'\x01'
        signature = private_key.sign(hashed) + b'\x41'

        script_sig = (len(signature).to_bytes(1, byteorder='little') +
                      signature + public_key_len + public_key)

        inputs[i].script = script_sig
        inputs[i].script_len = int_to_varint(len(script_sig))

    return bytes_to_hex(version + input_count + construct_input_block(inputs) +
                        output_count + output_block + lock_time)
Example #11
0
def chal2():
    """XOR two equal-length buffers."""
    IN1 = '1c0111001f010100061a024b53535009181c'
    IN2 = '686974207468652062756c6c277320657965'
    OUT = '746865206b696420646f6e277420706c6179'

    b1 = utils.hex_to_bytes(IN1)
    b2 = utils.hex_to_bytes(IN2)

    result = _crypto.xor(b1, b2)

    # The expected output is hex-encoded
    expect(utils.bytes_to_hex(result), OUT)
Example #12
0
 def generate_next_with_transaction(self, wallet, receiver_address, amount):
     if not TxOut.is_valid_address(receiver_address):
         error_payload = {'address': bytes_to_hex(receiver_address)}
         raise BadRequestError('invalid address', payload=error_payload)
     if not isinstance(amount, Decimal):
         error_payload = {'amount': amount}
         raise BadRequestError('invalid amount', payload=error_payload)
     coinbase_tx = Transaction.coinbase(wallet.get_public_key(),
                                        self.get_latest().index + 1)
     tx = wallet.create_transaction(receiver_address, amount,
                                    self.unspent_tx_outs, self.tx_pool)
     block_data = [coinbase_tx, tx]
     return self.generate_raw_next_block(block_data)
    def transform(self, values):
        result = {}
        for field in values:
            if values[field] is not None:
                if field == "json_data":
                    result[field] = json.loads(values[field])
                elif isinstance(values[field], datetime.datetime):
                    result[field] = datetime.datetime.timestamp(values[field])
                elif isinstance(values[field], bytes):
                    result[field] = utils.bytes_to_hex(values[field])
                else:
                    result[field] = values[field]

        return result
Example #14
0
 def sign_input(self, tx_in_index, private_key, unspent_tx_outs):
     tx_in = self.tx_ins[tx_in_index]
     data_to_sign = self.id
     referenced_unspent_tx_out = UnspentTxOut.find(tx_in.tx_out_id,
                                                   tx_in.tx_out_index,
                                                   unspent_tx_outs)
     if not referenced_unspent_tx_out:
         print('could not find referenced txOut')
         raise BadRequestError('could not find referenced txOut')
     referenced_address = referenced_unspent_tx_out.address
     if get_public_key(private_key) != referenced_address:
         print(
             'trying to sign an input with private ' +
             ' key that does not match the address that is referenced in txIn'
         )
         raise UnauthorizedError('invalid private key')
     print('signing data: {}\nfor address: {}'.format(
         bytes_to_hex(data_to_sign),
         bytes_to_hex(get_public_key(private_key))))
     sk = ecdsa.SigningKey.from_string(private_key)
     signature = sk.sign(data_to_sign)
     print('signature: {}'.format(bytes_to_hex(signature)))
     return signature
Example #15
0
def chal5():
    """Encrypt the input under the key 'ICE' using repeating-key XOR."""
    IN = "Burning 'em, if you ain't quick and nimble\nI go crazy" \
         " when I hear a cymbal"
    OUT = '0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2a2622' \
          '6324272765272a282b2f20430a652e2c652a3124333a653e2b2027630c69' \
          '2b20283165286326302e27282f'
    KEY = 'ICE'

    ciphertext = _crypto.xor_repeating_key(bytes(IN, 'utf-8'),
                                          bytes(KEY, 'utf-8'))
    result = utils.bytes_to_hex(ciphertext)

    expect(result, OUT)
Example #16
0
 def _make_printable(self, s):
     """ Convert the non-printable chars in s to
         their printable hex equivalents.
     """
     p_list = []
     for ch in s:
         ord_ch = ord(ch)
         if (ord_ch < 0x20) or (ord_ch > 0x7E):
             if ord_ch == 0x03:
                 p_list.append('<cntl-c>')
             elif ord_ch == 0x0A:
                 p_list.append('<LF>')
             elif ord_ch == 0x0D:
                 p_list.append('<CR>')
             else:
                 p_list.append('<' + utils.bytes_to_hex(ch) + '>')
         else:
             p_list.append(ch)
     return ''.join(p_list)
    def write(self, records, ptr):

        f = open(self.config['out'], "a")

        for record in records:
            fields = feed.parse_record(record, False)
            record_str = str(datetime.datetime.now()) + "\n"

            if self.config['type'] == "dump-hex":
                record_str = "T: " + record_str

            f.write(record_str)

            record_str = ""
            if self.config['type'] == "dump":
                record_str = event_name(record["code"]) + ", length: " + str(
                    record["length"]) + "\n"
            elif self.config['type'] == "dump-hex":
                record_str = "R: {code:02x}: {length}\n".format(
                    code=record["code"], length=record["length"])
            f.write(record_str)

            for field in fields:
                value = field["value"]
                if multichain.is_binary_field(field["code"]):
                    value = utils.bytes_to_hex(value)
                field_str = ""
                if self.config['type'] == "dump":
                    field_str = "   " + field_name(
                        field["code"]) + ", length: " + str(
                            field["length"]) + ": " + str(value) + "\n"
                elif self.config['type'] == "dump-hex":
                    field_str = "F: {code:02x}: ".format(
                        code=field["code"]) + str(value) + "\n"

                f.write(field_str)

        f.close

        self.pointer = ptr

        return utils.write_file_ptr(self.config, ptr)
def decode_last_block2(c_text, block_size, i_n_b1):
    """
    Toma un texto cifrado, y tamaño de bloque
    Retorna el último bloque del mensaje original del texto cifrado
    :param c_text: byte-like message
    """
    error_mssg = "pkcs7"                                        # Prefijo de error típico de padding
    blocks_array = utils.split_blocks(c_text, block_size//8)    # Get cyphered text as an bytearray
    n = len(blocks_array)                                       # Cantidad n de bloques
    b = block_size//8                                           # Cantidad b de bytes por bloque

    i_n = bytearray(b)                                          # Crea bytearray de largo 128//8 = 16 bytes
    for i in range(0, b - 2):                                   # Copia del byte 0 al 15
        i_n[i] = 0
    i_n[b-1] = i_n_b1                                           # Único Valor conocido a la fecha

    queremos = b - 2                                            # Queremos conocer b - 2 al inicio
    while queremos >= 0:
        print("Descifrando byte: " + str(queremos), flush = True)
        conocemos = queremos + 1                                # Conocemos de b-1 : b-1, 
        paddingByte = b - queremos                              # Padding byte

        m_n1 = bytearray(b)                                     # Crea bytearray de largo 128//8 = 16 bytes
        for i in range(0, b):                                   # [[0].....................[b-1]]
            m_n1[i] = blocks_array[n-2][i]                      # M[n-1] = C[n-1]

        for i in range(conocemos, b):                           # [.........[conocemos]....[b-1]]
            m_n1[i] = i_n[i]^paddingByte                        # M[n-1] = I[n] XOR PaddingByte, para que al hacer el servidor M[n-1][i] XOR I[n-1][i] de PaddingByte
        
        i = 1                                                   # De 0 a 256
        ant_mn1 = m_n1[b-1]
        while True:
            if (i == ant_mn1):
                pass
            else:
                #print(i, flush=True)
                m_n1[queremos] = i                                  # M[n-1][Queremos] = i
                blocks_array[n-2] = m_n1                            # Sobrescribimos el blocks_Array[n-2] por el M[n-1]
                modified_c_text = utils.bytes_to_hex(utils.join_blocks(blocks_array)) # Joinblocks and then cast to hex
                resp = utils.send_message(sock_B_input, sock_B_output, modified_c_text) # Send to sock_B
                #print(resp, flush=True)
                if not resp.startswith(error_mssg):                 # Check if there is not a padding error, we have a candidate
                    if queremos != 0:                               # Si el es primer byte, no podemos validar
                        
                        # Validar: Asegurar que texto plano termina en 0x01
                        ant = m_n1[queremos-1]                      # M[n-1][queremos-1] penúltimo valor antiguo
                        m_n1[queremos-1] = (ant+1) % 256              # Cambiar a otro valor
                        blocks_array[n-2] = m_n1                    # Modificamos M[n-2]
                        modified_c_text = utils.bytes_to_hex(utils.join_blocks(blocks_array))   # Joinblocks and then cast to hex
                        resp = utils.send_message(sock_B_input, sock_B_output, modified_c_text) # Ask if it still works

                        if resp.startswith(error_mssg):             # No validó There is an error message, go back
                            #print("No valida, falso positivo encontrado, valor encontrado para M[n-1][queremos] incosistente, buscando otro valor ...")
                            m_n1[queremos-1] = ant                  # Always Revert
                            blocks_array[n-2] = m_n1
                            modified_c_text = utils.bytes_to_hex(utils.join_blocks(blocks_array))
                        else:
                            m_n1[queremos-1] = ant                  # Always Revert
                            blocks_array[n-2] = m_n1
                            modified_c_text = utils.bytes_to_hex(utils.join_blocks(blocks_array))
                            break                                   # Pasó validación, encontramos M[n-1][queremos]
                    else:
                        break
            if (i == 0):
                print("Se han probado los 256 valores de padding sin éxito")
                exit(1)
            i = (i + 1)%256                         # Try next i
                
        i_n[queremos] = i^paddingByte # XOR para obtener I_[n][queremos]. i = M[n-1][queremos], paddingByte = 0x02, 0x03 ...
        queremos -= 1

    # Obtener el último bloque
    c_n1 = utils.split_blocks(c_text, block_size//8)[n-2]       # Get clean C[n-2][b-1]
    b_n = bytearray(b)                                          # Crea bytearray de largo 128//8 = 16 bytes
    for i in range(0, b):                                   # Copia del byte 0 al 15
        b_n[i] = i_n[i]^c_n1[i]
    # print(b_n)
    #print(binascii.unhexlify(b_n.hex()))
    return b_n                                                  # Return bytearray del texto descifrado
Example #19
0
def hex_op(op):
    return utils.bytes_to_hex(operators[op])
def generate_sighash_single_rawtx(utxosets, changeaddress, authrized_amount):
    unspents = [Unspent.from_dict(utxo) for utxo in utxosets]
    version = VERSION_1
    lock_time = LOCK_TIME
    #sequence = SEQUENCE

    input_count = int_to_varint(len(unspents))

    inputs = []
    total_input_amount = 0
    for unspent in unspents:
        txid = hex_to_bytes(unspent.txid)[::-1]
        txindex = unspent.txindex.to_bytes(4, byteorder='little')
        amount = unspent.amount.to_bytes(8, byteorder='little')
        inputs.append(TxIn('', 0, txid, txindex, amount))
        total_input_amount += unspent.amount  #satoshi

    output_count = int_to_varint(1)
    output_block = b''
    output_script = (OP_DUP + OP_HASH160 + OP_PUSH_20 +
                     address_to_public_key_hash(changeaddress) +
                     OP_EQUALVERIFY + OP_CHECKSIG)
    output_block += (total_input_amount - authrized_amount).to_bytes(
        8, byteorder='little')  #satoshi
    output_block += int_to_varint(len(output_script))
    output_block += output_script

    hashPrevouts = double_sha256(b''.join([i.txid + i.txindex
                                           for i in inputs]))
    hashSequence = bytes.fromhex(
        '0000000000000000000000000000000000000000000000000000000000000000')
    # scriptCode_len is part of the script.
    for i, txin in enumerate(inputs):
        if i == 0:
            hashOutputs = double_sha256(output_block)
            hash_type = 0x43.to_bytes(4, byteorder='little')  #sighash single
        else:
            hashOutputs = bytes.fromhex(
                '0000000000000000000000000000000000000000000000000000000000000000'
            )
            hash_type = 0x42.to_bytes(4, byteorder='little')  #sighash none

        private_key = bsv(utxosets[i]['PrivateKey'])
        public_key = bytes.fromhex(private_key.public_key)
        public_key_len = len(public_key).to_bytes(1, byteorder='little')
        scriptCode = (OP_DUP + OP_HASH160 + OP_PUSH_20 +
                      address_to_public_key_hash(private_key.address) +
                      OP_EQUALVERIFY + OP_CHECKSIG)
        scriptCode_len = int_to_varint(len(scriptCode))
        to_be_hashed = (version + hashPrevouts + hashSequence + txin.txid +
                        txin.txindex + scriptCode_len + scriptCode +
                        txin.amount + SEQUENCE + hashOutputs + lock_time +
                        hash_type)
        hashed = sha256(to_be_hashed)  # BIP-143: Used for Bitcoin SV

        # signature = private_key.sign(hashed) + b'\x01'   sighash ALL  ; single b'\x03' ,NONE b'\x02'
        if i == 0:
            signature = private_key.sign(hashed) + b'\x43'
        else:
            signature = private_key.sign(hashed) + b'\x42'

        script_sig = (len(signature).to_bytes(1, byteorder='little') +
                      signature + public_key_len + public_key)

        inputs[i].script = script_sig
        inputs[i].script_len = int_to_varint(len(script_sig))

    return {
        "version": bytes_to_hex(version),
        "input": bytes_to_hex(input_count + construct_input_block(inputs)),
        "output": bytes_to_hex(output_block),
        "lock_time": bytes_to_hex(lock_time)
    }
Example #21
0
 def to_raw(self):
     return {'address': bytes_to_hex(self.address), 'amount': self.amount}
Example #22
0
 def to_raw(self):
     return {
         'txIns': TxIn.to_raw_list(self.tx_ins),
         'txOuts': TxOut.to_raw_list(self.tx_outs),
         'id': bytes_to_hex(self.id)
     }
Example #23
0
def get_address():
    address = bytes_to_hex(app.wallet.get_public_key())
    return jsonify({'address': address})
def calc_txid(tx_hex):
    return bytes_to_hex(double_sha256(hex_to_bytes(tx_hex))[::-1])
def main():
    res1 = hex_to_base64(
        '49276d206b696c6c696e6720796f757220627261696e206c6'
        '96b65206120706f69736f6e6f7573206d757368726f6f6d')
    print('Task 1')
    print(res1)
    assert res1 == (b'SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc'
                    b'29ub3VzIG11c2hyb29t')

    print('Task 2')
    x = hex_to_bytes('1c0111001f010100061a024b53535009181c')
    y = hex_to_bytes('686974207468652062756c6c277320657965')
    res2 = bytes_to_hex(xor(x, y))
    print(res2)
    assert res2 == '746865206b696420646f6e277420706c6179'

    print('Task 3')
    ciphertext = hex_to_bytes('1b37373331363f78151b7f2b783431333d78397828372d'
                              '363c78373e783a393b3736')
    res3 = decode_1_byte_xor(ciphertext)
    print(res3[1])
    assert res3[1] == "Cooking MC's like a pound of bacon"

    print('Task 4')
    ciphertexts = get_file('4.txt').split('\n')
    res4 = find_and_decrypt_ciphertexts(ciphertexts)
    print('Key: {0}\nPlaintext: {1}'.format(*res4))
    assert res4[1] == 'Now that the party is jumping\n'

    print('Task 5')
    plaintext5 = ("Burning 'em, if you ain't quick and nimble\n"
                  "I go crazy when I hear a cymbal""")
    key = "ICE"
    correct_answer = ("0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343"
                      "c2a26226324272765272a282b2f20430a652e2c652a3124333a653e"
                      "2b2027630c692b20283165286326302e27282f")
    res5 = bytes_to_hex(repeating_key_xor(text_to_bytes(plaintext5),
                                          text_to_bytes(key)))
    print(res5)
    assert res5 == correct_answer

    print('Task 6')
    string1 = b'this is a test'
    string2 = b'wokka wokka!!!'
    print('Hamming Distance Check:', hamming_distance(string1, string2))
    ciphertext6 = get_file('6.txt')
    ciphertext6 = base64_to_bytes(ciphertext6)
    res6 = decode_repeating_byte_xor(ciphertext6)
    assert res6[0] == 'Terminator X: Bring the noise'
    print('Key:', res6[0])
    print('Plaintext:')
    print(res6[1])

    print('Task 7')
    ciphertext7 = get_file('7.txt')
    ciphertext7 = base64_to_bytes(ciphertext7)
    password = b"YELLOW SUBMARINE"
    res7 = aes_ecb_decode(ciphertext7, password).decode('ascii')
    assert res7.startswith("I'm back and I'm ringin' the bell ")
    print(res7)

    print('Task 8')
    ciphertexts8 = get_file('8.txt').split('\n')
    ciphertexts8 = [bytes.fromhex(x) for x in ciphertexts8 if x]
    res8 = detect_aes_ecb_encrypted_texts(ciphertexts8)
    assert len(res8[1]) == 1
    print('Most likely string:', bytes_to_hex(res8[1][0]))
    print('Max no. of repeats of a 16byte chunk found:', res8[0])
def decode_last_char(c_text, block_size):
    d = {}
    # Get cyphered text as an bytearray
    blocks_array = utils.split_blocks(c_text, block_size)
    # Define block_size
    block_size_arr = len(blocks_array)
    # Get last block or C_{n}
    c_n = blocks_array[len(blocks_array) - 1]
    # Get block C_{n-1}
    c_n1 = blocks_array[len(blocks_array) - 2]
    # TODO : Error mssg, can be captured, not just hardcoded by a
    # function called experiments of something like that
    error_mssg = "pkcs7: invalid padding (last byte is larger than total length)"
    # C_{n-1}[BlockSize-1] = 0
    c_n1[len(c_n1) - 1] = 0
    # Declare M_{n-1}
    m_n1 = c_n1
    blocks_array[len(blocks_array) - 2] = m_n1
    # Joinblocks and then cast to hex
    modified_c_text = utils.bytes_to_hex(utils.join_blocks(blocks_array))
    i = 1
    # Do-While
    while True:
        # Send to sock_B
        resp = utils.send_message(sock_B, modified_c_text)
        # Dictionary
        d[i] = resp
        # Check if there is not a padding error
        #if not resp.startswith('pkcs7'):
        #    break
        # Increase M_{n-1}[BlockSize-1] in one
        m_n1[len(c_n1) - 1] = i
        # Create a new M_{n-1}
        blocks_array[len(blocks_array) - 2] = m_n1
        # Joinblocks and then cast to hex
        modified_c_text = utils.bytes_to_hex(utils.join_blocks(blocks_array))
        i += 1
        if i > 255:
            break
    # Print dictionary
    pprint(d)
    print("Pasa While")
    print(i)
    # Asegurar que texto plano termina en 0x01
    # Almacenar valor anterior, por si no se asegura
    ant = m_n1[len(c_n1) - 2]
    # Cambiar a otro valor
    m_n1[len(c_n1) - 1] += 1
    blocks_array[len(blocks_array) - 2] = m_n1
    # Joinblocks and then cast to hex
    modified_c_text = utils.bytes_to_hex(utils.join_blocks(blocks_array))
    # Ask if it still works
    resp = utils.send_message(sock_B, modified_c_text)
    # There is an error message, go back
    if resp.startswith('pkcs7'):
        print("No termina en 0x01")
    m_n1[len(c_n1) - 1] = ant
    blocks_array[len(blocks_array) - 2] = m_n1
    modified_c_text = utils.bytes_to_hex(utils.join_blocks(blocks_array))
    # Else there is not, continue with the same M_{n-1}
    print("This code has done something until this point")
    # XOR_1
    # Get M_{n-1}[BlockSize-1]
    value_1 = m_n1[len(m_n1) - 1]
    #value_1 = i
    # Get 0x01
    value_2 = 1
    # Do XOR and get I_{n}[Blocksize-1]
    i_n = value_1 ^ value_2

    # XOR_2
    # Get clean c_{n-1}
    blocks_array = utils.split_blocks(c_text, block_size)
    c_n1 = blocks_array[len(blocks_array) - 2]
    # Get last byte of c_n1
    value_1 = c_n1[len(c_n1) - 1]
    # Recover I_{n}[Blocksize-1]
    value_2 = i_n
    # Do XOR and get B_{n}[BlockSize-1]
    result = value_1 ^ value_2
    print(result)
    return result
Example #27
0
    parser.add_argument(
        '-k',
        '--key_location',
        help='location of wallet private key (defaults to "wallet/pk.pem")',
        default='wallet/pk.pem',
        type=str)
    args = parser.parse_args()

    tx_pool = TransactionPool()
    blockchain = Blockchain(tx_pool)
    wallet = Wallet(args.key_location)
    p2p_application = P2PApplication(blockchain)
    blockchain.p2p_application = p2p_application
    web_app.blockchain = blockchain
    web_app.p2p_application = p2p_application
    web_app.wallet = wallet

    print('My pubblic address is: {}'.format(
        bytes_to_hex(wallet.get_public_key())))

    server_url = 'ws://127.0.0.1:{}'.format(args.p2p_port)
    print('Starting p2p server at {}'.format(server_url))
    p2p_application.start_server(server_url)

    # pylint: disable=maybe-no-member
    resource = WSGIResource(reactor, reactor.getThreadPool(), web_app)
    site = Site(resource)
    print('Starting web server at http://127.0.0.1:{}'.format(args.web_port))
    reactor.listenTCP(args.web_port, site)
    reactor.run()
    # Do XOR and get B_{n}[BlockSize-1]
    result = value_1 ^ value_2
    print(result)
    return result


if __name__ == "__main__":
    # sock = utils.create_socket(CONNECTION_ADDR)
    # Call block_size here because of strange issue that happened
    block_size = calcBlockSize()
    while True:
        try:
            # Read a message from standard input
            response = input("send a message: ")
            # The next line is a good hint
            # You need to use encode() method to send a string as bytes.
            print("[Client] \"{}\"".format(response))
            print(utils.bytes_to_hex(response.encode()))
            # resp = utils.send_message(sock, response)
            resp_A = utils.send_message(sock_A, response)
            resp_B = utils.send_message(sock_B, resp_A)
            print("[Server] \"{}\"".format(resp_A))
            decode_last_char(resp_A.encode(), block_size)
            # Wait for a response and disconnect.
        except Exception as e:
            print(e)
            print("Closing...")
            sock_A.close()
            sock_B.close()
            break