示例#1
0
 def __init__(self):
     # type: () -> None
     self.vk, self._sk = libnacl.crypto_sign_keypair()
     self._other_chains = {}  # type: Dict[str, GrowingList]
     self.my_chain = Chain(self.vk, self._sk)
     self.consensus = {}  # type: Dict[int, Cons]
     logging.info("TC: my VK is {}".format(b64encode(self.vk)))
示例#2
0
 def test_box(self):
     msg = b'Are you suggesting coconuts migrate?'
     # run 1
     vk1, sk1 = libnacl.crypto_sign_keypair()
     sig = libnacl.crypto_sign(msg, sk1)
     self.assertEqual(msg, sig[libnacl.crypto_sign_BYTES:])
     sig_msg = libnacl.crypto_sign_open(sig, vk1)
     self.assertEqual(msg, sig_msg)
示例#3
0
 def test_gen(self):
     vk1, sk1 = libnacl.crypto_sign_keypair()
     vk2, sk2 = libnacl.crypto_sign_keypair()
     vk3, sk3 = libnacl.crypto_sign_keypair()
     self.assertEqual(len(vk1), libnacl.crypto_sign_PUBLICKEYBYTES)
     self.assertEqual(len(sk1), libnacl.crypto_sign_SECRETKEYBYTES)
     self.assertEqual(len(vk2), libnacl.crypto_sign_PUBLICKEYBYTES)
     self.assertEqual(len(sk2), libnacl.crypto_sign_SECRETKEYBYTES)
     self.assertEqual(len(vk3), libnacl.crypto_sign_PUBLICKEYBYTES)
     self.assertEqual(len(sk3), libnacl.crypto_sign_SECRETKEYBYTES)
     self.assertNotEqual(vk1, sk1)
     self.assertNotEqual(vk2, sk2)
     self.assertNotEqual(vk3, sk3)
     self.assertNotEqual(vk1, vk2)
     self.assertNotEqual(vk1, vk3)
     self.assertNotEqual(sk1, sk2)
     self.assertNotEqual(sk2, sk3)
示例#4
0
文件: urc.py 项目: mikalv/urc.py
 def initkeys(self, fname='keys.dat'):
     """
     generate / load signing keys
     """
     if not os.path.exists(fname):
         self._pk , self._sk  = libnacl.crypto_sign_keypair()
         self.dump_keys(fname)
     self.load_keys(fname)
示例#5
0
def testSignatureValidation():
    vk, sk = libnacl.crypto_sign_keypair()
    data = {'message': 'this is a test'}
    signed = libnacl.crypto_sign(bytes(data['message'], 'utf-8'), sk)
    base64Signature = base64.b64encode(signed)
    base64Key = base64.b64encode(vk)
    verified, message = validateSignature(base64Signature, base64Key, dumps(data))
    assert verified
    data = {'message': 'this will fail'}
    verified, message = validateSignature(base64Signature, base64Key, dumps(data))
    assert not verified
示例#6
0
    def create(cls) -> 'Member':
        """
        Creates new member with a signing (private) key
        """
        verify_key_bytes, signing_key_bytes = crypto_sign_keypair()
        verify_key = base64_encode(verify_key_bytes).decode("UTF-8")
        signing_key = base64_encode(signing_key_bytes).decode("UTF-8")
        new_member = Member(verify_key, signing_key)
        new_member.name = "Me"

        bptc.logger.info("Created new Member: " + str(new_member))

        return new_member
示例#7
0
 def _generate():
     """Generate an Ed25519-SHA512 signing key pair
     """
     return libnacl.crypto_sign_keypair()
示例#8
0
    def __init__(self, filename):

        self.filename = os.path.abspath(filename)
        self.threadLocal = threading.local()

        #Deterministically generate a keypair that we will use to sign all correspondance
        self.localNodeVK, self.localNodeSK = libnacl.crypto_sign_seed_keypair(
            libnacl.crypto_generichash(
                os.path.basename(filename).encode("utf8"), nodeID))
        print(len(self.localNodeVK), self.localNodeVK, 90)

        #Websockets that are subscribing to us.
        self.subscribers = weakref.WeakValueDictionary()

        self.dbConnect()

        self.config = configparser.ConfigParser()

        if os.path.exists(filename + ".conf"):
            self.config.read(filename + ".conf")

        self.threadLocal.conn.row_factory = sqlite3.Row
        # self.threadLocal.conn.execute("PRAGMA wal_checkpoint=FULL")
        self.threadLocal.conn.execute("PRAGMA secure_delete = off")

        # Yep, we're really just gonna use it as a document store like this.
        self.threadLocal.conn.execute(
            '''CREATE TABLE IF NOT EXISTS document (rowid integer primary key, json text, signature text, localinfo text)'''
        )

        self.threadLocal.conn.execute('''CREATE TABLE IF NOT EXISTS meta
             (key text primary key, value  text)''')

        self.threadLocal.conn.execute('''CREATE TABLE IF NOT EXISTS peers
             (peerID text primary key, lastArrival integer, info text)''')

        # To keep indexing simple and universal, it only works on three properties.  _tags, _description and _body.
        self.threadLocal.conn.execute('''
             CREATE VIRTUAL TABLE IF NOT EXISTS search USING fts5(tags, description, body, content='')'''
                                      )

        self.threadLocal.conn.execute(
            '''CREATE INDEX IF NOT EXISTS document_parent ON document(json_extract(json,"$.parent")) WHERE json_extract(json,"$.parent") IS NOT null '''
        )
        self.threadLocal.conn.execute(
            '''CREATE INDEX IF NOT EXISTS document_link ON document(json_extract(json,"$.link")) WHERE json_extract(json,"$.link") IS NOT null'''
        )
        self.threadLocal.conn.execute(
            '''CREATE INDEX IF NOT EXISTS document_name ON document(json_extract(json,"$.name"))'''
        )
        self.threadLocal.conn.execute(
            '''CREATE INDEX IF NOT EXISTS document_id ON document(json_extract(json,"$.id"))'''
        )
        self.threadLocal.conn.execute(
            '''CREATE INDEX IF NOT EXISTS document_type ON document(json_extract(json,"$.type"))'''
        )

        self.threadLocal.conn.execute("""
            CREATE TRIGGER IF NOT EXISTS search_index AFTER INSERT ON document BEGIN
            INSERT INTO search(rowid, tags, description, body) VALUES (new.rowid, IFNULL(json_extract(new.json,"$.tags"), ""), IFNULL(json_extract(new.json,"$.description"), ""), IFNULL(json_extract(new.json,"$.body"), ""));
            END;
            """)

        self.threadLocal.conn.execute(
            """   CREATE TRIGGER IF NOT EXISTS search_delete AFTER DELETE ON document BEGIN
            INSERT INTO search(search, rowid, tags, description, body) VALUES ('delete', old.rowid, IFNULL(json_extract(old.json,"$.tags"), ""), IFNULL(json_extract(old.json,"$.description"), ""), IFNULL(json_extract(old.json,"$.body"), ""));
            END;""")

        self.threadLocal.conn.execute("""
            CREATE TRIGGER IF NOT EXISTS search_update AFTER UPDATE ON document BEGIN
            INSERT INTO search(search, rowid, tags, description, body) VALUES ('delete', old.rowid, IFNULL(json_extract(old.json,"$.tags"), ""), IFNULL(json_extract(old.json,"$.description"), ""), IFNULL(json_extract(old.json,"$.body"), ""));
            INSERT INTO search(rowid, tags, description, body) VALUES (new.rowid, IFNULL(json_extract(new.json,"$.tags"), ""), IFNULL(json_extract(new.json,"$.description"), ""), IFNULL(json_extract(new.json,"$.body"), ""));
            END;
            """)

        self.keys = configparser.ConfigParser()

        if os.path.exists(filename + ".keys"):
            self.keys.read(filename + ".keys")

        pk = base64.b64decode(self.keys.get('key', 'public', fallback=''))
        sk = base64.b64decode(self.keys.get('key', 'secret', fallback=''))

        # Generate a keypair for this particular node.
        if not (pk and sk):
            pk, sk = libnacl.crypto_sign_keypair()
            try:
                self.keys.add_section("key")
            except:
                pass
            self.keys.set('key', 'public', base64.b64encode(pk).decode('utf8'))
            self.keys.set('key', 'secret', base64.b64encode(sk).decode('utf8'))

            # Add our new key to the approved list, for our local copy.
            if 'approved' not in self.config:
                self.config.add_section('approved')
                self.config.set('approved', 'autogenerated',
                                base64.b64encode(pk).decode())
            self.saveConfig()

        self.publicKey = pk
        self.secretKey = sk

        if 'sync' not in self.config:
            self.config.add_section('sync')
            self.config.set('sync', 'syncKey',
                            base64.b64encode(os.urandom(24)).decode('utf8'))
            self.config.set('sync', 'writePassword',
                            base64.b64encode(os.urandom(24)).decode('utf8'))
            self.saveConfig()

        self.syncKey = self.config.get('sync', 'syncKey', fallback=None)
        self.writePassword = self.config.get('sync',
                                             'writePassword',
                                             fallback='')

        if self.syncKey:
            databaseBySyncKeyHash[libnacl.crypto_generichash(
                self.syncKey.encode("utf8"))[:16]] = self
        if self.writePassword:
            databaseBySyncKeyHash[libnacl.crypto_generichash(
                self.writePassword.encode("utf8"))[:16]] = self

        print(list(databaseBySyncKeyHash.keys()))
        self.approvedPublicKeys = {}

        if 'approved' in self.config:
            for i in self.config['approved']:
                # Reverse lookup
                self.approvedPublicKeys[self.config['approved'][i]] = i
示例#9
0
 def _generate():
     """Generate an Ed25519-SHA512 signing key pair
     """
     return libnacl.crypto_sign_keypair()
示例#10
0
文件: urc.py 项目: mikalv/urc.py
def test_crypto(data=rand(8)):
    pk , sk = libnacl.crypto_sign_keypair()
    sig = nacl_sign(data, sk)
    nacl_verify(data, sig, pk)
    def __init__(self, filename):

        self.filename = os.path.abspath(filename)

        self.conn = sqlite3.connect(filename)
        self.config = configparser.ConfigParser()

        if os.path.exists(filename + ".conf"):
            self.config.read(filename + ".conf")

        self.conn.row_factory = sqlite3.Row
        # Self.conn.execute("PRAGMA wal_checkpoint=FULL")
        self.conn.execute("PRAGMA secure_delete = off")

        # Yep, we're really just gonna use it as a document store like this.
        self.conn.execute(
            '''CREATE TABLE IF NOT EXISTS document (rowid integer primary key, json text, signature text, localinfo text)'''
        )

        self.conn.execute('''CREATE TABLE IF NOT EXISTS meta
             (key text primary key, value  text)''')

        # To keep indexing simple and universal, it only works on three properties.  _tags, _description and _body.
        self.conn.execute('''
             CREATE VIRTUAL TABLE IF NOT EXISTS search USING fts5(tags, description, body, content='')'''
                          )

        self.conn.execute(
            '''CREATE INDEX IF NOT EXISTS document_parent ON document(json_extract(json,"$._parent")) WHERE json_extract(json,"$._parent") IS NOT null '''
        )
        self.conn.execute(
            '''CREATE INDEX IF NOT EXISTS document_link ON document(json_extract(json,"$._link")) WHERE json_extract(json,"$._link") IS NOT null'''
        )
        self.conn.execute(
            '''CREATE INDEX IF NOT EXISTS document_name ON document(json_extract(json,"$._name"))'''
        )
        self.conn.execute(
            '''CREATE INDEX IF NOT EXISTS document_id ON document(json_extract(json,"$._id"))'''
        )
        self.conn.execute(
            '''CREATE INDEX IF NOT EXISTS document_type ON document(json_extract(json,"$._type"))'''
        )

        self.conn.execute("""
            CREATE TRIGGER IF NOT EXISTS search_index AFTER INSERT ON document BEGIN
            INSERT INTO search(rowid, tags, description, body) VALUES (new.rowid, IFNULL(json_extract(new.json,"$._tags"), ""), IFNULL(json_extract(new.json,"$._description"), ""), IFNULL(json_extract(new.json,"$._body"), ""));
            END;
            """)

        self.conn.execute(
            """   CREATE TRIGGER IF NOT EXISTS search_delete AFTER DELETE ON document BEGIN
            INSERT INTO search(search, rowid, tags, description, body) VALUES ('delete', old.rowid, IFNULL(json_extract(old.json,"$._tags"), ""), IFNULL(json_extract(old.json,"$._description"), ""), IFNULL(json_extract(old.json,"$._body"), ""));
            END;""")

        self.conn.execute("""
            CREATE TRIGGER IF NOT EXISTS search_update AFTER UPDATE ON document BEGIN
            INSERT INTO search(search, rowid, tags, description, body) VALUES ('delete', old.rowid, IFNULL(json_extract(old.json,"$._tags"), ""), IFNULL(json_extract(old.json,"$._description"), ""), IFNULL(json_extract(old.json,"$._body"), ""));
            INSERT INTO search(rowid, tags, description, body) VALUES (new.rowid, IFNULL(json_extract(new.json,"$._tags"), ""), IFNULL(json_extract(new.json,"$._description"), ""), IFNULL(json_extract(new.json,"$._body"), ""));
            END;
            """)

        self.keys = configparser.ConfigParser()

        if os.path.exists(filename + ".keys"):
            self.keys.read(filename + ".keys")

        pk = base64.b64decode(self.keys.get('key', 'public', fallback=''))
        sk = base64.b64decode(self.keys.get('key', 'secret', fallback=''))

        # Generate a keypair for this particular node.
        if not (pk and sk):
            pk, sk = libnacl.crypto_sign_keypair()
            try:
                self.keys.add_section("key")
            except:
                pass
            self.keys.set('key', 'public', base64.b64encode(pk).decode('utf8'))
            self.keys.set('key', 'secret', base64.b64encode(sk).decode('utf8'))

            # Add our new key to the approved list, for our local copy.
            if 'approved' not in self.config:
                self.config.add_section('approved')
                self.config.set('approved', 'autogenerated',
                                base64.b64encode(pk).decode())
            self.saveConfig()

        self.publicKey = pk
        self.secretKey = sk

        if 'sync' not in self.config:
            self.config.add_section('sync')
            self.config.set('sync', 'syncKey', str(uuid.uuid4()))
            self.config.set('sync', 'writePassword', str(uuid.uuid4()))
            self.saveConfig()

        self.syncKey = self.config.get('sync', 'syncKey', fallback=None)

        if self.syncKey:
            databaseBySyncKey[libnacl.crypto_generichash(self.syncKey)] = self

        self.approvedPublicKeys = {}

        if 'approved' in self.config:
            for i in self.config['approved']:
                # Reverse lookup
                self.approvedPublicKeys[self.config['approved'][i]] = i