Ejemplo n.º 1
0
    def func(s: sock.socket.socket):
        send_user(s, own_pub)
        # Receive server public key.
        while alive:
            data = s.recv(1024)
            if data:  # ??!
                remote_user = name.User.from_bytes(data)
                print('The server identifies as', remote_user)
                break

        handle_input((s,), own_priv, (remote_user.pub,))

        # Accept text messages.
        q = Queue(maxsize=1)
        while alive:
            data = s.recv(1024)  # TODO: handle longer packets
            if data:
                packet = pack.Packet.from_bytes(data)
                text = crypto.decrypt(packet.encrypted, own_priv)
                crypto.verify(text, packet.signature, remote_user.pub)
                assert(q.empty())
                q.put(text)
                #print(text)
            time.sleep(0.1)

            # TODO: mirror bot logic into serve()
            bot_threads = spawn_bots(q)
            assert(q.full())
            q.get()  # drop()

        while False:
             insult = bot.curse()
             send(insult, s, own_priv, remote_pub)
             time.sleep(bot.random.randint(1,8))
Ejemplo n.º 2
0
    def _validate_block(self, block):
        miner_id = block["header"]["miner_id"]
        miner_public_key = self.get_block(0)["content"]["miners"][str(
            miner_id)]["public_key"].encode('ascii')

        crypto.verify(block["header"]["signature"],
                      json.dumps(block["content"], sort_keys=True),
                      crypto.load_public_key(miner_public_key))
Ejemplo n.º 3
0
    def process_command(self, input_data: bytes) -> str:
        args = input_data.decode().split(' ')  # split signature
        command = args[0]

        complete_command = input_data.decode()

        banned_words = ["select", "from", "union"]

        for word in banned_words:
            if word.lower() in complete_command.lower():
                return 'Nice try'

        if command == 'receive':
            #checking signature
            if len(args) != 5:
                return "Entered line must have format \"receive category data tick signature\""
            signature = args[-1]
            args = args[1:-1]
            checker_key = RSA.importKey(open('checker.pubkey', 'r').read())
            if not verify(' '.join(args), signature, checker_key):
                return "invalid signature"
            return self.receive(*args)
        elif command == 'send':
            try:
                tick = int(args[1])
            except ValueError:
                print('First argument must be integer')
            return self.send(args[1])
        elif command == 'send_pubkey':
            return self.key.publickey().export_key().decode()
        else:
            return 'Unknown command'
Ejemplo n.º 4
0
def new_transaction():
    if request.method == 'POST':
        tx_data = request.get_json()

        forwarder = tx_data['forwarder']
        receiver = tx_data['receiver']
        amount = tx_data['amount']
        publickey = tx_data['publickey']
        signature = tx_data['signature']
        hashed = tx_data['hash']

        transaction = blockchain.Transaction(forwarder, receiver, amount, publickey)
        print("Checking: " + str(transaction.overview()))
        if not has_transaction(transaction):
            # two step verification
            # transaction comes from publickey owner
            condition = crypto.verify(publickey, str(transaction), signature)
            print ('tx condition: ' + str(condition))
            # value can be spend
            # TODO get_balance(fingerprint)

            if condition:
                advertise_transaction(transaction)
                add_transaction(transaction)
                if not transaction_thread.is_alive():
                        transaction_thread = threading.Thread(name='transaction', target=process_transaction)
                    transaction_thread.start()
                return 'Transaction registered'
            else:
                return 'Verification fail, requester is a teapot', 418
        else:
            return 'Transaction already registered'
Ejemplo n.º 5
0
 def verify(self):
     if self.signed_by_id != self.id:
         return False
     key = self.get_public_key()
     try:
         return crypto.verify(self._hashable_representation(), crypto.decode_base64(self.signature), key)
     except:
         return False
Ejemplo n.º 6
0
    def validate_vote(self, vote):
        genesis_block = self.blockchain.get_block(0)

        # check proof
        proofs = genesis_block["content"]["electronic_ballot_proofs"]

        if not vote["header"]["hash_of_proof"] in proofs:
            raise Exception("Invalid proof")

        # check VCM
        vcm_id = vote["header"]["vcm_id"]
        vcm_public_key = genesis_block["content"]["vcms"][vcm_id][
            "public_key"].encode('ascii')

        crypto.verify(vote["header"]["signature"],
                      json.dumps(vote["content"], sort_keys=True),
                      crypto.load_public_key(vcm_public_key))
Ejemplo n.º 7
0
def test_sign():
    for _ in range(5):
        privkey = RSA.generate(2048)
        pubkey = privkey.publickey()
        for str_len in range(2, 200):
            message = 'ENO{%s}' % ''.join(
                [random.choice(string.printable[:95]) for _ in range(str_len)])
            signature = sign(message, privkey)
            assert verify(message, signature, pubkey)
Ejemplo n.º 8
0
 def verifyAdd(self, s):
     if self.code == None:
         if crypto.verify(s, self._hash):
             self.code = s
             return self
         else:
             raise ValueError("Verification failed, string '%s' did not match hash %s"%(s, self._hash))
     else:
         raise Exception("Code already loaded into object")
Ejemplo n.º 9
0
 def verifyAdd(self, s):
     if self.code == None:
         if crypto.verify(s, self._hash):
             self.code = s
             return self
         else:
             raise ValueError(
                 "Verification failed, string '%s' did not match hash %s" %
                 (s, self._hash))
     else:
         raise Exception("Code already loaded into object")
 def is_valid(self):
     signature_valid = crypto.verify(self.utxos[0].public_key,
                                     self.signature, self.get_hash())
     spent = 0
     for msg in self.messages:
         spent = spent + msg
     balance = 0
     for utxo in self.utxos:
         balance = balance + utxo.message
     amount_enough = balance == spent
     return signature_valid and amount_enough
Ejemplo n.º 11
0
def new_block():
    global lock
    lock.acquire()
    if request.method == 'POST':
        tx_data = request.get_json()
        transactions.append(tx_data)

        index = tx_data['index']
        timestamp = tx_data['timestamp']
        previous_hash = tx_data['previous_hash']
        hashed = tx_data['hash']
        nonce = tx_data['nonce']
        miner = tx_data['miner']

        forwarder = tx_data['transaction']['forwarder']
        receiver = tx_data['transaction']['receiver']
        amount = tx_data['transaction']['amount']
        publickey = tx_data['transaction']['publickey']
        signature = tx_data['transaction']['signature']
        hashed = tx_data['transaction']['hash']

        transaction = blockchain.Transaction(forwarder, receiver, amount, publickey)
        print(blockchain.verify_proof(transaction, nonce, miner))
        print(crypto.verify(publickey, str(transaction), signature))
        # verify proof of work had place and transaction is from publickey owner
        condition = blockchain.verify_proof(transaction, nonce, miner) and \
                    crypto.verify(publickey, str(transaction), signature)

        if condition:
            advertise_block(block)
            #node.add_transaction(transaction)
            add_block(block)
            lock.release()
            return 'Transaction registered'
        else:
            return 'Verification fail, requester is a teapot', 418
    else:
        lock.release()
Ejemplo n.º 12
0
def validate_transaction(tx):
    """
    Checks a single transaction to make sure its valid by making sure the transaction is a valid signature of the coin's previous owner
    """
    if tx.previous_transaction == None:
        #This is a special case representing transactions created by mint_coin that create the coin
        to_hash = tx.current_owner_pubkey
    else:
        to_hash = combine_hex(tx.previous_transaction.transaction_signature,
                              tx.current_owner_pubkey)

    to_verify = crypto_hash(to_hash)
    return verify(to_verify, tx.transaction_signature,
                  tx.previous_owner_pubkey)
Ejemplo n.º 13
0
        def forever(s):
            # Handshake.
            while True:
                data = s.recv(1024)
                if data:
                    remote_user = name.User.from_bytes(data)
                    remote_sockets.append(s)
                    remote_keys.append(remote_user.pub)
                    ip = sock.Server(0, '').ip
                    us = name.User('a chat server', own_pub, ip, 'wellcome')
                    s.sendall(us.to_bytes())
                    break

            # Accept text messages.
            while True:
                data = s.recv(1024)
                if data:
                    assert(len(data) < 1024)
                    packet = pack.Packet.from_bytes(data)
                    text = crypto.decrypt(packet.encrypted, own_priv)
                    crypto.verify(text, packet.signature, remote_user.pub)
                    print(text)
                time.sleep(0.1)
Ejemplo n.º 14
0
def is_valid_transaction(transaction: Transaction) -> bool:
    sender_state = get_state(transaction.sender)
    if sender_state.nonce >= transaction.nonce:
        print('invalid nonce. Sender nonce:', sender_state.nonce,
              'transactions nonce:', transaction.nonce)
        return False
    if sender_state.balance < transaction.value:
        print('no money')
        return False
    message = transaction.sender + ' ' + transaction.to + ' ' + str(
        transaction.value) + ' ' + str(transaction.nonce)
    if not verify(transaction.sender, message, transaction.signature):
        print('invalid signature')
        return False
    return True
Ejemplo n.º 15
0
    async def process_command(self, input_data: bytes) -> str:
        args = input_data.decode().split(' ')  # split signature
        command = args[0]

        complete_command = input_data.decode()

        banned_words = ["select", "from", "union"]

        for word in banned_words:
            if word.lower() in complete_command.lower():
                return 'Nice try'

        if command == 'receive':
            #checking signature
            if len(args) != 5:
                self.tx.write(
                    b"Entered line must have format \"receive category data tick signature\"\n"
                )
                return

            signature = args[-1]
            args = args[1:-1]
            if not verify(' '.join(args), signature, CHECKER_KEY):
                self.tx.write(b"invalid signature\n")
                return

            await self.receive(*args)

        elif command == 'send':
            try:
                tick = int(args[1])
            except ValueError:
                self.tx.write(b'First argument must be integer\n')
            await self.send(args[1])

        elif command == 'send_pubkey':
            self.tx.write(PUBLIC_KEY + b'\n')
        else:
            self.tx.write(b'Unknown command\n')
Ejemplo n.º 16
0
 def verify(self):
     # if nobody signed it, verification fails
     if not self.signed_by_id:
         return False
     # if it's not a trusted device...
     if not self.signed_by.get_metadata().is_trusted:
         # but it's a model class that requires trusted signatures, verification fails
         if self.requires_trusted_signature:
             return False
         if settings.CENTRAL_SERVER:
             # if it's not in a zone at all (or its DeviceZone was revoked), verification fails
             if not self.signed_by.get_zone():
                 return False
         else:
             # or if it's not in the same zone as our device (or the DeviceZone was revoked), verification fails
             if self.signed_by.get_zone() != Device.get_own_device().get_zone():
                 return False
     # by this point, we know that we're ok with accepting this model from the device that it says signed it
     # now, we just need to check whether or not it is actually signed by that model's private key
     key = self.signed_by.get_public_key()
     try:
         return crypto.verify(self._hashable_representation(), crypto.decode_base64(self.signature), key)
     except:
         return False
Ejemplo n.º 17
0
        if text is None or text == '':
            return None, None
#        if not text.startswith('MIME-Version: 1.0'):
#            raise Ssm2Exception('Not a valid message.')
        
        # encrypted - this could be nicer
        if 'application/pkcs7-mime' in text or 'application/x-pkcs7-mime' in text:
            try:
                text = crypto.decrypt(text, self._cert, self._key)
            except crypto.CryptoException, e:
                log.error('Failed to decrypt message: %s' % e)
                return None, None
        
        # always signed
        try:
            message, signer = crypto.verify(text, self._capath, self._check_crls)
        except crypto.CryptoException, e:
            log.error('Failed to verify message: %s' % e)
            return None, None
        
        if signer not in self._valid_dns:
            log.error('Message signer not in the valid DNs list: %s' % signer)
            return None, signer
        else:
            log.info('Valid signer: %s' % signer)
            
        return message, signer
        
    def _send_msg(self, message, msgid):
        '''
        Send one message using stomppy.  The message will be signed using 
Ejemplo n.º 18
0
 def verify(self, data, signature):
     return crypto.verify(self._key, data, signature)
Ejemplo n.º 19
0
def verify_image():
    global message_label
    message_label.destroy()

    # retrieve image path using file dialog
    image = filedialog.askopenfilename()

    # load the image using the path
    load_image = Image.open(image)

    # set the image into the gui using the thumbnail function from tkinter
    load_image.thumbnail(image_size, Image.ANTIALIAS)

    # load the image as a numpy array for efficient computation and change the type to unsigned integer
    np_load_image = np.asarray(load_image)
    np_load_image = Image.fromarray(np.uint8(np_load_image))
    render = ImageTk.PhotoImage(np_load_image)
    img = Label(app, image=render)
    img.image = render
    img.pack()

    # used for performance metric
    intime = time.time_ns()

    # get a new reference to the image
    img = cv2.imread(image)

    #### FACIAL DETECTION ####

    # establish initial bounds
    # [x, y, width, height] where x, y is for the top left bounding pixel
    bounds = [0, 0, img.shape[0], img.shape[1]]

    # update our bounds based on the largest face detected
    bounds = facedetect.getFace(image)

    # narrow our facial bounds to:
    # - improve performance during verification
    # - focus our manipulation onto the main facial area
    bounds = [
        bounds[0] + bounds[2] // 4, bounds[1] + bounds[3] // 4, bounds[2] // 2,
        bounds[3] // 2
    ]

    #### STEGANOGRAPHY ####
    # strip the signature from the image by inverting our LSB algorithm

    bin_data = ''  # a string of our binary data, initially empty
    stop_found = False  # true if we have found our stop sequence (5 underscores)

    # loop through each pixel within our facial bounds
    for x in range(bounds[1], bounds[1] + bounds[3]):
        for y in range(bounds[0], bounds[0] + bounds[2]):

            # get red, green, blue LSBs and append to the data string
            r, g, b = helper.to_binary(img[x][y])
            bin_data += r[-1] + g[-1] + b[-1]

    # convert string of bits into array of byte-length strings
    byte_data = [bin_data[i:i + 8] for i in range(0, len(bin_data), 8)]

    # convert byte array to character string
    data_str = ''
    for byte in byte_data:
        data_str += chr(int(byte, 2))

        #check for stop sequence of 5 underscores ('_____') in last 5 characters added
        if data_str[-5:] == '_____':
            # remove the stop sequence from the data
            data_str = data_str[:-5]
            stop_found = True
            break

    # check if we ever found the stop sequence
    if not stop_found:
        # signature must be invalid since it was never terminated with the stop sequence
        message = 'Failed Authentication...'
        print(f'AUTHENTICATION FAILED\nReason: no stop sequence found')

        # used for performance metrics
        verifytime = (time.time_ns() - intime) // 1000000
        testout(image, img, original_message, verifytime, "fake")

        # display failed authentication message
        message_label = Label(app,
                              text=message,
                              bg='red',
                              font=("arial", 20),
                              wraplength=500)
        message_label.pack()
        return

    print(f'-\nBase64 Signature:\n{data_str}')

    # Decode the base64 signature into its original format, removing the residual " b' " from the beginning and " ' " from the end
    try:
        signature = base64.b64decode(data_str[2:-1])
    except:
        # part of our base64 string can't be decoded
        message = 'Failed Authentication...'
        print(
            f'AUTHENTICATION FAILED\nReason: invalid characters found in signature'
        )

        # used for performance metrics
        verifytime = (time.time_ns() - intime) // 1000000
        testout(image, img, original_message, verifytime, "fake")

        #display failed authentication message
        message_label = Label(app,
                              text=message,
                              bg='red',
                              font=("arial", 20),
                              wraplength=500)
        message_label.pack()
        return

    print(f'-\nDecoded Signature:\n{signature}\n-')

    # Attempt to authenticate the image by verifying the signature is valid
    try:
        print('Verifying image...')
        message = crypto.verify(signature, original_message)
        print(f'AUTHENTICATION SUCCESSFUL!')

        verifytime = (time.time_ns() - intime) // 1000000
        testout(image, img, original_message, verifytime, "real")

        message_label = Label(app,
                              text='Authentication Succesful!',
                              bg='light green',
                              font=("arial", 20),
                              wraplength=500)
    except crypto.cryptography.exceptions.InvalidSignature:
        message = 'AUTHENTICATION FAILED'
        print(f'{message}\nReason: signature did not match expected result')

        verifytime = (time.time_ns() - intime) // 1000000
        testout(image, img, original_message, verifytime, "fake")

        message_label = Label(app,
                              text=message,
                              bg='red',
                              font=("arial", 20),
                              wraplength=500)
    message_label.pack()
Ejemplo n.º 20
0
from note import Note # à coder
from crypto import sign, verify # à coder
import requests

# pour l'exemple
URL_SERVER = 'http://localhost' 
MY_PRIVATE_KEY = 'XXXX'

# get data for payment # à coder
merchant_key = 'YYYY'
data = {'montant': 1, 'cle': merchant_key}

# send a request to the server and get back the note
r = requests.get(url, data = data)
response_from_server = r.content() # ou r.json() ?
note = Note(response_from_server) # il faudra surement reformater response

# verify note signature
if not verify(note, note.transactions[-1]['signature']):
    raise SignatureError # à coder

# create new transaction and sign
new_transaction = {'cle': merchant_key, 'hash_info_payment': None, 'signature': None}
note.transactions.append(new_transaction)
my_sig = sign(note, MY_PRIVATE_KEY)
note.transactions[-1]['signature'] = my_sig

# send to merchant
note.display_QR_code() # une manière de faire parmi d'autres
Ejemplo n.º 21
0
def verify_signature(signed_binary_data, pubkey_data):
    (sig_len, ) = struct.unpack("<I", signed_binary_data[-4:])
    sig_start = len(signed_binary_data) - 4 - sig_len
    signature = signed_binary_data[sig_start:-4]
    binary = signed_binary_data[0:sig_start]
    return crypto.verify(binary, signature, pubkey_data, False)
Ejemplo n.º 22
0
 def valid_signature(self):
     if self.owner == "mined":
         return True
     return crypto.verify(self.comp(), self.owner, self.signature)
Ejemplo n.º 23
0
 def verify_signature(self):
     """Verify that the incoming request includes a valid signature."""
     if not crypto.verify(
         self.xsrf_key, self.user.user_id(), self.request.get('signature')):
         raise ErrorMessage(400, 'Invalid signature.')
Ejemplo n.º 24
0
 def _verify_genesis_block(self):
     crypto.verify(self.genesis_block["header"]["signature"], json.dumps(self.genesis_block["content"], sort_keys=True), self.election_public_key)
Ejemplo n.º 25
0
 def _verify_signature(self, device, signature):
     return crypto.verify(self._hashable_representation(), crypto.decode_base64(signature), device.get_public_key())