示例#1
0
def elli(key_size_bytes):
    # Generate the key pair for Alice
    a_private = urandom(key_size_bytes)
    a_public = scalarmult_base(a_private)

    # Generate the key pair for Bob
    b_private = urandom(key_size_bytes)
    b_public = scalarmult_base(b_private)

    a_shared = scalarmult(a_private, b_public)
    b_shared = scalarmult(b_private, a_public)

    assert a_shared == b_shared
示例#2
0
def test_dh():
    a_priv = unhexlify(
        '77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a')
    a_pub = unhexlify(
        '8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a')
    b_priv = unhexlify(
        '5dab087e624a8a4b79e17f8b83800ee66f3bb1292618b6fd1c2f8b27ff88e0eb')
    b_pub = unhexlify(
        'de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f')
    k = '4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742'

    assert hexlify(scalarmult_base(a_priv)) == hexlify(a_pub)
    assert hexlify(scalarmult_base(b_priv)) == hexlify(b_pub)
    assert hexlify(scalarmult(a_priv, b_pub)) == k
    assert hexlify(scalarmult(b_priv, a_pub)) == k
示例#3
0
        def run(self):
            HOST = ''
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            s.bind((HOST,self.port))
            s.listen(1)
            self.conn, self.addr = s.accept()

            # Curve25519 encryption scheme
            # Usign a size-32 key
            a = urandom(32)
            a_pub = scalarmult_base(a)

            # send public key
            print(binascii.hexlify(a_pub))
            self.conn.send(a_pub)

            b_pub = self.conn.recv(32)
            secret = scalarmult(a, b_pub)

            print("Private Key A: " +binascii.hexlify(a))
            print("Public Key A: " +binascii.hexlify(a_pub))
            print("Public Key B: " +binascii.hexlify(b_pub))
            print("Shared key: " + binascii.hexlify(secret))


            # Select loop for listen
            while self.running == True:
示例#4
0
        def run(self):              
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.sock.settimeout(5.0)
            try:
                self.sock.connect((self.host, self.port))
            except socket.timeout:
                print("Timeout, host inacessivel")
                connecter.config(state=NORMAL)
                raise SystemExit(0)

            print("Conectado ao peer:"+ self.host +
                    " on port: " + str(self.port))

            # Curve25519 encryption scheme
            # Usign a size-32 key
            a = urandom(32)
            a_pub = scalarmult_base(a)

            # send public key
            self.sock.send(a_pub)

            b_pub = self.sock.recv(32)

            secret = scalarmult(a, b_pub)

            print("Private Key A: " +binascii.hexlify(a))
            print("Public Key A: " +binascii.hexlify(a_pub))
            print("Public Key B: " +binascii.hexlify(b_pub))
            print("Shared key: " + binascii.hexlify(secret))
            
            # Select loop for listen
            while self.running == True:
示例#5
0
        def run(self):              
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.sock.settimeout(5.0)
            try:
                self.sock.connect((self.host, self.port))
            except socket.timeout:
                print("Timeout, host inacessivel")
                connecter.config(state=NORMAL)
                raise SystemExit(0)

            print("Conectado ao peer:"+ self.host +
                    " on port: " + str(self.port))

            t0 = time.clock()

            # Curve25519 encryption scheme
            # Usign a size-32 key
            a = urandom(32)
            a_pub = scalarmult_base(a)

            # send public key
            self.sock.send(a_pub)


            context = str(my_ip) + str(peer_ip) + str(i)
            k_collection = k_db['key_collection']
            entry = {"userid":str(my_ip),
                      "context":context,
                      "key": binascii.hexlify(a_pub)}

                k_collection.insert_one(entry)
        def run(self):              
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.sock.settimeout(5.0)
            try:
                self.sock.connect((self.host, self.port))
            except socket.timeout:
                print("Timeout, host inacessivel")
                connecter.config(state=NORMAL)
                raise SystemExit(0)

            print("Conectado ao peer:"+ self.host +
                    " on port: " + str(self.port))

            t0 = time.clock()

            # Curve25519 encryption scheme
            # Usign a size-32 key
            a = urandom(32)
            a_pub = scalarmult_base(a)

            # send public key
            self.sock.send(a_pub)


            context = str(my_ip) + str(peer_ip) + str(i)

            des.create('stream', contexto,True)
            des.publish(contexto, {"userid":str(my_ip),
                                   "context":context,
                                   "key": binascii.hexlify(a_pub)})

            time.seep(tau - (time.clock() - t0))

            secret = scalarmult(a, b_pub)

            count = 0
            entries = api.liststreams()
            for entry in entries:
                count += 1
                entry = entry['details']
                if str(entry["context"]) == context and \
                str(entry["userid"]) == str(peer_ip):
                    b_pub = binascii.unhexlify(entry["key"])
                    found = True
            if (count > 2):
                for entry in k_collection.find({"context":context}):
                    print(entry)
                print("poisoned block, disconnect")
                sys.exit()


            print("Private Key A: " +binascii.hexlify(a))
            print("Public Key A: " +binascii.hexlify(a_pub))
            print("Public Key B: " +binascii.hexlify(b_pub))
            print("Shared key: " + binascii.hexlify(secret))
            
            # Select loop for listen
            while self.running == True:
示例#7
0
    async def create_relationship(self, bulletin_secret, username, to):
        config = self.config
        mongo = self.config.mongo

        if not bulletin_secret:
            return 'error: "bulletin_secret" missing', 400

        if not username:
            return 'error: "username" missing', 400

        if not to:
            return 'error: "to" missing', 400
        rid = TU.generate_rid(config, bulletin_secret)
        dup = mongo.db.blocks.find({'transactions.rid': rid})
        if dup.count():
            found_a = False
            found_b = False
            for txn in dup:
                if txn['public_key'] == config.public_key:
                    found_a = True
                if txn['public_key'] != config.public_key:
                    found_b = True
            if found_a and found_b:
                return json.dumps({
                    "success": False,
                    "status": "Already added"
                })

        miner_transactions = mongo.db.miner_transactions.find()
        mtxn_ids = []
        for mtxn in miner_transactions:
            for mtxninput in mtxn['inputs']:
                mtxn_ids.append(mtxninput['id'])

        checked_out_txn_ids = mongo.db.checked_out_txn_ids.find()
        for mtxn in checked_out_txn_ids:
            mtxn_ids.append(mtxn['id'])

        a = os.urandom(32).decode('latin1')
        dh_public_key = scalarmult_base(a).encode('latin1').hex()
        dh_private_key = a.encode('latin1').hex()

        transaction = await Transaction.generate(
            bulletin_secret=bulletin_secret,
            username=username,
            fee=0.00,
            public_key=config.public_key,
            dh_public_key=dh_public_key,
            private_key=config.private_key,
            dh_private_key=dh_private_key,
            outputs=[{
                'to': to,
                'value': 0
            }])
        return transaction
        def run(self):
            HOST = ''
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            s.bind((HOST,self.port))
            s.listen(1)
            self.conn, self.addr = s.accept()

            t0 = time.clock()

            # Curve25519 encryption scheme
            # Usign a size-32 key
            a = urandom(32)
            a_pub = scalarmult_base(a)

            # send public key
            print(binascii.hexlify(a_pub))
            self.conn.send(a_pub)

            b_pub = self.conn.recv(32)

            time.seep(tau - (time.clock() - t0))

            secret = scalarmult(a, b_pub)

            count = 0
            entries = api.liststreams()
            for entry in entries:
                count += 1
                entry = entry['details']
                if str(entry["context"]) == context and \
                str(entry["userid"]) == str(peer_ip):
                    b_pub = binascii.unhexlify(entry["key"])
                    found = True
            if (count > 2):
                for entry in k_collection.find({"context":context}):
                    print(entry)
                print("poisoned block, disconnect")
                sys.exit()

            print("Private Key A: " +binascii.hexlify(a))
            print("Public Key A: " +binascii.hexlify(a_pub))
            print("Public Key B: " +binascii.hexlify(b_pub))
            print("Shared key: " + binascii.hexlify(secret))


            # Select loop for listen
            while self.running == True:
示例#9
0
 def add_user(self, data):
     user = User.from_dict(data)
     a = os.urandom(32).decode('latin1')
     dh_public_key = scalarmult_base(a).encode('latin1').hex()
     dh_private_key = a.encode('latin1').hex()
     relationship = user.their_dict
     relationship.update(self.service.my_dict)
     relationship['dh_private_key'] = dh_private_key
     encrypted_relationship = self.service.encrypt_relationship(
         json.dumps(relationship)
     )
     extra_data = {
         'relationship': encrypted_relationship,
         'dh_public_key': dh_public_key
     }
     data.update(extra_data)
     return self.service.api_call(
         '/add-user',
         data
     )
示例#10
0
    def dispatch_request(self):
        config = app.config['yada_config']
        mongo = app.config['yada_mongo']
        if request.method == 'GET':
            bulletin_secret = request.args.get('bulletin_secret', '')
            username = request.args.get('username', '')
            to = request.args.get('to', '')
        else:
            bulletin_secret = request.json.get('bulletin_secret', '')
            username = request.json.get('username', '')
            to = request.json.get('to', '')

        if not bulletin_secret:
            return 'error: "bulletin_secret" missing', 400

        if not username:
            return 'error: "username" missing', 400

        if not to:
            return 'error: "to" missing', 400
        rid = TU.generate_rid(config, bulletin_secret)
        dup = mongo.db.blocks.find({'transactions.rid': rid})
        if dup.count():
            for txn in dup:
                if txn['public_key'] == config.public_key:
                    return json.dumps({
                        "success": False,
                        "status": "Already added"
                    })

        miner_transactions = mongo.db.miner_transactions.find()
        mtxn_ids = []
        for mtxn in miner_transactions:
            for mtxninput in mtxn['inputs']:
                mtxn_ids.append(mtxninput['id'])

        checked_out_txn_ids = mongo.db.checked_out_txn_ids.find()
        for mtxn in checked_out_txn_ids:
            mtxn_ids.append(mtxn['id'])

        a = os.urandom(32)
        dh_public_key = scalarmult_base(a).encode('hex')
        dh_private_key = a.encode('hex')

        transaction = TransactionFactory(config=config,
                                         mongo=mongo,
                                         block_height=BU.get_latest_block(
                                             config, mongo)['index'],
                                         bulletin_secret=bulletin_secret,
                                         username=username,
                                         fee=0.00,
                                         public_key=config.public_key,
                                         dh_public_key=dh_public_key,
                                         private_key=config.private_key,
                                         dh_private_key=dh_private_key,
                                         outputs=[{
                                             'to': to,
                                             'value': 0
                                         }])

        TU.save(config, mongo, transaction.transaction)

        mongo.db.miner_transactions.insert(transaction.transaction.to_dict())
        job = Process(target=TxnBroadcaster.txn_broadcast_job,
                      args=(transaction.transaction, ))
        job.start()

        my_bulletin_secret = config.bulletin_secret
        bulletin_secrets = sorted(
            [str(my_bulletin_secret),
             str(bulletin_secret)], key=str.lower)
        rid = hashlib.sha256(
            str(bulletin_secrets[0]) +
            str(bulletin_secrets[1])).digest().encode('hex')
        mongo.site_db.friends.insert({
            'rid': rid,
            'relationship': {
                'bulletin_secret': bulletin_secret
            }
        })
        return json.dumps({"success": True})
示例#11
0
    def dispatch_request(self):
        config = app.config['yada_config']
        mongo = app.config['yada_mongo']
        if request.method == 'GET':
            bulletin_secret = request.args.get('bulletin_secret', '')
            username = request.args.get('username', '')
            to = request.args.get('to', '')
        else:
            bulletin_secret = request.json.get('bulletin_secret', '')
            username = request.json.get('username', '')
            to = request.json.get('to', '')

        if not bulletin_secret:
            return 'error: "bulletin_secret" missing', 400

        if not username:
            return 'error: "username" missing', 400

        if not to:
            return 'error: "to" missing', 400
        rid = TU.generate_rid(config, bulletin_secret)
        dup = mongo.db.blocks.find({'transactions.rid': rid})
        if dup.count():
            found_a = False
            found_b = False
            for txn in dup:
                if txn['public_key'] == config.public_key:
                    found_a = True
                if txn['public_key'] != config.public_key:
                    found_b = True
            if found_a and found_b:
                return json.dumps({"success": False, "status": "Already added"})

        miner_transactions = mongo.db.miner_transactions.find()
        mtxn_ids = []
        for mtxn in miner_transactions:
            for mtxninput in mtxn['inputs']:
                mtxn_ids.append(mtxninput['id'])

        checked_out_txn_ids = mongo.db.checked_out_txn_ids.find()
        for mtxn in checked_out_txn_ids:
            mtxn_ids.append(mtxn['id'])

        a = os.urandom(32).decode('latin1')
        dh_public_key = scalarmult_base(a).encode('latin1').hex()
        dh_private_key = a.encode('latin1').hex()

        transaction = TransactionFactory(
            block_height=BU().get_latest_block()['index'],
            bulletin_secret=bulletin_secret,
            username=username,
            fee=0.00,
            public_key=config.public_key,
            dh_public_key=dh_public_key,
            private_key=config.private_key,
            dh_private_key=dh_private_key,
            outputs=[
                {
                    'to': to,
                    'value': 0
                }
            ]
        )

        mongo.db.miner_transactions.insert(transaction.transaction.to_dict())
        job = Process(target=TxnBroadcaster.txn_broadcast_job, args=(transaction.transaction,))
        job.start()

        return json.dumps({"success": True})
        salt=salt,
        iterations=100000,
        backend=default_backend()
    )
    derived_key = base64.urlsafe_b64encode(kdf.derive(shared_master_key))

    f = Fernet(derived_key)
    # Dependent on the mode, either encrypt or decrypt
    if is_encryption_mode:
        return f.encrypt(message.encode())
    else:
        return f.decrypt(message).decode()

# Generate the key pair for the reader
r_private = urandom(32)
r_public = scalarmult_base(r_private)

# Generate the key pair for the tag
t_private = urandom(32)
t_public = scalarmult_base(t_private)

# Sign the Public Key of the tag with the Private Key of the reader
certificate_salt = urandom(32)
t_public_hash = hashlib.sha256(t_public).hexdigest()
t_certificate = encrypt(r_private, t_public_hash, certificate_salt)

print "Reader Public Key: ",binascii.hexlify(r_public)
print "Reader Private Key:",binascii.hexlify(r_private)
print

print "Tag Public Key:    ",binascii.hexlify(t_public)
示例#13
0
 def get_public(self):
     return scalarmult_base(self.secret)
示例#14
0
    async def post(self):
        config = self.config
        mongo = self.config.mongo
        kwargs = json.loads(self.request.body.decode('utf-8'))
        bulletin_secret = kwargs.get('bulletin_secret', '')
        username = kwargs.get('username', '')
        to = kwargs.get('to', '')

        if not bulletin_secret:
            return 'error: "bulletin_secret" missing', 400

        if not username:
            return 'error: "username" missing', 400

        if not to:
            return 'error: "to" missing', 400
        rid = TU.generate_rid(config, bulletin_secret)
        dup = mongo.db.blocks.find({'transactions.rid': rid})
        if dup.count():
            found_a = False
            found_b = False
            for txn in dup:
                if txn['public_key'] == config.public_key:
                    found_a = True
                if txn['public_key'] != config.public_key:
                    found_b = True
            if found_a and found_b:
                return json.dumps({
                    "success": False,
                    "status": "Already added"
                })

        miner_transactions = mongo.db.miner_transactions.find()
        mtxn_ids = []
        for mtxn in miner_transactions:
            for mtxninput in mtxn['inputs']:
                mtxn_ids.append(mtxninput['id'])

        checked_out_txn_ids = mongo.db.checked_out_txn_ids.find()
        for mtxn in checked_out_txn_ids:
            mtxn_ids.append(mtxn['id'])

        a = os.urandom(32).decode('latin1')
        dh_public_key = scalarmult_base(a).encode('latin1').hex()
        dh_private_key = a.encode('latin1').hex()

        transaction = TransactionFactory(
            block_height=BU().get_latest_block()['index'],
            bulletin_secret=bulletin_secret,
            username=username,
            fee=0.00,
            public_key=config.public_key,
            dh_public_key=dh_public_key,
            private_key=config.private_key,
            dh_private_key=dh_private_key,
            outputs=[{
                'to': to,
                'value': 0
            }])

        mongo.db.miner_transactions.insert(transaction.transaction.to_dict())
        """
        # TODO: integrate new socket/peer framework for transmitting txns

        job = Process(target=TxnBroadcaster.txn_broadcast_job, args=(transaction.transaction,))
        job.start()
        """

        self.render_as_json({"success": True})
示例#15
0
# implementation is a translation of the pseudocode
# specified in RFC7748: https://tools.ietf.org/html/rfc7748
# 
# libraries required for implementation
from os import urandom
from eccsnacks.curve25519 import scalarmult, scalarmult_base
import binascii

# (l) is a random selected point for Reader RFID
l = urandom(32)
a = scalarmult_base(l)

# (e) is a random seclected point for RFID tag
e = urandom(32)
b = scalarmult_base(e)

# reference points defined by the scalar multiplication from the elliptic curve
c = scalarmult(e, a)
d = scalarmult(l, b)

# Reader RFID and RFID tag private key values
print "RFID private key: ",binascii.hexlify(e)
print "Reader private key: ",binascii.hexlify(l)

# printing value of A and B in function of (a) and (b) with the Binary ASCII 
print "A value: ",binascii.hexlify(a)
print "B value: ",binascii.hexlify(b)

# printing value of A and B in function of (c) and (d) with the Binary ASCII
print "C value: ",binascii.hexlify(c)
print "D value: ",binascii.hexlify(d)
示例#16
0
def test_invalid_scalar():
    with pytest.raises(ValueError):
        scalarmult_base('\xff' * 64)
示例#17
0
from os import urandom
from eccsnacks.curve25519 import scalarmult, scalarmult_base
import binascii

lamb = urandom(32)
a = scalarmult_base(lamb)

eps = urandom(32)
b = scalarmult_base(eps)

c = scalarmult(eps, a)

d = scalarmult(lamb, b)

print("RFID private key: ", binascii.hexlify(eps))

print("Reader private key: ", binascii.hexlify(lamb))

print("A value: ", binascii.hexlify(a))
print("B value: ", binascii.hexlify(b))

print("C value: ", binascii.hexlify(c))
print("D value: ", binascii.hexlify(d))
示例#18
0
 def generate_dh(self):
     a = os.urandom(32).decode('latin1')
     dh_public_key = scalarmult_base(a).encode('latin1').hex()
     dh_private_key = a.encode().hex()
     return dh_public_key, dh_private_key
示例#19
0
    async def generate(cls,
                       bulletin_secret='',
                       username='',
                       value=0,
                       fee=0.0,
                       rid='',
                       requester_rid='',
                       requested_rid='',
                       public_key='',
                       dh_public_key='',
                       private_key='',
                       dh_private_key='',
                       to='',
                       inputs='',
                       outputs='',
                       coinbase=False,
                       chattext=None,
                       signin=None,
                       relationship='',
                       no_relationship=False,
                       exact_match=False):
        cls_inst = cls()
        cls_inst.config = get_config()
        cls_inst.mongo = cls_inst.config.mongo
        cls_inst.app_log = getLogger('tornado.application')
        cls_inst.bulletin_secret = bulletin_secret
        cls_inst.username = username
        cls_inst.rid = rid
        cls_inst.requester_rid = requester_rid
        cls_inst.requested_rid = requested_rid
        cls_inst.public_key = public_key
        cls_inst.dh_public_key = dh_public_key
        cls_inst.private_key = private_key
        cls_inst.value = value
        cls_inst.fee = float(fee)
        cls_inst.dh_private_key = dh_private_key
        cls_inst.to = to
        cls_inst.time = str(int(time.time()))
        cls_inst.outputs = []
        cls_inst.relationship = relationship
        cls_inst.no_relationship = no_relationship
        cls_inst.exact_match = exact_match
        for x in outputs:
            cls_inst.outputs.append(Output.from_dict(x))
        cls_inst.inputs = []
        for x in inputs:
            if 'signature' in x and 'public_key' in x and 'address' in x:
                cls_inst.inputs.append(ExternalInput.from_dict(x))
            else:
                cls_inst.inputs.append(Input.from_dict(x))
        cls_inst.coinbase = coinbase
        cls_inst.chattext = chattext
        cls_inst.signin = signin
        await cls_inst.do_money()

        inputs_concat = ''.join([
            x.id for x in sorted(cls_inst.inputs, key=lambda x: x.id.lower())
        ])
        outputs_concat = cls_inst.get_output_hashes()
        if bulletin_secret or rid:
            if not cls_inst.rid:
                cls_inst.rid = cls_inst.generate_rid()
            if cls_inst.chattext:
                cls_inst.relationship = json.dumps(
                    {"chatText": cls_inst.chattext})
                cls_inst.encrypted_relationship = cls_inst.config.cipher.encrypt(
                    cls_inst.relationship)
            elif cls_inst.signin:
                for shared_secret in cls_inst.config.GU.get_shared_secrets_by_rid(
                        cls_inst.rid):
                    cls_inst.relationship = SignIn(cls_inst.signin)
                    cls_inst.cipher = Crypt(shared_secret.hex(), shared=True)
                    cls_inst.encrypted_relationship = cls_inst.cipher.shared_encrypt(
                        cls_inst.relationship.to_json())
                    break
            elif cls_inst.relationship:
                cls_inst.encrypted_relationship = cls_inst.relationship
            elif cls_inst.no_relationship:
                cls_inst.encrypted_relationship = ''
            else:
                if not cls_inst.dh_public_key or not cls_inst.dh_private_key:
                    a = os.urandom(32).decode('latin1')
                    cls_inst.dh_public_key = scalarmult_base(a).encode(
                        'latin1').hex()
                    cls_inst.dh_private_key = a.encode().hex()
                cls_inst.relationship = cls_inst.generate_relationship()
                if not private_key:
                    raise Exception('missing private key')
                cls_inst.encrypted_relationship = cls_inst.config.cipher.encrypt(
                    cls_inst.relationship.to_json().encode())
        else:
            cls_inst.rid = ''
            cls_inst.encrypted_relationship = ''

        cls_inst.header = (cls_inst.public_key + cls_inst.time +
                           cls_inst.dh_public_key + cls_inst.rid +
                           cls_inst.encrypted_relationship +
                           "{0:.8f}".format(cls_inst.fee) +
                           cls_inst.requester_rid + cls_inst.requested_rid +
                           inputs_concat + outputs_concat)
        cls_inst.hash = hashlib.sha256(
            cls_inst.header.encode('utf-8')).digest().hex()
        if cls_inst.private_key:
            cls_inst.transaction_signature = TU.generate_signature_with_private_key(
                private_key, cls_inst.hash)
        else:
            cls_inst.transaction_signature = ''
        return cls(cls_inst.time,
                   cls_inst.rid,
                   cls_inst.transaction_signature,
                   cls_inst.encrypted_relationship,
                   cls_inst.public_key,
                   cls_inst.dh_public_key,
                   float(cls_inst.fee),
                   cls_inst.requester_rid,
                   cls_inst.requested_rid,
                   cls_inst.hash,
                   inputs=[x.to_dict() for x in cls_inst.inputs],
                   outputs=[x.to_dict() for x in cls_inst.outputs],
                   coinbase=cls_inst.coinbase)
示例#20
0
    def __init__(self,
                 config,
                 mongo,
                 block_height,
                 bulletin_secret='',
                 username='',
                 value=0,
                 fee=0.0,
                 requester_rid='',
                 requested_rid='',
                 public_key='',
                 dh_public_key='',
                 private_key='',
                 dh_private_key='',
                 to='',
                 inputs='',
                 outputs='',
                 coinbase=False,
                 chattext=None,
                 signin=None):
        self.config = config
        self.mongo = mongo
        self.block_height = block_height
        self.bulletin_secret = bulletin_secret
        self.username = username
        self.requester_rid = requester_rid
        self.requested_rid = requested_rid
        self.public_key = public_key
        self.dh_public_key = dh_public_key
        self.private_key = private_key
        self.value = value
        self.fee = float(fee)
        self.dh_private_key = dh_private_key
        self.to = to
        self.time = str(int(time.time()))
        self.outputs = []
        for x in outputs:
            self.outputs.append(Output.from_dict(x))
        self.inputs = []
        for x in inputs:
            if 'signature' in x:
                self.inputs.append(
                    ExternalInput.from_dict(self.config, self.mongo, x))
            else:
                self.inputs.append(Input.from_dict(x))
        self.coinbase = coinbase
        self.chattext = chattext
        self.signin = signin
        self.do_money()
        inputs_concat = self.get_input_hashes()
        outputs_concat = self.get_output_hashes()
        if bulletin_secret:
            self.rid = self.generate_rid()
            if self.chattext:
                self.relationship = json.dumps({"chatText": self.chattext})
                self.cipher = Crypt(self.config.wif)
                self.encrypted_relationship = self.cipher.encrypt(
                    self.relationship)
            elif self.signin:
                for shared_secret in TU.get_shared_secrets_by_rid(
                        self.config, self.mongo, self.rid):
                    self.relationship = SignIn(self.signin)
                    self.cipher = Crypt(shared_secret.encode('hex'),
                                        shared=True)
                    self.encrypted_relationship = self.cipher.shared_encrypt(
                        self.relationship.to_json())
            else:
                if not self.dh_public_key or not self.dh_private_key:
                    a = os.urandom(32)
                    self.dh_public_key = scalarmult_base(a).encode('hex')
                    self.dh_private_key = a.encode('hex')
                self.relationship = self.generate_relationship()
                if not private_key:
                    raise BaseException('missing private key')
                self.cipher = Crypt(self.config.wif)
                self.encrypted_relationship = self.cipher.encrypt(
                    self.relationship.to_json())
        else:
            self.rid = ''
            self.encrypted_relationship = ''

        self.header = (self.public_key + self.time + self.dh_public_key +
                       self.rid + self.encrypted_relationship +
                       "{0:.8f}".format(self.fee) + self.requester_rid +
                       self.requested_rid + inputs_concat + outputs_concat)
        self.hash = hashlib.sha256(self.header).digest().encode('hex')
        if self.private_key:
            self.transaction_signature = TU.generate_signature_with_private_key(
                private_key, self.hash)
        else:
            self.transaction_signature = ''
        self.transaction = self.generate_transaction()
示例#21
0
# dh_25519.py
# Demonstrates generating keypair for Alice & Bob, and lastly
# compute Diffie-Hellman and compare keys.

from os import urandom
from eccsnacks.curve25519 import scalarmult, scalarmult_base

# Private keys in Curve25519 can be any 32-byte string.
a = urandom(32)
a_pub = scalarmult_base(a)

b = urandom(32)
b_pub = scalarmult_base(b)

# perform Diffie-Hellman computation for alice and bob
k_ab = scalarmult(a, b_pub)
k_ba = scalarmult(b, a_pub)

# keys should be the same
assert k_ab == k_ba
示例#22
0
def create_relationship():  # demo site
    if request.method == 'GET':
        bulletin_secret = request.args.get('bulletin_secret', '')
        username = request.args.get('username', '')
        to = request.args.get('to', '')
    else:
        bulletin_secret = request.json.get('bulletin_secret', '')
        username = request.json.get('username', '')
        to = request.json.get('to', '')

    if not bulletin_secret:
        return 'error: "bulletin_secret" missing', 400

    if not username:
        return 'error: "username" missing', 400

    if not to:
        return 'error: "to" missing', 400

    rid = TU.generate_rid(bulletin_secret)
    dup = Mongo.db.blocks.find({'transactions.rid': rid})
    if dup.count():
        for txn in dup:
            if txn['public_key'] == Config.public_key:
                return json.dumps({
                    "success": False,
                    "status": "Already added"
                })
    input_txns = BU.get_wallet_unspent_transactions(Config.address)

    miner_transactions = Mongo.db.miner_transactions.find()
    mtxn_ids = []
    for mtxn in miner_transactions:
        for mtxninput in mtxn['inputs']:
            mtxn_ids.append(mtxninput['id'])

    checked_out_txn_ids = Mongo.db.checked_out_txn_ids.find()
    for mtxn in checked_out_txn_ids:
        mtxn_ids.append(mtxn['id'])

    a = os.urandom(32)
    dh_public_key = scalarmult_base(a).encode('hex')
    dh_private_key = a.encode('hex')

    transaction = TransactionFactory(bulletin_secret=bulletin_secret,
                                     username=username,
                                     fee=0.01,
                                     public_key=Config.public_key,
                                     dh_public_key=dh_public_key,
                                     private_key=Config.private_key,
                                     dh_private_key=dh_private_key,
                                     outputs=[Output(to=to, value=1)])

    TU.save(transaction.transaction)

    Mongo.db.miner_transactions.insert(transaction.transaction.to_dict())
    job = Process(target=endpoints.TxnBroadcaster.txn_broadcast_job,
                  args=(transaction.transaction, ))
    job.start()

    my_bulletin_secret = Config.get_bulletin_secret()
    bulletin_secrets = sorted([str(my_bulletin_secret),
                               str(bulletin_secret)],
                              key=str.lower)
    rid = hashlib.sha256(str(bulletin_secrets[0]) +
                         str(bulletin_secrets[1])).digest().encode('hex')
    Mongo.site_db.friends.insert({
        'rid': rid,
        'relationship': {
            'bulletin_secret': bulletin_secret
        }
    })
    return json.dumps({"success": True})