Esempio n. 1
0
    def create_user_id(self, num_pubkeys=1, public_keys=None):

        keypair = bbclib.KeyPair()
        user_id = hashlib.sha256(bytes(keypair.public_key)).digest()
        # FIXME: detect collision

        initial_keypairs = []
        if public_keys is None:
            public_keys = []
            for i in range(num_pubkeys):
                new_keypair = bbclib.KeyPair()
                initial_keypairs.append(new_keypair)
                public_keys.append(new_keypair.public_key)

        directive = Directive(Directive.CMD_REPLACE, public_keys)

        tx = bbclib.make_transaction_for_base_asset(
            asset_group_id=self.namespace_id, event_num=1)

        tx.events[0].asset.add(user_id=user_id,
                               asset_body=directive.serialize())
        tx.events[0].add(mandatory_approver=user_id)
        tx.add(witness=bbclib.BBcWitness())
        tx.witness.add_witness(user_id)
        self.sign_and_insert(tx, user_id, keypair)
        return (user_id, initial_keypairs)
Esempio n. 2
0
def sign_document(xml_string, private_key):
    if private_key is None:
        keypair = bbclib.KeyPair()
        keypair.generate()
        print('Keep this privately:')
        print('private key : {0}'.format(
            binascii.b2a_hex(keypair.private_key).decode()))
        print('')

    else:
        keypair = bbclib.KeyPair(privkey=binascii.a2b_hex(private_key))

    if xml_string.endswith('.xml'):
        tree = ET.parse(xml_string)
        e = tree.getroot()
    else:
        s = xml_string.encode('utf-8')
        e = ET.fromstring(s)

    digest = hashlib.sha256(registry_lib.file(e)).digest()

    sig = keypair.sign(digest)

    print('Put the following as attributes of your XML document root:')
    print('algo="{0}"'.format('ecdsa-p256v1'))
    print('sig="{0}"'.format(binascii.b2a_hex(sig).decode()))
    print('pubkey="{0}"'.format(binascii.b2a_hex(keypair.public_key).decode()))
Esempio n. 3
0
    def create_user_id(self,
                       num_pubkeys=1,
                       public_keys=None,
                       key_types=None,
                       label=None):
        """Creates a user ID (and key pairs) and map public keys to it.

        Args: 
            num_pubkeys (int): The number of new public keys to map to the ID.
            public_keys (list): The public keys to map. None by default.
            key_types (list): Types of the public keys. None by default.
            label (TransactionLabel): Label of transaction. None by default.
        
        Returns:
            user_id (bytes): The created user ID.
            initial_keypairs (list): The list of created key pairs.

        """

        keypair = bbclib.KeyPair(curvetype=self.default_key_type)
        keypair.generate()
        user_id = hashlib.sha256(bytes(keypair.public_key)).digest()
        # FIXME: detect collision

        initial_keypairs = []
        if public_keys is None:
            public_keys = []
            for i in range(num_pubkeys):
                new_keypair = bbclib.KeyPair(curvetype=self.default_key_type)
                new_keypair.generate()
                initial_keypairs.append(new_keypair)
                public_keys.append(new_keypair.public_key)

        directive = Directive(Directive.CMD_REPLACE, public_keys, key_types)

        tx = bbclib.make_transaction(event_num=1, witness=True)
        tx.events[0].asset_group_id = self.namespace_id
        tx.events[0].asset.add(user_id=user_id,
                               asset_body=directive.serialize(
                                   self.default_key_type))
        tx.events[0].add(mandatory_approver=user_id)

        if label is not None:
            tx.add(event=label.get_event())

        tx.witness.add_witness(user_id)
        self.sign_and_insert(tx, user_id, keypair)
        return user_id, initial_keypairs
Esempio n. 4
0
def read_keypair_file():
    with open(PRIVATE_KEY, "rb") as fin:
        private_key = fin.read()
    with open(PUBLIC_KEY, "rb") as fin:
        public_key = fin.read()
    key_pair = bbclib.KeyPair(privkey=private_key, pubkey=public_key)
    return key_pair
Esempio n. 5
0
def replace_keypair():

    username = request.json.get('username')
    password_digest_str = request.json.get('password_digest_str')

    if username is None:
        return jsonify(message="user name is nothing."), 404
    user = g.store.read_user(username, 'user_table')

    if user is None:
        return jsonify(message='user {0} is not found'.format(username)), 404

    if user.password != password_digest_str:
        return jsonify(message='password is incorrect.'), 404

    keypair_old = user.keypair

    keypair = bbclib.KeyPair()
    keypair.generate()

    g.idPubkeyMap = id_lib.BBcIdPublickeyMap(domain_id)
    g.idPubkeyMap.update(user.user_id,
                         public_key_to_replace=[keypair.public_key],
                         keypair=keypair_old)

    user.keypair = keypair
    g.store.update(user, 'user_table')

    return jsonify(
        pulic_key_str=bbclib.convert_id_to_string(keypair.public_key),
        private_key_str=bbclib.convert_id_to_string(keypair.private_key)), 200
Esempio n. 6
0
    def from_dict(dic):
        user_id = bytes(binascii.a2b_hex(dic['user_id']))
        public_key = bytes(binascii.a2b_hex(dic['public_key']))
        private_key = bytes(binascii.a2b_hex(dic['private_key']))

        return User(user_id,
                    bbclib.KeyPair(privkey=private_key, pubkey=public_key))
Esempio n. 7
0
    def test_00_setup(self):
        print("\n-----", sys._getframe().f_code.co_name, "-----")
        print("domain_id =", binascii.b2a_hex(domain_id))

        keypair = bbclib.KeyPair()
        keypair.generate()
        keyname = domain_id.hex() + ".pem"
        try:
            os.mkdir(".bbc1")
        except:
            pass
        with open(os.path.join(".bbc1", keyname), "wb") as f:
            f.write(keypair.get_private_key_in_pem())

        global msg_processor
        prepare(core_num=core_num, client_num=client_num, loglevel=LOGLEVEL)
        for i in range(core_num):
            start_core_thread(index=i,
                              core_port_increment=i,
                              p2p_port_increment=i)
            time.sleep(0.1)
            domain_setup_utility(i, domain_id)  # system administrator
        time.sleep(1)
        for i in range(client_num):
            msg_processor[i] = MessageProcessor(index=i)
            make_client(index=i,
                        core_port_increment=i,
                        callback=msg_processor[i])
        time.sleep(1)

        global cores, clients
        cores, clients = get_core_client()
Esempio n. 8
0
def make_client(index,
                core_port_increment,
                callback=None,
                connect_to_core=True,
                domain_id=None):
    keypair = bbclib.KeyPair()
    keypair.generate()
    clients[index]['user_id'] = bbclib.get_new_id("user_%i" % index)
    clients[index]['keypair'] = keypair
    clients[index]['app'] = bbc_app.BBcAppClient(port=DEFAULT_CORE_PORT +
                                                 core_port_increment,
                                                 multiq=False,
                                                 loglevel=loglv)
    if connect_to_core:
        if domain_id is None:
            global common_domain_id
            domain_id = common_domain_id
        clients[index]['app'].set_user_id(clients[index]['user_id'])
        clients[index]['app'].set_domain_id(domain_id)
    if callback is not None:
        clients[index]['app'].set_callback(callback)
    working_dir = ".bbc1-%i/" % (DEFAULT_CORE_PORT + core_port_increment)
    if os.path.exists(os.path.join(working_dir, "node_key.pem")):
        clients[index]['app'].set_node_key(
            os.path.join(working_dir, "node_key.pem"))
    time.sleep(1)
    print("[%i] user_id = %s" %
          (index, binascii.b2a_hex(clients[index]['user_id'])))
Esempio n. 9
0
def test_keypair_generate():
    """
    """
    keypair = bbclib.KeyPair()
    keypair.generate()
    assert (keypair.private_key_len.value == 32)
    assert (keypair.public_key_len.value == 65)
Esempio n. 10
0
def generate_keypair():
    keypair = bbclib.KeyPair()
    keypair.generate()
    print('private key : {0}'.format(
        binascii.b2a_hex(keypair.private_key).decode()))
    print('public key : {0}'.format(
        binascii.b2a_hex(keypair.public_key).decode()))
    return
Esempio n. 11
0
def create_keypair():
    keypair = bbclib.KeyPair()
    keypair.generate()
    with open(PRIVATE_KEY, "wb") as fout:
        fout.write(keypair.private_key)
    with open(PUBLIC_KEY, "wb") as fout:
        fout.write(keypair.public_key)
    print("created private_key and public_key : %s, %s" % (PRIVATE_KEY, PUBLIC_KEY))
Esempio n. 12
0
def get_keypair():
    keypair = bbclib.KeyPair()
    keypair.generate()

    return jsonify({
        'pubkey': binascii.b2a_hex(keypair.public_key).decode(),
        'privkey': binascii.b2a_hex(keypair.private_key).decode()
    })
Esempio n. 13
0
def create_keypair():
    if request.method == 'GET':
        keypair = bbclib.KeyPair()
        keypair.generate()

        save_keypair(keypair)

        return render_template('fileproof/message.html',
                               message="Keypair was created successfully.")
Esempio n. 14
0
def make_user(index):
    global users
    keypair = bbclib.KeyPair()
    keypair.generate()
    user_info = {
        'user_id': bbclib.get_new_id("user_%i" % index),
        'keypair': keypair,
    }
    users.append(user_info)
Esempio n. 15
0
def test_keypair_pubkey():
    """
    """
    keypair = bbclib.KeyPair(curvetype=bbclib.KeyType.ECDSA_SECP256k1,
                             privkey=in_privkey)
    keypair.mk_keyobj_from_private_key()
    assert (keypair.public_key_len.value == 65)
    assert (bytes(
        keypair.public_key)[:keypair.public_key_len.value] == in_pubkey)
Esempio n. 16
0
def store_proc(asset_body,
               asset_file,
               asset_group_id,
               domain_id,
               key_pair,
               user_id,
               txid=None):

    bbc_app_client = setup_bbc_client(domain_id, user_id)

    store_transaction = bbclib.make_transaction(relation_num=1, witness=True)
    bbclib.add_relation_asset(store_transaction,
                              relation_idx=0,
                              asset_group_id=asset_group_id,
                              user_id=user_id,
                              asset_body=asset_body,
                              asset_file=asset_file)
    store_transaction.witness.add_witness(user_id)

    if txid:
        bbc_app_client.search_transaction(txid)
        response_data = bbc_app_client.callback.synchronize()
        if response_data[KeyType.status] < ESUCCESS:
            return None, None, "ERROR: %s" % response_data[
                KeyType.reason].decode()

        prev_tx, fmt_type = bbclib.deserialize(
            response_data[KeyType.transaction_data])

        keypair = bbclib.KeyPair(privkey=key_pair.private_key,
                                 pubkey=key_pair.public_key)
        if not keypair.verify(prev_tx.transaction_id,
                              prev_tx.signatures[0].signature):
            return None, None, "ERROR: Signature or keypair is invalid."

        bbclib.add_relation_pointer(transaction=store_transaction,
                                    relation_idx=0,
                                    ref_transaction_id=prev_tx.transaction_id)

    sig = store_transaction.sign(private_key=key_pair.private_key,
                                 public_key=key_pair.public_key)
    store_transaction.get_sig_index(user_id)
    store_transaction.add_signature_object(user_id=user_id, signature=sig)
    store_transaction.digest()
    print(store_transaction)

    ret = bbc_app_client.insert_transaction(store_transaction)
    assert ret
    response_data = bbc_app_client.callback.synchronize()
    if response_data[KeyType.status] < ESUCCESS:
        return None, None, "ERROR: %s" % response_data[KeyType.reason].decode()

    transaction_id = response_data[KeyType.transaction_id]
    asset_ids = store_transaction.relations[0].asset.asset_id

    return asset_ids, transaction_id, None
    def test_06_domain_key_change(self):
        print("\n-----", sys._getframe().f_code.co_name, "-----")
        keypair = bbclib.KeyPair()
        keypair.generate()
        keyname = domain_id.hex() + ".pem"
        with open(keyname, "wb") as f:
            f.write(keypair.get_private_key_in_pem())

        for i, nw in enumerate(networkings):
            nw.get_domain_keypair(domain_id)

        keypair = bbclib.KeyPair()
        keypair.generate()
        keyname = domain_id.hex() + ".pem"
        with open(keyname, "wb") as f:
            f.write(keypair.get_private_key_in_pem())

        for i, nw in enumerate(networkings):
            nw.get_domain_keypair(domain_id)
Esempio n. 18
0
def create_keypair():

    if request.method == 'GET':

        keypair = bbclib.KeyPair()
        keypair.generate()

        return jsonify(private_key_str=bbclib.convert_id_to_string(
            keypair.private_key),
                       public_key_str=bbclib.convert_id_to_string(
                           keypair.public_key)), 200
    def test_00_key_setup(self):
        print("\n-----", sys._getframe().f_code.co_name, "-----")
        try:
            os.mkdir(".bbc1-domainkeys")
        except:
            pass

        keypair = bbclib.KeyPair()
        keypair.generate()
        keyname = os.path.join(".bbc1-domainkeys", domain_id.hex() + ".pem")
        with open(keyname, "wb") as f:
            f.write(keypair.get_private_key_in_pem())
Esempio n. 20
0
def test_keypair_pem():
    keypair = bbclib.KeyPair(curvetype=bbclib.KeyType.ECDSA_SECP256k1,
                             privkey=in_privkey,
                             pubkey=in_pubkey)

    pem = keypair.get_private_key_in_pem()
    assert (bytes(pem) == in_pem[:(len(in_pem) - 1)])  # ヌル終端を取り除いて比較する。

    keypair.mk_keyobj_from_private_key_pem(pem.decode())  # 文字列化する。
    assert (bytes(
        keypair.private_key)[:keypair.private_key_len.value] == in_privkey)
    assert (bytes(
        keypair.public_key)[:keypair.public_key_len.value] == in_pubkey)
Esempio n. 21
0
    def set_node_key(self, pem_file=None):
        """Set node_key to this client

        Args:
            pem_file (str): path string for the pem file
        """
        if pem_file is None:
            self.node_keypair = None
        try:
            self.node_keypair = bbclib.KeyPair()
            with open(pem_file, "r") as f:
                self.node_keypair.mk_keyobj_from_private_key_pem(f.read())
        except:
            return
Esempio n. 22
0
def test_keypair_der():
    """
    """
    keypair = bbclib.KeyPair(curvetype=bbclib.KeyType.ECDSA_SECP256k1,
                             privkey=in_privkey,
                             pubkey=in_pubkey)

    der = keypair.get_private_key_in_der()
    assert (der == in_der)

    keypair.mk_keyobj_from_private_key_der(der)
    assert (bytes(
        keypair.private_key)[:keypair.private_key_len.value] == in_privkey)
    assert (bytes(
        keypair.public_key)[:keypair.public_key_len.value] == in_pubkey)
Esempio n. 23
0
def replace_keypair(name, dic, file_name):
    for name0, user in dic.items():
        if name0 == name:
            keypair_old = user.keypair
            keypair = bbclib.KeyPair()
            idPubkeyMap = id_lib.BBcIdPublickeyMap(domain_id)
            idPubkeyMap.update(user.user_id,
                               public_keys_to_replace=[keypair.public_key],
                               keypair=keypair_old)
            user.keypair = keypair
            break

    write_dic(file_name, dic)
    print("public key for %s is renewed:" % (name))
    print("old:", binascii.b2a_hex(keypair_old.public_key).decode())
    print("new:", binascii.b2a_hex(keypair.public_key).decode())
def test_map_creation_with_pubkeys(default_domain_id):

    NUM_KEYPAIRS = 3

    public_keys = []
    for i in range(NUM_KEYPAIRS):
        keypair = bbclib.KeyPair()
        keypair.generate()
        public_keys.append(keypair.public_key)

    idPubkeyMap = id_lib.BBcIdPublickeyMap(default_domain_id)
    user_id, keypairs = idPubkeyMap.create_user_id(public_keys=public_keys)

    assert len(keypairs) == 0

    for i in range(NUM_KEYPAIRS):
        assert idPubkeyMap.is_mapped(user_id, public_keys[i]) == True
def test_key_types(default_domain_id):

    idPubkeyMap = id_lib.BBcIdPublickeyMap(
        default_domain_id, default_key_type=bbclib.KeyType.ECDSA_SECP256k1)
    user_id, keypairs = idPubkeyMap.create_user_id(num_pubkeys=1)

    assert len(keypairs) == 1

    assert idPubkeyMap.is_mapped(user_id, keypairs[0].public_key) == True

    public_keys, key_types = idPubkeyMap.get_mapped_public_keys(user_id)

    assert len(key_types) == 1
    assert key_types[0] == bbclib.KeyType.ECDSA_SECP256k1

    public_keys = []
    key_types = []
    for i in range(3):
        if i == 1:
            key_type = bbclib.KeyType.ECDSA_SECP256k1
        else:
            key_type = bbclib.KeyType.ECDSA_P256v1
        keypair = bbclib.KeyPair(key_type)
        keypair.generate()
        public_keys.append(keypair.public_key)
        key_types.append(key_type)

    tx = idPubkeyMap.update(user_id,
                            public_keys_to_replace=public_keys,
                            key_types_to_replace=key_types,
                            keypair=keypairs[0])

    assert idPubkeyMap.is_mapped(user_id, keypairs[0].public_key) == False
    for i in range(3):
        assert idPubkeyMap.is_mapped(user_id, public_keys[i]) == True

    public_keys, key_types = idPubkeyMap.get_mapped_public_keys(user_id)

    assert len(key_types) == 3
    for i, key_type in enumerate(key_types):
        if i == 1:
            assert key_type == bbclib.KeyType.ECDSA_SECP256k1
        else:
            assert key_type == bbclib.KeyType.ECDSA_P256v1
Esempio n. 26
0
def sign_document():
    document = get_document(request)

    privkey = request.json.get('privkey')

    if privkey is None:
        abort_by_missing_param('privkey')

    keypair = bbclib.KeyPair(privkey=binascii.a2b_hex(privkey))

    digest = hashlib.sha256(registry_lib.file(document.root)).digest()

    sig = keypair.sign(digest)

    return jsonify({
        'algo': 'ecdsa-p256v1',
        'sig': binascii.b2a_hex(sig).decode(),
        'pubkey': binascii.b2a_hex(keypair.public_key).decode()
    })
Esempio n. 27
0
    def test_00_setup(self):
        print("\n-----", sys._getframe().f_code.co_name, "-----")
        print("domain_id =", binascii.b2a_hex(domain_id))

        prepare(core_num=core_num, client_num=client_num, loglevel=LOGLEVEL)
        for i in range(core_num):
            start_core_thread(index=i, core_port_increment=i, p2p_port_increment=i)
        time.sleep(1)

        global cores
        cores = testutils.cores

        for i in range(client_num):
            clients[i] = setup_bbc_client(i, user_ids[i])
            ret = clients[i].register_to_core()
            assert ret
            keypairs[i] = bbclib.KeyPair()
            keypairs[i].generate()
        time.sleep(1)
Esempio n. 28
0
def sys_check(args):
    if args.command_type in ("store", "update", "verify") and \
            not os.path.exists(args.target_file):
        raise Exception("file not found : %s" % args.target_file)
    # TODO consider whether to check core accessibility
    if args.command_type != "keypair":
        if not os.path.exists(PRIVATE_KEY):
            message = "not exist private key\n"
            message += "create a key pair with keypair option"
            raise Exception(message)
        if not os.path.exists(PUBLIC_KEY):
            message = "not exist public key\n"
            message += "create a key pair with keypair option"
            raise Exception(message)
        with open(PRIVATE_KEY, "rb") as fin:
            private_key = fin.read()
        with open(PUBLIC_KEY, "rb") as fin:
            public_key = fin.read()
        global key_pair
        key_pair = bbclib.KeyPair(privkey=private_key, pubkey=public_key)
Esempio n. 29
0
def test_keypair_sign_and_verify():
    """
    """
    digest = binascii.a2b_hex(
        "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")

    keypair = bbclib.KeyPair(curvetype=bbclib.KeyType.ECDSA_SECP256k1,
                             privkey=in_privkey,
                             pubkey=in_pubkey)
    signature = keypair.sign(digest)
    print("signature = {}".format(signature))

    ret = keypair.verify(digest, signature)
    # print("ret = {}".format(ret))
    assert (ret == 1)

    not_digest = binascii.a2b_hex("bbbbbb")

    ret = keypair.verify(not_digest, signature)
    # print("ret = {}".format(ret))
    assert (ret == 0)
Esempio n. 30
0
def replace_keypair(hex_user_id=None):
    if hex_user_id is None:
        abort_by_missing_param('user_id')

    user = from_hex_to_user(g, hex_user_id, 'user_table')
    keypair_old = user.keypair

    keypair = bbclib.KeyPair()
    keypair.generate()

    g.idPubkeyMap = id_lib.BBcIdPublickeyMap(domain_id)
    g.idPubkeyMap.update(user.user_id,
            public_keys_to_replace=[keypair.public_key], keypair=keypair_old)
    
    user.keypair = keypair
    g.store.update_user(user, 'user_table')

    return jsonify({
        'old_pubkey': binascii.b2a_hex(keypair_old.public_key).decode(),
        'new_pubkey': binascii.b2a_hex(keypair.public_key).decode()
    })