Пример #1
0
 def from_raw(cls, raw_obj):
     tx_out_id = hex_to_bytes(raw_obj['txOutId'])
     tx_out_index = raw_obj['txOutIndex']
     address = hex_to_bytes(raw_obj['address'])
     amount = raw_obj['amount'] if isinstance(
         raw_obj['amount'], Decimal) else Decimal(raw_obj['amount'])
     return cls(tx_out_id, tx_out_index, address, amount)
Пример #2
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)
Пример #3
0
def chal4():
    """
    One of the 60-character strings in input/4.txt has been
    encrypted with single-character XOR. Find it and decrypt it.
    """
    f = open('input/4.txt')
    # TODO Fenimore's suggestion about using an uppercase key
    OUT = b'nOW\x00THAT\x00THE\x00PARTY\x00IS\x00JUMPING*'
    best_score = 0
    result = ''

    for line in f:
        ciphertext = utils.hex_to_bytes(line.strip())

        # Assume the most popular byte in the ciphertext is the key
        key = utils.get_popular_byte(ciphertext)

        # Try the key
        plaintext_bytes = _crypto.xor_single_byte_key(ciphertext, key)

        score = utils.english_score(str(plaintext_bytes))

        # The decrypted string that looks most like English is most
        # likely the one we're looking for
        if score > best_score:
            best_score = score
            result = plaintext_bytes

    expect(result.decode('utf-8'), OUT.decode('utf-8'))
Пример #4
0
def mine_transaction():
    data = request.get_json()
    address = hex_to_bytes(get_param(data, 'address'))
    amount = Decimal(get_param(data, 'amount'))
    block = app.blockchain.generate_next_with_transaction(
        app.wallet, address, amount)
    return jsonify(block.to_raw() if block else None)
Пример #5
0
def send_transaction():
    data = request.get_json()
    print('/sendTransaction data: {}'.format(data))
    address = hex_to_bytes(get_param(data, 'address'))
    amount = Decimal(get_param(data, 'amount'))
    print('address: {}, amount: {}'.format(address, amount))
    tx = app.blockchain.send_transaction(app.wallet, address, amount)
    return jsonify(tx.to_raw() if tx else None)
Пример #6
0
def revoke_creds_cmd(txid, cred_hash1, cred_hash2=None):
    bstring = (_create_header() + operators['op_revoke_creds'] +
               utils.hex_to_bytes(txid) + utils.ripemd160(cred_hash1))

    if cred_hash2:
        bstring += utils.ripemd160(cred_hash2)

    return bstring
Пример #7
0
def issue_abs_expiry_cmd(issuer_identifier, merkle_root, expiry):
    expiry = int(expiry)

    # if expiry is in the past
    if expiry < time.time():
        raise TypeError("Absolute expiry is in the past")
    if expiry > 0xffffffffff:
        raise TypeError("Absolute expiry is greater than allowed")

    # uses 5 bytes so convert to hex and right justify (pad) accordingly
    expiry_hex = format(expiry, 'x')
    expiry_hex_padded = expiry_hex.rjust(10, '0')

    bstring = (_create_header() + operators['op_issue_abs_expiry'] +
               _str_to_8_chars(issuer_identifier).encode('utf-8') +
               utils.hex_to_bytes(merkle_root) +
               utils.hex_to_bytes(expiry_hex_padded))
    return bstring
Пример #8
0
def find_and_decrypt_ciphertexts(ciphertexts: List[str]):
    plaintexts = {}  # type: Dict[str, str]
    for c in ciphertexts:
        key, string = decode_1_byte_xor(hex_to_bytes(c))
        if not key or not string:
            continue
        plaintexts[string] = key
    res = find_english_text(plaintexts.keys())
    return plaintexts[res], res
Пример #9
0
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)
Пример #10
0
 def from_raw(cls, raw_obj):
     index = raw_obj['index']
     previous_hash = hex_to_bytes(
         raw_obj['previousHash']
     ) if raw_obj['previousHash'] is not None else None
     timestamp = datetime.fromtimestamp(raw_obj['timestamp'],
                                        tz=timezone.utc)
     data = Transaction.from_raw_list(raw_obj['data'])
     difficulty = raw_obj['difficulty']
     nonce = raw_obj['nonce']
     return cls(index=index,
                previous_hash=previous_hash,
                timestamp=timestamp,
                data=data,
                difficulty=difficulty,
                nonce=nonce)
Пример #11
0
def chal3():
    """The input has been XORed against a single character. Find the
    key, decrypt the message.
    """
    IN = '1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a' \
         '393b3736'
    OUT = b'cOOKING\x00mc\x07S\x00LIKE\x00A\x00POUND\x00OF\x00BACON'
    ciphertext = utils.hex_to_bytes(IN)

    # I forgot how I figured this out in my Golang implementation, but
    # it turns out there are a bunch of null bytes in the
    # plaintext. A NULL byte in binary is 000000 so when you XOR it
    # with any byte, you get the byte. So in this case, because the
    # NULL byte occurs most frequently in the plaintext, in the
    # ciphertext the key is the most common byte. TODO how in the heck
    # do I figure this out with frequency analysis and without advance
    # knowledge of the fact that there are a bunch of NULL bytes?
    key = utils.get_popular_byte(ciphertext)
    plaintext = _crypto.xor_single_byte_key(ciphertext, key)

    expect(plaintext.decode('utf-8'), OUT.decode('utf-8'))
Пример #12
0
 def from_raw(cls, raw_obj):
     address = hex_to_bytes(raw_obj['address'])
     amount = raw_obj['amount'] if isinstance(
         raw_obj['amount'], Decimal) else Decimal(raw_obj['amount'])
     return cls(address, amount)
Пример #13
0
 def from_raw(cls, raw_obj):
     tx_ins = TxIn.from_raw_list(raw_obj['txIns'])
     tx_outs = TxOut.from_raw_list(raw_obj['txOuts'])
     identifier = hex_to_bytes(raw_obj['id'])
     return cls(tx_ins, tx_outs, identifier)
Пример #14
0
def get_block(hash):
    block = app.blockchain.get_block_with_hash(hex_to_bytes(hash))
    return jsonify(block.to_raw())
Пример #15
0
def get_transaction(id):
    transaction = app.blockchain.get_transaction_with_id(hex_to_bytes(id))
    return jsonify(transaction.to_raw())
Пример #16
0
from utils import decode_base64, decrypt_ecb, encrypt_ecb, hex_to_bytes
from resources import RESOURCES_PATH

with open(RESOURCES_PATH + '7.txt', 'r') as f:
    lines = f.readlines()

key = b'YELLOW SUBMARINE'
encrypted_data = hex_to_bytes(decode_base64(b''.join(bytes(line.strip(), 'utf-8') for line in lines)))
print(decrypt_ecb(key=key, cipher_text=encrypted_data).decode('utf-8'))

test_str = b'GANAN    GIDEL    DAGAN    BAGAN'
assert(decrypt_ecb(key=key, cipher_text=encrypt_ecb(key=key, plain_text=test_str)) == test_str)
Пример #17
0
def issue_cmd(issuer_identifier, merkle_root):
    bstring = (_create_header() + operators['op_issue'] +
               _str_to_8_chars(issuer_identifier).encode('utf-8') +
               utils.hex_to_bytes(merkle_root))
    return bstring
Пример #18
0
# If your function works properly, then when you feed it the string:

# 1c0111001f010100061a024b53535009181c

# ... after hex decoding, and when XOR'd against:

# 686974207468652062756c6c277320657965

# ... should produce:

# 746865206b696420646f6e277420706c6179

if __name__=="__main__":
	parser=argparse.ArgumentParser()
	parser.add_argument("a",help="Input 1")
	parser.add_argument("b",help="Input 2")

	args = parser.parse_args()

	a = utils.hex_to_bytes(args.a)
	b = utils.hex_to_bytes(args.b)

	result = bytearray(utils.xor_bytes(a,b))

	result = utils.byte_to_hex(result)
	print("Input 1 : ",args.a)
	print("Input 2 : ",args.b)
	print("Output  : ",result.decode('utf-8'))

Пример #19
0
def revoke_address_cmd(pkh):
    bstring = (_create_header() + operators['op_revoke_address'] +
               utils.hex_to_bytes(pkh))

    return bstring
Пример #20
0
def revoke_batch_cmd(txid):
    bstring = (_create_header() + operators['op_revoke_batch'] +
               utils.hex_to_bytes(txid))
    return bstring
Пример #21
0
def hex_to_base64(bstr: str):
    return bytes_to_base64(hex_to_bytes(bstr))
Пример #22
0
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])
Пример #23
0
 def from_raw(cls, raw_obj):
     tx_out_id = hex_to_bytes(raw_obj['txOutId'])
     tx_out_index = raw_obj['txOutIndex']
     signature = hex_to_bytes(
         raw_obj['signature']) if raw_obj['signature'] is not None else None
     return cls(tx_out_id, tx_out_index, signature)
Пример #24
0
from utils import decode_base64, hex_to_bytes, byte_byte_ecb_break

unknown_string = b'Um9sbGluJyBpbiBteSA1LjAKV2l0aCBteSByYWctdG9wIGRvd24gc28gbXkgaGFpciBjYW4gYmxvdwpUaGUgZ2lybGllcy' \
                 b'BvbiBzdGFuZGJ5IHdhdmluZyBqdXN0IHRvIHNheSBoaQpEaWQgeW91IHN0b3A/IE5vLCBJIGp1c3QgZHJvdmUgYnkK'

hex_decoded = hex_to_bytes(decode_base64(unknown_string))

print(byte_byte_ecb_break(unknown_str=hex_decoded, hard=True))
assert (byte_byte_ecb_break(unknown_str=hex_decoded, hard=True) == hex_decoded)

if __name__ == "__main__":
    # sock = utils.create_socket(CONNECTION_ADDR)
    # Call block_size here because of strange issue that happened
    # block_size = calcBlockSize()
    
    block_size = calcBlockSize()*8
    while True:
        try:
            
            response = input("send a message: ") # Read a message from standard input
            print("[Client] Plaintext:  \"{}\"".format(response))

            resp = utils.send_message(sock_A_input, sock_A_output, response)
            decode_all_blocks2(utils.hex_to_bytes(resp), block_size)

            #i_n_b1, b = decode_last_char(resp.encode(), block_size)
            #decode_last_block2(resp.encode(), block_size, i_n_b1)

            print('')
            print("[Server] Ciphertext: \"{}\"".format(resp))
        except Exception as e:
            print(e)
            print("Closing...")
            sock_A_input.close()
            sock_A_output.close()
            sock_B_input.close()
            sock_B_output.close()
            sock_C_input.close()
            sock_C_output.close()
Пример #26
0
def get_address_info(address):
    uTxOs = app.blockchain.unspent_tx_outs_for_address(hex_to_bytes(address))
    return jsonify({'unspentTxOuts': UnspentTxOut.to_raw_list(uTxOs)})
Пример #27
0
import argparse
import utils

# Convert hex to base64

# The string:

# 49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d

# Should produce:

# SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("input", help="Hexadecimal input for conversion")
    args = parser.parse_args()
    print("Input : ", args.input)
    print("Output : ", utils.hex_to_bytes(args.input).decode("utf-8"))
    print("Output : ", utils.hex_to_base64(args.input).decode("utf-8"))
Пример #28
0
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)
    }
Пример #29
0
def calc_txid(tx_hex):
    return bytes_to_hex(double_sha256(hex_to_bytes(tx_hex))[::-1])
Пример #30
0
from utils import encode_base64, hex_to_bytes

bytes_to_encode = hex_to_bytes(
    '49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d'
)

expected_result = b'SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t'

print(encode_base64(hex_bytes=bytes_to_encode), expected_result)
assert (encode_base64(hex_bytes=bytes_to_encode) == expected_result)
Пример #31
0
    f: 2.228,
    g: 2.015,
    h: 6.094,
    i: 6.966,
    j: 0.153,
    k: 0.772,
    l: 4.025,
    m: 2.406,
    n: 6.749,
    o: 7.507,
    p: 1.929,
    q: 0.095,
    r: 5.987,
    s: 6.327,
    t: 9.056,
    u: 2.758,
    v: 0.978,
    w: 2.360,
    x: 0.150,
    y: 1.974,
    z: 0.074,
}

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("input", "Hex encoded string")

    args = parser.parse_args()

    encoded = utils.hex_to_bytes(args.input)