コード例 #1
0
ファイル: test_crypto.py プロジェクト: cn-uofbasel/ssbdrv
def client():
    client_key = SigningKey(CLIENT_KEY_SEED)
    server_key = SigningKey(SERVER_KEY_SEED)
    client_eph_key = PrivateKey(CLIENT_EPH_KEY_SEED)
    return SHSClientCrypto(client_key,
                           bytes(server_key.verify_key),
                           client_eph_key,
                           application_key=APP_KEY)
コード例 #2
0
ファイル: test_signing.py プロジェクト: quipri/pynacl
class TestSigningKey:
    def test_initialize_with_generate(self):
        SigningKey.generate()

    def test_wrong_length(self):
        with pytest.raises(ValueError):
            SigningKey(b"")

    def test_bytes(self):
        k = SigningKey(b"\x00" * crypto_sign_SEEDBYTES)
        assert bytes(k) == b"\x00" * crypto_sign_SEEDBYTES

    def test_equal_keys_are_equal(self):
        k1 = SigningKey(b"\x00" * crypto_sign_SEEDBYTES)
        k2 = SigningKey(b"\x00" * crypto_sign_SEEDBYTES)
        assert_equal(k1, k1)
        assert_equal(k1, k2)

    def test_equal_keys_have_equal_hashes(self):
        k1 = SigningKey(b"\x00" * crypto_sign_SEEDBYTES)
        k2 = SigningKey(b"\x00" * crypto_sign_SEEDBYTES)
        assert hash(k1) == hash(k2)
        assert id(k1) != id(k2)

    @pytest.mark.parametrize('k2', [
        b"\x00" * crypto_sign_SEEDBYTES,
        SigningKey(b"\x01" * crypto_sign_SEEDBYTES),
        SigningKey(b"\x00" * (crypto_sign_SEEDBYTES - 1) + b"\x01"),
    ])
    def test_different_keys_are_not_equal(self, k2):
        k1 = SigningKey(b"\x00" * crypto_sign_SEEDBYTES)
        assert_not_equal(k1, k2)

    @pytest.mark.parametrize("seed", [
        b"77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a",
    ])
    def test_initialization_with_seed(self, seed):
        SigningKey(seed, encoder=HexEncoder)

    @pytest.mark.parametrize(
        ("seed", "_public_key", "message", "signature", "expected"),
        ed25519_known_answers()
    )
    def test_message_signing(self, seed, _public_key,
                             message, signature, expected):
        signing_key = SigningKey(
            seed,
            encoder=HexEncoder,
        )
        signed = signing_key.sign(
            binascii.unhexlify(message),
            encoder=HexEncoder,
        )

        assert signed == expected
        assert signed.message == message
        assert signed.signature == signature
コード例 #3
0
def test_get_chat_event():
    try:
        with LogCapture() as log_cap:
            private_key = secrets.token_bytes(32)
            signing_key = SigningKey(private_key)
            public_key_feed_id = signing_key.verify_key.encode()

            content0 = Content('chat/whateveraction', {
                'messagekey': 'hallo zusammen',
                'chat_id': '1',
                'timestampkey': 10
            })
            hash_of_content = hashlib.sha256(
                content0.get_as_cbor()).hexdigest()
            hash_of_prev = None
            meta = Meta(public_key_feed_id, 0, hash_of_prev, 'ed25519',
                        ('sha256', hash_of_content))
            signature = signing_key.sign(meta.get_as_cbor())._signature
            event = Event(meta, signature, content0).get_as_cbor()

            connector = EventHandler()
            connector.add_event(event)
            meta = Meta(public_key_feed_id, 1, hash_of_prev, 'ed25519',
                        ('sha256', hash_of_content))
            content1 = Content('chat/whateveraction', {
                'messagekey': 'wie gehts?',
                'chat_id': '1',
                'timestampkey': 20
            })
            signature = signing_key.sign(meta.get_as_cbor())._signature
            event = Event(meta, signature, content1).get_as_cbor()
            connector.add_event(event)
            content2 = Content(
                'chat/whateveraction', {
                    'messagekey': 'schönes Wetter heute',
                    'chat_id': '1',
                    'timestampkey': 30
                })
            meta = Meta(public_key_feed_id, 2, hash_of_prev, 'ed25519',
                        ('sha256', hash_of_content))
            signature = signing_key.sign(meta.get_as_cbor())._signature
            event = Event(meta, signature, content2).get_as_cbor()
            connector.add_event(event)
        print(log_cap)
        print('\n#######################################')
        # TODO: there seem to be some errors concerning the chat_id, I would watch out in what form it is (binary or string?)
        q = EventHandler().get_event_since('chat', 15, '1')
        print(q)
        print('\n#######################################')
        t = EventHandler().get_all_events(application='chat', chat_id='1')
        print(t)
        assert True
    finally:
        try:
            if os.path.exists('eventDatabase.sqlite'):
                os.remove('eventDatabase.sqlite')
            else:
                assert False
        except PermissionError:
            print('Database is still in use')
コード例 #4
0
    def __init__(self, secret, algorithm=None):
        if algorithm is None:
            algorithm = DEFAULT_SIGN_ALGORITHM

        assert algorithm in ALGORITHMS, "Unknown algorithm"
        if isinstance(secret, six.string_types):
            secret = secret.encode("ascii")

        self._rsa = None
        self._hash = None
        self._ed25519 = None
        splitted = algorithm.split('-')
        if len(splitted) > 1:
            self.sign_algorithm, self.hash_algorithm = splitted
        else:
            self.sign_algorithm, self.hash_algorithm = splitted[0], None

        if self.sign_algorithm == 'rsa':
            try:
                rsa_key = RSA.importKey(secret)
                self._rsa = PKCS1_v1_5.new(rsa_key)
                self._hash = HASHES[self.hash_algorithm]
            except ValueError:
                raise HttpSigException("Invalid key.")

        elif self.sign_algorithm == 'hmac':
            self._hash = HMAC.new(secret,
                                  digestmod=HASHES[self.hash_algorithm])

        elif self.sign_algorithm == 'ed25519':
            self._ed25519 = SigningKey(secret, encoder=Base64Encoder)
コード例 #5
0
def route_logic(message_class, current_user, msg_content):
    # grid relative
    from .node import get_node  # TODO: fix circular import

    if current_user:
        user_key = SigningKey(current_user.private_key.encode("utf-8"),
                              encoder=HexEncoder)
        msg_content["internal_key"] = current_user.private_key
        msg_content["current_user"] = current_user.id
    else:
        user_key = SigningKey.generate()

    content = {
        "address": get_node().address,
        "content": msg_content,
        "reply_to": get_node().address,
    }

    syft_message = {}
    syft_message["message_class"] = message_class
    syft_message["message_content"] = content
    syft_message["sign_key"] = user_key

    # Execute task
    response_msg = task_handler(
        route_function=process_as_syft_message,
        data=syft_message,
        mandatory={
            "message_class": MissingRequestKeyError,
            "message_content": MissingRequestKeyError,
            "sign_key": MissingRequestKeyError,
        },
    )
    return response_msg
コード例 #6
0
ファイル: views.py プロジェクト: netsec-ethz/scion-web
def prep_approved_join_reply(request, join_rep_dict, own_isdas, own_as_obj):
    """
    Prepares the join reply for the APPROVED case.
    """
    logger.info("New AS ID = %s", request.POST['newASId'])
    joining_as = request.POST['newASId']
    is_core = request.POST['join_as_a_core']
    sig_pub_key = from_b64(request.POST['sig_pub_key'])
    enc_pub_key = from_b64(request.POST['enc_pub_key'])
    signing_as_sig_priv_key = from_b64(own_as_obj.sig_priv_key)
    joining_ia = TopoID.from_values(own_isdas[0], joining_as)
    if is_core.lower() == "true":
        validity = Certificate.CORE_AS_VALIDITY_PERIOD
        comment = "Core AS Certificate"
    else:
        validity = Certificate.AS_VALIDITY_PERIOD
        comment = "AS Certificate"
    cert = Certificate.from_values(
        str(joining_ia), str(own_isdas), INITIAL_TRC_VERSION, INITIAL_CERT_VERSION, comment,
        is_core, validity, enc_pub_key, sig_pub_key, SigningKey(signing_as_sig_priv_key)
    )
    respond_ia_chain = CertificateChain.from_raw(own_as_obj.certificate)
    request_ia_chain = CertificateChain([cert, respond_ia_chain.core_as_cert])
    join_rep_dict['JoiningIA'] = str(joining_ia)
    join_rep_dict['IsCore'] = is_core.lower() == "true"
    join_rep_dict['RespondIA'] = str(own_isdas)
    join_rep_dict['JoiningIACertificate'] = request_ia_chain.to_json()
    join_rep_dict['RespondIACertificate'] = respond_ia_chain.to_json()
    join_rep_dict['TRC'] = TRC.from_raw(own_as_obj.trc).to_json()
    logger.debug("Accepting Join Request = %s", join_rep_dict)
コード例 #7
0
ファイル: ironhouse.py プロジェクト: Mat001/cilantro
    def generate_certificates(self, sk):
        sk = SigningKey(seed=bytes.fromhex(sk))
        self.vk = sk.verify_key.encode().hex()
        self.public_key = self.vk2pk(self.vk)
        private_key = crypto_sign_ed25519_sk_to_curve25519(
            sk._signing_key).hex()

        for d in [self.keys_dir, self.public_keys_dir, self.secret_keys_dir]:
            if self.wipe_certs and os.path.exists(d):
                shutil.rmtree(d)
            os.makedirs(d, exist_ok=True)

        if self.wipe_certs:
            self.create_from_private_key(private_key)

            # move public keys to appropriate directory
            for key_file in os.listdir(self.keys_dir):
                if key_file.endswith(".key"):
                    shutil.move(os.path.join(self.keys_dir, key_file),
                                os.path.join(self.public_keys_dir, '.'))

            # move secret keys to appropriate directory
            for key_file in os.listdir(self.keys_dir):
                if key_file.endswith(".key_secret"):
                    shutil.move(os.path.join(self.keys_dir, key_file),
                                os.path.join(self.secret_keys_dir, '.'))

            log.info('Generated CURVE certificate files!')
コード例 #8
0
 def author(self, cursor):
     cursor.execute("SELECT author_name, author_private_key FROM config")
     name, keydata = cursor.fetchone()
     return LocalAuthor(
         name=name,
         signing_key=SigningKey(keydata, encoder=Base32Encoder),
     )
コード例 #9
0
ファイル: lib.py プロジェクト: roshanlam/HonorsPy
def read_signing_key_file(file):
    """Read signing key from file"""
    try:
        with open(file, 'rb') as f:
            return SigningKey(f.read(), encoder=HexEncoder)
    except FileNotFoundError:
        create_account_and_save_signing_key_file(file)
コード例 #10
0
def verify_pair(filename):
    """
    Function to verify a public/private key pair previously generated by this
    tool.

    Parameters
    ----------

    filename: str
        Name of the files to write the public and private key to.
    """
    with open(filename, 'r') as f:
        hex_read = f.read().encode()
        sk_read = SigningKey(hex_read, encoder=HexEncoder)

    pub_filename = filename + '.pub'
    with open(pub_filename, 'r') as f:
        hex_read = f.read().encode()
        vk_read = VerifyKey(hex_read, encoder=HexEncoder)

    phrase_to_sign = b'phrase to sign'
    try:
        signed_phrase = sk_read.sign(phrase_to_sign)
        vk_read.verify(signed_phrase)
    except BadSignatureError as be:
        print(f"Private key in {filename} does not match public key in {pub_filename}.")
        return False

    print(f"Private key in {filename} matches public key in {pub_filename}.")
    return True
コード例 #11
0
ファイル: blockchain.py プロジェクト: k98kurz/BasicBlockChain
    def create_block(signing_key,
                     previous_block,
                     body,
                     difficulty=1,
                     difficulty_mode=0):
        signing_key = SigningKey(signing_key) if type(signing_key) == type(
            's') or type(signing_key) == type(b's') else signing_key
        nonce = nacl.utils.random(16)
        signature = signing_key.sign(previous_block['hash'] + nonce + body)

        # mild PoW
        while not BasicBlockChain.meets_difficulty(
                signature.signature, difficulty, difficulty_mode):
            nonce = nacl.utils.random(16)
            signature = signing_key.sign(previous_block['hash'] + nonce + body)

        hash = sha256(signature.signature, encoder=RawEncoder)

        # return the block
        return {
            'block_height': previous_block['block_height'] + 1,
            'hash': hash,
            'signature': signature.signature,
            'address': signing_key.verify_key._key,
            'previous_block': previous_block['hash'],
            'nonce': nonce,
            'body': body
        }
コード例 #12
0
def test_worker_key_pair_tool():
    key_file = "gen_pair_test"
    private_key, public_key = gen_pair(key_file)

    test_phrase = b"Test phrase"
    try:
        public_key.verify(private_key.sign(test_phrase))
    except BadSignatureError as bse:
        assert False

    # load the generated keys from the file
    with open(key_file, 'r') as f:
        loaded_private_key = SigningKey(f.read().encode(), encoder=HexEncoder)
    with open(key_file + '.pub', 'r') as f:
        loaded_public_key = VerifyKey(f.read().encode(), encoder=HexEncoder)

    # test the
    try:
        loaded_public_key.verify(loaded_private_key.sign(test_phrase))
    except BadSignatureError as bse:
        assert False
    assert verify_pair(key_file)

    # test that a bad signature is detected
    with open(key_file, 'w') as f:
        f.write(
            SigningKey.generate().encode(encoder=HexEncoder).decode('utf-8'))
    assert not verify_pair(key_file)

    # clean up
    os.remove(key_file)
    os.remove(key_file + '.pub')
コード例 #13
0
def prepare_hsc_transfer_transaction():
    from stablecoin.TransferTransactionData_pb2 import TransferTransactionData
    from stablecoin.TransactionBody_pb2 import TransactionBody
    from stablecoin.Transaction_pb2 import Transaction

    key_from = SigningKey(
        bytes.fromhex(
            "1aaced2d7b85ca122adfb5e6d15926eddbdfa8f270e40109fa01e3607446c48b")
    )
    address_from = bytes(key_from.verify_key)

    address_to = bytes.fromhex(
        "c9fef56cee613e390d728399bef53619603b9f0559daab6ba68bf1c24715fb23")
    value = int_to_bytes(100)  # $1.00

    transfer = TransferTransactionData(to=address_to, value=value)
    valid_start = generate_valid_start_nanos()
    body = TransactionBody(caller=address_from,
                           operatorAccountNum=9523,
                           validStartNanos=valid_start,
                           transfer=transfer)
    body_bytes = body.SerializeToString()

    body_signature = key_from.sign(body_bytes).signature

    tx = Transaction(body=body_bytes, signature=body_signature)
    tx_bytes = tx.SerializeToString()

    return tx_bytes, 9523, valid_start
コード例 #14
0
def send_signed_block(*, block, ip_address, port, protocol, url_path):
    """
    Sign block and send to recipient
    """

    network_signing_key = get_environment_variable('NETWORK_SIGNING_KEY')
    signing_key = SigningKey(network_signing_key, encoder=HexEncoder)
    node_identifier = get_verify_key(signing_key=signing_key)
    node_identifier = encode_verify_key(verify_key=node_identifier)
    message = sort_and_encode(block)

    signed_block = {
        'block': block,
        'node_identifier': node_identifier,
        'signature': generate_signature(message=message,
                                        signing_key=signing_key)
    }

    node_address = format_address(ip_address=ip_address,
                                  port=port,
                                  protocol=protocol)
    url = f'{node_address}{url_path}'

    try:
        post(url=url, body=signed_block)
    except Exception as e:
        logger.exception(e)
コード例 #15
0
    def get_keys_from_file(private_key_file):
        """
        Creates the SigningKey object from the private_key_file containing
        the private key string, and reads the public key from the corresponding
        .pub file and returns the SigningKey and the public key string.

        Parameters
        ----------

        private_key_file: str
            The name of the file containing the private key. The corresponding
            public key is expected to be in the private_key_file+'.pub' file

        Returns
        -------

        SigningKey, str:
            The private key, and the public key in string form.
        """
        if private_key_file is None:
            return None, None
        with open(private_key_file, 'r') as f:
            hex_read = f.read().encode()
            private_key = SigningKey(hex_read, encoder=HexEncoder)
        with open(private_key_file + '.pub', 'r') as f:
            public_key_str = f.read()

        return private_key, public_key_str
コード例 #16
0
ファイル: agent.py プロジェクト: clicknull/petmail
    def command_list_addressbook(self):
        resp = []
        # these entries might merely be incomplete invitations
        for row in self.db.execute("SELECT * FROM addressbook").fetchall():
            entry = {}
            # these properties are set right away
            entry["cid"] = row["id"]
            entry["petname"] = row["petname"]
            entry["acked"] = bool(row["acked"])
            entry["invitation_context"] = {
                "when_invited": row["when_invited"],
                "code": row["invitation_code"],
            }
            sk = SigningKey(row["my_signkey"].decode("hex"))
            entry["my_verfkey"] = sk.verify_key.encode(Hex)

            # these appear when the invitation process is complete
            if row["when_accepted"] is not None:
                entry["invitation_context"]["when_accepted"] = row[
                    "when_accepted"]
            if row["their_verfkey"] is not None:
                entry["their_verfkey"] = str(row["their_verfkey"])
            if row["their_channel_record_json"] is not None:
                entry["their_channel_record"] = json.loads(
                    row["their_channel_record_json"])
            # TODO: filter out the long-term stuff
            resp.append(entry)
        return resp
コード例 #17
0
def test_local_feed():
    secret = b64decode('Mz2qkNOP2K6upnqibWrR+z8pVUI1ReA1MLc7QMtF2qQ=')
    feed = LocalFeed(SigningKey(secret))
    assert bytes(feed.private_key) == secret
    assert bytes(feed.public_key) == b64decode(
        'I/4cyN/jPBbDsikbHzAEvmaYlaJK33lW3UhWjNXjyrU=')
    assert feed.id == '@I/4cyN/jPBbDsikbHzAEvmaYlaJK33lW3UhWjNXjyrU=.ed25519'
コード例 #18
0
ファイル: transactions.py プロジェクト: BoladoSeis/MathCoins
def create_transaction(
    private_key: str, public_key: str, receiver: str, amount: int
) -> dict:
    """
    Creates a transaction from a sender's public key to a receiver's public key

    :param private_key: The Sender's private key
    :param public_key: The Sender's public key
    :param receiver: The Receiver's public key
    :param amount: The amount in cents
    :return: <dict> The transaction dict
    """

    tx = {
        "sender": public_key,
        "receiver": receiver,
        "amount": amount,
        "timestamp": int(time()),
    }
    tx_bytes = json.dumps(tx, sort_keys=True).encode("ascii")

    # Generate a signing key from the private key
    signing_key = SigningKey(private_key, encoder=HexEncoder)

    # Now add the signature to the original transaction
    signature = signing_key.sign(tx_bytes).signature
    tx["signature"] = HexEncoder.encode(signature).decode("ascii")

    return tx
コード例 #19
0
    def generate_certificates(cls, sk_hex, wipe_certs=False):
        sk = SigningKey(seed=bytes.fromhex(sk_hex))
        vk = sk.verify_key.encode().hex()
        public_key = cls.vk2pk(vk)
        private_key = crypto_sign_ed25519_sk_to_curve25519(
            sk._signing_key).hex()

        for d in [cls.keys_dir, cls.authorized_keys_dir]:
            if wipe_certs and exists(d):
                shutil.rmtree(d)
            os.makedirs(d, exist_ok=True)

        if wipe_certs:
            _, secret = cls.create_from_private_key(private_key)

            for key_file in os.listdir(cls.keys_dir):
                if key_file.endswith(".key"):
                    shutil.move(join(cls.keys_dir, key_file),
                                join(cls.authorized_keys_dir, '.'))

            if exists(cls.keys_dir):
                shutil.rmtree(cls.keys_dir)

            log.info('Generated CURVE certificate files!')

        return vk, public_key, secret
コード例 #20
0
def read_signing_key_file(file):
    """
    Read signing key from file
    """

    with open(file, "rb") as f:
        return SigningKey(f.read(), encoder=HexEncoder)
コード例 #21
0
def test_get_current_event():
    try:
        with LogCapture():
            private_key = secrets.token_bytes(32)
            signing_key = SigningKey(private_key)
            public_key_feed_id = signing_key.verify_key.encode()

            content = Content('whateverapp/whateveraction', {
                'oneKey': 'somevalue',
                'someotherkey': 1
            })
            hash_of_content = hashlib.sha256(content.get_as_cbor()).hexdigest()
            hash_of_prev = None
            meta = Meta(public_key_feed_id, 0, hash_of_prev, 'ed25519',
                        ('sha256', hash_of_content))
            signature = signing_key.sign(meta.get_as_cbor())._signature
            event = Event(meta, signature, content).get_as_cbor()

            connector = DatabaseConnector()
            connector.add_event(event)
            result = connector.get_current_event(public_key_feed_id)
            result = Event.from_cbor(result)
        assert result.meta.hash_of_content[1] == meta.hash_of_content[1]
    finally:
        try:
            if os.path.exists('cborDatabase.sqlite'):
                os.remove('cborDatabase.sqlite')
                if os.path.exists('eventDatabase.sqlite'):
                    os.remove('eventDatabase.sqlite')
            else:
                assert False
        except PermissionError:
            print('Database is still in use')
コード例 #22
0
def decrypt_message(encrypted_message, keying_material, private_key):
    encrypted_key = keying_material['encrypted_key']
    message_signature = keying_material['message_signature']
    temp_public_key = PublicKey(
        keying_material['temp_public_key'],
        Base64Encoder)

    box = PublicBox(private_key, temp_public_key)

    message_key = box.decrypt(
        encrypted_key,
        encoder=Base64Encoder)

    # We got the key, so let's get the message.
    message_box = nacl.secret.SecretBox(message_key)
    message = message_box.decrypt(
        encrypted_message,
        encoder=Base64Encoder)

    # Check the signature.
    mac_key = sha256(box._shared_key, RawEncoder)
    signing_key = SigningKey(mac_key)
    if signing_key.sign(message, Base64Encoder) != message_signature:
        raise SignatureError("The signature is not valid")

    return message
コード例 #23
0
ファイル: signing_key.py プロジェクト: maxide/Bank-1
def get_signing_key():
    """
    Return signing key
    """

    network_signing_key = get_environment_variable('NETWORK_SIGNING_KEY')
    return SigningKey(network_signing_key, encoder=HexEncoder)
コード例 #24
0
ファイル: ECKeyPair.py プロジェクト: bitlogik/uniblow
 def __init__(self, pv_key_int, curve):
     """An EllipticCurvePrivateKey object"""
     self.curve = curve
     if self.curve == "K1":
         curveobj = K1_CURVE
     elif self.curve == "R1":
         curveobj = R1_CURVE
     if self.curve == "K1" or self.curve == "R1":
         # K1 or R1
         if pv_key_int < 0:
             # No private key provided, generating
             self.key_obj = ec.generate_private_key(
                 curveobj, backends.default_backend())
         else:
             # Create a key pair from the provided key integer
             self.key_obj = ec.derive_private_key(
                 pv_key_int, curveobj, backends.default_backend())
     elif self.curve == "ED":
         if pv_key_int < 0:
             # No private key provided, generating
             seed_bytes = random_generator()
         else:
             # Create a key pair from the provided key integer
             seed_bytes = pv_key_int.to_bytes(32, "big")
         self.key_obj = SigningKey(seed_bytes, RawEncoder)
     else:
         raise ValueError("ECkeypair must be K1, R1 or ED")
コード例 #25
0
ファイル: local_gen.py プロジェクト: pietdevaere/scion-coord
def generate_certificate(joining_ia, core_ia, core_sign_priv_key_file, core_cert_file, trc_file):
    """
    """
    core_ia_chain = CertificateChain.from_raw(read_file(core_cert_file))
    # AS cert is always expired one second before the expiration of the Core AS cert
    validity = core_ia_chain.core_as_cert.expiration_time - int(time.time()) - 1
    comment = "AS Certificate"
    core_ia_sig_priv_key = base64.b64decode(read_file(core_sign_priv_key_file))
    public_key_sign, private_key_sign = generate_sign_keypair()
    public_key_encr, private_key_encr = generate_enc_keypair()
    cert = Certificate.from_values(
        str(joining_ia), str(core_ia), INITIAL_TRC_VERSION, INITIAL_CERT_VERSION, comment,
        False, validity, public_key_encr, public_key_sign, core_ia_sig_priv_key)
    sig_priv_key = base64.b64encode(private_key_sign).decode()
    enc_priv_key = base64.b64encode(private_key_encr).decode()
    sig_priv_key_raw = base64.b64encode(SigningKey(private_key_sign)._signing_key).decode()
    joining_ia_chain = CertificateChain([cert, core_ia_chain.core_as_cert]).to_json()
    trc = open(trc_file).read()
    master_as_key = base64.b64encode(Random.new().read(16)).decode('utf-8')
    key_dict = {
        'enc_key': enc_priv_key,
        'sig_key': sig_priv_key,
        'sig_key_raw': sig_priv_key_raw,
        'master_as_key': master_as_key,
    }
    as_obj = ASCredential(joining_ia_chain, trc, key_dict)
    return as_obj
コード例 #26
0
 def _assign_keys(self, as_):
     isd_as_id = as_.isd_as_str()
     chain = self.loader.certs[isd_as_id]
     as_.certificate_chain = chain
     assert (chain['0']['Subject'] == isd_as_id)
     as_.sig_pub_key = chain['0']['SubjectSignKey']
     as_.enc_pub_key = chain['0']['SubjectEncKey']
     as_.sig_priv_key = self.loader.keys_sig[isd_as_id]
     as_.enc_priv_key = self.loader.keys_decrypt[isd_as_id]
     as_.master_as_key = self.loader.master0s[isd_as_id]
     if as_.is_core:
         trc = self.loader.trcs[as_.isd.isd_id]
         as_.core_offline_priv_key = self.loader.core_keys_offline[
             isd_as_id]
         as_.core_offline_pub_key = trc['CoreASes'][isd_as_id]['OfflineKey']
         as_.core_online_priv_key = self.loader.core_keys_online[isd_as_id]
         as_.core_online_pub_key = trc['CoreASes'][isd_as_id]['OnlineKey']
         as_.core_sig_priv_key = self.loader.core_keys_sig[isd_as_id]
         as_.core_sig_pub_key = base64.b64encode(
             SigningKey(base64.b64decode(
                 as_.core_sig_priv_key)).verify_key._key).decode()
         core_cert = Certificate(
             chain['1'])  # load the one from the json file and adapt it
         core_cert.subject = as_.isd_as_str()
         core_cert.issuer = as_.isd_as_str()  # self signed
         core_cert.subject_enc_key = ''
         core_cert.subject_sig_key = as_.core_sig_pub_key
         core_cert.sign(base64.b64decode(as_.core_online_priv_key))
         as_.core_certificate = core_cert.dict()
         # redo the AS cert in the chain
         cert = Certificate(chain['0'])
         cert.issuer = as_.isd_as_str()
         cert.sign(base64.b64decode(as_.core_sig_priv_key))
         as_.certificate_chain = {'0': cert.dict(), '1': core_cert.dict()}
     as_.save()
コード例 #27
0
def create_local_author_from_config(config, name=None):
    """
    :param config: a Tahoe config instance (created via `allmydata.client.read_config`)

    :param name: which Magic Folder to use (or 'default')

    :returns: a LocalAuthor instance from our configuration
    """
    # private-keys go in "<node_dir>/private/magicfolder_<name>.privkey"
    # to mirror where the sqlite database goes
    if name is None:
        name = "default"
    nodedir = config.get_config_path()
    magic_folders = load_magic_folders(nodedir)
    if name not in magic_folders:
        raise RuntimeError("No magic-folder named '{}'".format(name))

    # we will always have authorship information for this
    # magic-folder; "legacy" magic-folders will go through "tahoe
    # migrate" first and have an author created.

    author_raw = config.get_private_config(
        "magicfolder_{}.privkey".format(name))
    author_data = json.loads(author_raw)

    return LocalAuthor(
        name=author_data[u"author_name"],
        signing_key=SigningKey(
            author_data[u"author_private_key"],
            encoder=Base64Encoder,
        ),
    )
コード例 #28
0
ファイル: client.py プロジェクト: yashlamba/PySyft
        def __init__(
            self,
            credentials: Dict,
            url: str,
            conn_type: Type[ClientConnection],
            client_type: Type[Client],
        ) -> None:

            # Use Server metadata
            # to build client route
            self.conn = conn_type(url=url)  # type: ignore
            self.client_type = client_type

            if credentials:
                metadata, _user_key = self.conn.login(credentials=credentials)  # type: ignore
                _user_key = SigningKey(_user_key.encode("utf-8"), encoder=HexEncoder)
            else:
                metadata = self.conn._get_metadata()  # type: ignore
                if not user_key:
                    _user_key = SigningKey.generate()
                else:
                    _user_key = user_key

            (
                spec_location,
                name,
                client_id,
            ) = self.client_type.deserialize_client_metadata_from_node(
                metadata=metadata
            )

            # Create a new Solo Route using the selected connection type
            route = SoloRoute(destination=spec_location, connection=self.conn)

            location_args = self.__route_client_location(
                client_type=self.client_type, location=spec_location
            )

            self.proxy_address: Optional[Address] = None

            # Create a new client using the selected client type
            super().__init__(
                network=location_args[NetworkClient],
                domain=location_args[DomainClient],
                device=location_args[DeviceClient],
                vm=location_args[VirtualMachineClient],
                name=name,
                routes=[route],
                signing_key=_user_key,
            )

            self.groups = GroupRequestAPI(send=self.__perform_grid_request)
            self.users = UserRequestAPI(send=self.__perform_grid_request)
            self.roles = RoleRequestAPI(send=self.__perform_grid_request)
            self.workers = WorkerRequestAPI(
                send=self.__perform_grid_request, domain_client=self
            )
            self.association_requests = AssociationRequestAPI(
                send=self.__perform_grid_request
            )
コード例 #29
0
def test_handshake_envelopes():
    vectors = get_test_vectors()
    client_signing_private_key = SigningKey(
        binascii.a2b_base64(vectors['test1']['client_signing_priv_key']))
    client_signing_keypair = Ed25519KeyPair(
        client_signing_private_key, client_signing_private_key.verify_key)
    client_e_keypair = Curve25519KeyPair(
        PrivateKey(
            binascii.a2b_base64(
                vectors['test1']['client_ephemeral_priv_key'])),
        PublicKey(
            binascii.a2b_base64(vectors['test1']['client_ephemeral_pub_key'])))
    server_e_keypair = Curve25519KeyPair(
        PrivateKey(
            binascii.a2b_base64(
                vectors['test1']['server_ephemeral_priv_key'])),
        PublicKey(
            binascii.a2b_base64(vectors['test1']['server_ephemeral_pub_key'])))
    server_signing_private_key = SigningKey(
        binascii.a2b_base64(vectors['test1']['server_signing_priv_key']))
    server_signing_keypair = Ed25519KeyPair(
        server_signing_private_key, server_signing_private_key.verify_key)

    server_envelope_factory = SecretHandshakeEnvelopeFactory(
        bytes(binascii.a2b_base64(vectors['test1']['application_key'])),
        server_e_keypair, server_signing_keypair,
        client_signing_keypair.public_key)
    client_envelope_factory = SecretHandshakeEnvelopeFactory(
        bytes(binascii.a2b_base64(vectors['test1']['application_key'])),
        client_e_keypair, client_signing_keypair,
        server_signing_keypair.public_key)

    client_challenge = client_envelope_factory.create_client_challenge()
    assert bytes(client_challenge) == binascii.a2b_base64(
        vectors['test1']['client_challenge'])
    assert server_envelope_factory.is_client_challenge_verified(
        client_challenge) == True

    server_challenge = server_envelope_factory.create_server_challenge()
    assert client_envelope_factory.is_server_challenge_verified(
        server_challenge) == True

    client_auth = client_envelope_factory.create_client_auth()
    server_envelope_factory.verify_client_auth(client_auth)

    server_accept = server_envelope_factory.create_server_accept()
    client_envelope_factory.verify_server_accept(server_accept)
コード例 #30
0
def test_get_event():
    try:
        with LogCapture() as log_cap:
            private_key = secrets.token_bytes(32)
            signing_key = SigningKey(private_key)
            public_key_feed_id = signing_key.verify_key.encode()

            content0 = Content('whateverapp/whateveraction', {
                'firstkey': 'somevalue',
                'someotherkey': 3
            })
            hash_of_content = hashlib.sha256(
                content0.get_as_cbor()).hexdigest()
            hash_of_prev = None
            meta = Meta(public_key_feed_id, 0, hash_of_prev, 'ed25519',
                        ('sha256', hash_of_content))
            signature = signing_key.sign(meta.get_as_cbor())._signature
            event = Event(meta, signature, content0).get_as_cbor()

            connector = DatabaseConnector()
            connector.add_event(event)
            meta = Meta(public_key_feed_id, 1, hash_of_prev, 'ed25519',
                        ('sha256', hash_of_content))
            content1 = Content('whateverapp/whateveraction', {
                'secondkey': 'somevalue',
                'someotherkey': 4
            })
            signature = signing_key.sign(meta.get_as_cbor())._signature
            event = Event(meta, signature, content1).get_as_cbor()
            connector.add_event(event)
            content2 = Content('whateverapp/whateveraction', {
                'thirdkey': 'somevalue',
                'someotherkey': 5
            })
            meta = Meta(public_key_feed_id, 2, hash_of_prev, 'ed25519',
                        ('sha256', hash_of_content))
            signature = signing_key.sign(meta.get_as_cbor())._signature
            event = Event(meta, signature, content2).get_as_cbor()
            connector.add_event(event)
            res0 = connector.get_event(public_key_feed_id, 0)
            res1 = connector.get_event(public_key_feed_id, 1)
            res2 = connector.get_event(public_key_feed_id, 2)
            result0 = Event.from_cbor(res0)
            result1 = Event.from_cbor(res1)
            result2 = Event.from_cbor(res2)
        assert result0.content.content == content0.content
        assert result1.content.content == content1.content
        assert result2.content.content == content2.content
        print(log_cap)
    finally:
        try:
            if os.path.exists('cborDatabase.sqlite'):
                os.remove('cborDatabase.sqlite')
                if os.path.exists('eventDatabase.sqlite'):
                    os.remove('eventDatabase.sqlite')
            else:
                assert False
        except PermissionError:
            print('Database is still in use')