def CheckBlock(filename, curve):
    if os.path.isfile(filename):
        f = open(filename, "r")
        block = f.readlines()
        if len(block)%9 != 0:
            print("Incorrect file format")
            f.close()
            return -10000
        block_count = len(block)//9
        for i in range(0, block_count):
            # coordinates of the public key point
            x1 = int(block[i*9+2][22:-1])
            y1 = int(block[i*9+3][22:-1])
            r = int(block[i*9+7][15:-1])
            s = int(block[i*9+8][15:-1])
            tx = "".join(block[i*9: i*9+7])
            # For the signature verfication
            payer = ECDSA()
            payer_pk = ECPublicKey(Point(x1, y1, curve))
            signature = encode_sig(r, s)
            try:
                assert(payer.verify(tx.encode('UTF-8'), signature, payer_pk))
                ver = 0
                f.close()
                return ver
            except:
                ver = -i-1
                f.close()
                return ver
        return 0
    else:
        print("File does not exist")
        return -10000
    def __verifyUsingPublicKey(self, signature, api_key, params, timestamp,
                               public_key):
        signer = ECDSA()
        pu_bytes = base64.b64decode(public_key)
        # int(pu_bytes[1:33].encode('hex'), 16)
        x = int(binascii.hexlify(pu_bytes[1:33]), 16)
        y = int(binascii.hexlify(pu_bytes[33:]), 16)
        pu_key = ECPublicKey(Point(x, y, cv))
        hashed = hashlib.sha256("{}.{}.{}".format(
            api_key, params, timestamp).encode("UTF-8")).hexdigest()

        return signer.verify(bytearray.fromhex(hashed),
                             bytearray.fromhex(signature), pu_key)
Esempio n. 3
0
### ECS
# test key
cv     = Curve.get_curve('secp256k1')
pv_key = ECPrivateKey(0xf028458b39af92fea938486ecc49562d0e7731b53d9b25e2701183e4f2adc991,cv)
pu_key = ECPublicKey(Point(0x81bc1f9486564d3d57a305e8f9067df2a7e1f007d4af4fed085aca139c6b9c7a,
                           0x8e3f35e4d7fb27a56a3f35d34c8c2b27cd1d266d5294df131bf3c1cbc39f5a91,
                           cv))


k = pv_key.get_public_key()
assert(k.W.x == pu_key.W.x)
assert(k.W.y == pu_key.W.y)

print("Public key ok")

msg = 0x8c7632afe967e2e16ae7f39dc32c252b3d751fa6e01daa0efc3c174e230f4617
msg = msg.to_bytes(32,'big')

sig = 0x304402203a329589dbc6f3bb88bf90b45b5d4935a18e13e2cb8fcee0b94b3102ec19645702202f61af55df0e56e71d40a9f5f111faeb2f831c1fd314c55227ac44110fb33049
sig = sig.to_bytes(70,'big')

## verify
signer = ECDSA()

while True:
    sig = signer.sign(msg,pv_key)
    signer.verify(msg,sig,pu_key)

assert(signer.verify(msg,sig,pu_key))        
Esempio n. 4
0
print('iv = 0x%032x' % iv)
ivbin = unhexlify('%032x' % iv)
counter = Counter.new(128, initial_value=iv)
cryptor = AES.new(keybin, AES.MODE_CTR, counter=counter)
ciphertext = cryptor.encrypt(message)
raw = ivbin + ciphertext
sig = nak.sign(raw)
signed = nakpubbin + unhexlify('%064x' % sig[0]) + unhexlify('%064x' % sig[1]) + raw
payload = base64.b64encode(signed)

r = requests.post(_server + _onion + client_P.compress(), data=payload)
assert r.status_code == 200
d_bd = base64.b64decode(r.text)
sig = (int(hexlify(d_bd[0:32]),16), int(hexlify(d_bd[32:64]),16))
print('sig = ' + str(sig))
assert ecdsa.verify(server_R, sig, d_bd[64:])
d_ecdh = server_R * client_r
d_keybin = hashlib.sha256(d_ecdh.compress().encode('UTF-8')).digest()
print('ecdh key hex = ' + str(hexlify(d_keybin)))
d_ivcount = int(hexlify(d_bd[64:80]),16)
print('iv hex = ' + str(hexlify(d_bd[64:80])))
d_counter = Counter.new(128,initial_value=d_ivcount)
d_cryptor = AES.new(d_keybin, AES.MODE_CTR, counter=d_counter)
d_plaintext = d_cryptor.decrypt(d_bd[80:])
d_plaintext = d_plaintext.decode('UTF-8')
print("plaintext = " + d_plaintext)

r = requests.get(_server2 + _status)
assert r.status_code == 200
rd = r.json()
Esempio n. 5
0
# You can keep this part (i.e., curve setting and key generation)
curve = Curve.get_curve('secp256k1')
n = curve.order
P = curve.generator
sA = random.randint(0, n)
sk = ECPrivateKey(sA, curve)
QA = sA * P
pk = ECPublicKey(QA)

# You need to change sign and verify methods below
signer = ECDSA()  # this line can be removed
message = b'Anything goes here'
sig = signer.sign(message, sk)  # new sign method here

verifier = ECDSA()  # this line can be removed

message = b'Anything goes here'
try:
    assert (verifier.verify(message, sig, pk))  # new sign method here
    print("Signature verifies")
except:
    print("Signature does not verify")

message = b'Anything goes heree'
try:
    assert (verifier.verify(message, sig, pk))  # new sign method here
    print("Signature verifies")
except:
    print("Signature does not verify")
Esempio n. 6
0
ivbin = unhexlify('%032x' % iv)
counter = Counter.new(128, initial_value=iv)
cryptor = AES.new(keybin, AES.MODE_CTR, counter=counter)
ciphertext = cryptor.encrypt(message)
raw = ivbin + ciphertext
sig = nak.sign(raw)
signed = nakpubbin + unhexlify('%064x' % sig[0]) + unhexlify(
    '%064x' % sig[1]) + raw
payload = base64.b64encode(signed)

r = requests.post(_server + _onion + client_P.compress(), data=payload)
assert r.status_code == 200
d_bd = base64.b64decode(r.text)
sig = (int(hexlify(d_bd[0:32]), 16), int(hexlify(d_bd[32:64]), 16))
print('sig = ' + str(sig))
assert ecdsa.verify(server_R, sig, d_bd[64:])
d_ecdh = server_R * client_r
d_keybin = hashlib.sha256(d_ecdh.compress().encode('UTF-8')).digest()
print('ecdh key hex = ' + str(hexlify(d_keybin)))
d_ivcount = int(hexlify(d_bd[64:80]), 16)
print('iv hex = ' + str(hexlify(d_bd[64:80])))
d_counter = Counter.new(128, initial_value=d_ivcount)
d_cryptor = AES.new(d_keybin, AES.MODE_CTR, counter=d_counter)
d_plaintext = d_cryptor.decrypt(d_bd[80:])
d_plaintext = d_plaintext.decode('UTF-8')
print("plaintext = " + d_plaintext)

r = requests.get(_server2 + _status)
assert r.status_code == 200
rd = r.json()
Esempio n. 7
0
f.write("Public key - y: " + str(QA.y)+"\n")
f.write("Signature - r: " + str(r)+"\n")
f.write("Signature - s: " + str(s)+"\n")
f.close()

f = open("deneme.txt", "r")
x1 = int(f.readline()[16:-1])
y1 = int(f.readline()[16:-1])
r1 = int(f.readline()[15:-1])
s1 = int(f.readline()[15:-1])
f.close()

verifier = ECDSA()
pk1 = ECPublicKey(Point(x1, y1, curve))
sig1 = encode_sig(r1, s1)

message = b'Anything goes here'
try:
    assert(verifier.verify(message,sig1, pk1))
    print("Signature verifies")
except:
    print("Signature does not verify")
    
message = b'Anything goes heree'
try:
    assert(verifier.verify(message,sig1, pk1))
    print("Signature verifies")
except:
    print("Signature does not verify")
    
def P2PKH(private_key, tran, txin, txout):
    """
    :param tran: <Transaction> object
    :param txin: <TxIn> object
    :param txout: <TxOut> object
    :return: <Bool> True or False
    """
    stack = []

    # get signature and add it to stack
    signature = tran.generate_signature(private_key)
    stack.append(signature)  # stack[0]

    # get public key and add it to stack
    public_key = txin.public_key
    stack.append(public_key)  # stack[1]

    # copy the public key and add the copy to stack
    public_key_copy = copy.deepcopy(str(public_key))
    stack.append(public_key_copy)  # stack[2]

    # apply hash function to copy of public key
    hash_public_key_copy = sha256(public_key_copy.encode('utf-8')).hexdigest()
    stack[2] = hash_public_key_copy  # stack[2]

    # get address of recipient and add it to stack
    hash_public_key = txout.address
    stack.append(hash_public_key)  # stack[3]

    print('\n################# stack 1 #####################')
    pprint(stack)

    # check if address matches the hash value of public key
    if stack[2] == stack[3]:
        stack.pop(3)
        stack.pop(2)
        print('\naddress match')
    else:
        print('\naddress does not match')
        return False

    print('\n################# stack 2 #####################')
    pprint(stack)

    # get whole transaction messages except the signature
    tx_in_str = txin.get_tx_in_content()
    tx_out_str = txout.get_tx_out_content()
    tran_id = tran.get_transaction_id()
    message = tx_in_str + tx_out_str + tran_id

    # Instantiate a signer
    signer = ECDSA()

    # check the integrity of message, i.e. M = S{PU} = {{M}PK}PU = M
    valid = signer.verify(str(message).encode('utf-8'), stack[0], stack[1])
    if valid:
        stack.pop(1)
        stack.pop(0)
        print('\nsignature is valid')
    else:
        print('\nsignature is not valid')
        return False

    print('\n################# stack 3 #####################')
    pprint(stack)

    # if the stack is empty, then the transaction is said to be verified
    if not stack:
        print('\nTransaction verified')
        return True
    else:
        print('\nTransaction not verified')
        return False
Esempio n. 9
0
                key = hashlib.sha256(ecdhkey.compress()).digest()
                cryptor = AES.new(key, AES.MODE_CTR, counter = counter)
                ciphertext = ivbin + cryptor.encrypt(msg)
                b64cipher = base64.b64encode(ciphertext)
                send['b64cipher'] = b64cipher
                sig = ecdsa.sign(d1['privkey'], ciphertext, ad)
                send['sig'] = sig
                print(send)
                print('')
                print('')
                recv = send
                recdhkey = d1['pubkey'] * d2['privkey']
                assert recdhkey == ecdhkey
                rciphertext = base64.b64decode(recv['b64cipher'])
                assert rciphertext == ciphertext
                rve = recdsa.verify(d1['pubkey'], recv['sig'], rciphertext, recv['ad'])
                assert rve == True
                rbs = AES.block_size
                assert rbs == bs
                rivbin = rciphertext[:rbs]
                assert rivbin == ivbin
                riv = int(binascii.hexlify(rivbin),16)
                rcounter = Counter.new(AES.block_size * 8, initial_value=riv)
                rkey = hashlib.sha256(recdhkey.compress()).digest()
                assert rkey == key
                rcryptor = AES.new(rkey, AES.MODE_CTR, counter=rcounter)
                plaintext = rcryptor.decrypt(rciphertext[rbs:])
                assert plaintext == msg.encode()