Example #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
Example #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
Example #3
0
 def get_shared_secrets_by_rid(cls, config, mongo, rid):
     from blockchainutils import BU
     shared_secrets = []
     dh_public_keys = []
     dh_private_keys = []
     txns = BU.get_transactions_by_rid(config,
                                       mongo,
                                       rid,
                                       config.bulletin_secret,
                                       rid=True)
     for txn in txns:
         if str(txn['public_key']) == str(
                 config.public_key
         ) and txn['relationship']['dh_private_key']:
             dh_private_keys.append(txn['relationship']['dh_private_key'])
     txns = BU.get_transactions_by_rid(config,
                                       mongo,
                                       rid,
                                       config.bulletin_secret,
                                       rid=True,
                                       raw=True)
     for txn in txns:
         if str(txn['public_key']) != str(
                 config.public_key) and txn['dh_public_key']:
             dh_public_keys.append(txn['dh_public_key'])
     for dh_public_key in dh_public_keys:
         for dh_private_key in dh_private_keys:
             shared_secrets.append(
                 scalarmult(dh_private_key.decode('hex'),
                            dh_public_key.decode('hex')))
     return shared_secrets
Example #4
0
    def compute(self, public):
        result = scalarmult(self.secret, public)

        if bad_result(result):
            raise ValueError("Error computing Curve25519 shared secret")

        return result
Example #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))

            # 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:
Example #6
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:
Example #7
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))

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

            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()

            secret = scalarmult(a, b_pub)

            # Select loop for listen
            while self.running == True:
Example #8
0
def test_n(n, expected):
    k = unhexlify(
        '0900000000000000000000000000000000000000000000000000000000000000')
    u = k
    for i in xrange(n):
        k, u = scalarmult(k, u), k

    assert hexlify(k) == expected
        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:
Example #10
0
 def get_shared_secrets_by_rid(self, rid):
     shared_secrets = []
     dh_public_keys = []
     dh_private_keys = []
     txns = self.get_transactions_by_rid(rid, self.config.bulletin_secret, rid=True)
     for txn in txns:
         if str(txn['public_key']) == str(self.config.public_key) and txn['relationship']['dh_private_key']:
             dh_private_keys.append(txn['relationship']['dh_private_key'])
     txns = self.get_transactions_by_rid(rid, self.config.bulletin_secret, rid=True, raw=True)
     for txn in txns:
         if str(txn['public_key']) != str(self.config.public_key) and txn['dh_public_key']:
             dh_public_keys.append(txn['dh_public_key'])
     for dh_public_key in dh_public_keys:
         for dh_private_key in dh_private_keys:
             shared_secrets.append(scalarmult(unhexlify(dh_private_key).decode('latin1'), unhexlify(dh_public_key).decode('latin1')).encode('latin1'))
     return shared_secrets
Example #11
0
    class Chat_Client(threading.Thread):
        """Client thread"""

        def __init__(self):
            threading.Thread.__init__(self)
            self.host = None
            self.sock = None
            self.port = None
            self.running = 1
        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)
            self.send_context = True

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

            count = 0
            entries = k_collection.find({"context":context})
            for entry in entries:
                count += 1
                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()


            time.sleep(time.clock() - t0)

            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:
Example #12
0
def test_kat(k, u, expected):
    k = unhexlify(k)
    u = unhexlify(u)
    assert hexlify(scalarmult(k, u)) == expected
Example #13
0
# 
# 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)

# Check that C is equal to D,
Example #14
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))
print "Tag Private Key:   ",binascii.hexlify(t_private)
print "Tag Public Hash:   ",t_public_hash
print "Tag Certificate:   ",t_certificate
print

# Authenticate the tag's public key
expected_t_public_hash = encrypt(r_private, t_certificate, certificate_salt, False)
if t_public_hash == expected_t_public_hash:
    print "Tag authenticated."
    print
else:
    print "Tag is not authentic."
    exit()

# The reader and the tag generate the shared key, following an exchange of public keys
r_shared = scalarmult(r_private, t_public)
t_shared = scalarmult(t_private, r_public)

# Check that the transmitted values match
if r_shared == t_shared:
    print "Keys exchanged."
    print "Reader: ",binascii.hexlify(r_shared)
    print "Tag:    ",binascii.hexlify(t_shared)
    print
else:
    print "Error in key exchange."
    exit()

# Generate a message for the tag to send to the reader
message = "Hello, I am T."
message_salt = urandom(32)
Example #16
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
            print "PUB report recieved", controllerKey
            print ''
            ackSeq = res[12:14]

        else:
            res = ''
    else:
        print "No response, Resending report"
        d.RFxmit(invert(PUBreport + chr(calculate_checksum(PUBreport))))
        start = time.time()

#sendAck
sendAck(nodeId, ackSeq, d)

#Derive session key (Shared secret established via Curve25519)
sessionKey = scalarmult(pKey.decode("hex"),
                        controllerKey.decode("hex")).encode("hex")

print ''
print "Session key calculated:", sessionKey
print ''

#send Nonce Get
PUBreport = '\xC0\x1F\x9E\x67' + nodeId.decode(
    "hex") + '\x41\x46\x0D\x01\x9F\x01\x00'
d.RFxmit(invert(PUBreport + chr(calculate_checksum(PUBreport))))

#wait for Nonce Report
start = time.time()
res = ''
while res == '':
    end = time.time()