Example #1
0
    def test_onetimeauth_verify(self):
        self.assertEqual("poly1305", libnacl.crypto_onetimeauth_primitive())

        msg = b'Anybody can invent a cryptosystem he cannot break himself. Except Bruce Schneier.'
        key1 = libnacl.randombytes(libnacl.crypto_onetimeauth_KEYBYTES)
        key2 = libnacl.randombytes(libnacl.crypto_onetimeauth_KEYBYTES)

        sig1 = libnacl.crypto_onetimeauth(msg, key1)
        sig2 = libnacl.crypto_onetimeauth(msg, key2)

        with self.assertRaises(ValueError):
            libnacl.crypto_onetimeauth(msg, b'too_short')

        with self.assertRaises(ValueError):
            libnacl.crypto_onetimeauth_verify(sig1, msg, b'too_short')

        with self.assertRaises(ValueError):
            libnacl.crypto_onetimeauth_verify(b'too_short', msg, key1)

        self.assertTrue(libnacl.crypto_onetimeauth_verify(sig1, msg, key1))
        self.assertTrue(libnacl.crypto_onetimeauth_verify(sig2, msg, key2))
        with self.assertRaises(ValueError) as context:
            libnacl.crypto_onetimeauth_verify(sig1, msg, key2)
        self.assertTrue('Failed to auth message' in context.exception.args)

        with self.assertRaises(ValueError) as context:
            libnacl.crypto_onetimeauth_verify(sig2, msg, key1)
        self.assertTrue('Failed to auth message' in context.exception.args)
Example #2
0
    def test_040_verify_cookiepacket(self):
        """ Check whether cookie is properly extraced. """
        identifier = struct.pack("<8s", b"rZQTd2nC")
        nonce = libnacl.randombytes(16)
        nonce_expanded = struct.pack("<8s16s", b"splonePK", nonce)

        cookie = libnacl.randombytes(96)
        payload = b''.join([self.servershorttermpk, cookie])
        box = libnacl.crypto_box(payload, nonce_expanded,
                                 self.crypt.clientshorttermpk,
                                 self.serverlongtermsk)

        # good case
        data = b''.join([identifier, nonce, box])
        cookie_extracted = self.crypt._verify_cookiepacket(data)
        self.assertEqual(cookie, cookie_extracted)

        # too short
        self.assertRaises(InvalidPacketException,
                          self.crypt._verify_cookiepacket, data[:167])

        # message has illegal identifier
        data = b''.join([struct.pack("<8s", b'foobar'), nonce, box])
        self.assertRaises(InvalidPacketException,
                          self.crypt._verify_cookiepacket, data)

        # manipulated payload
        data = b''.join([identifier, nonce, libnacl.randombytes(len(box))])
        self.assertRaises(InvalidPacketException,
                          self.crypt._verify_cookiepacket, data)
Example #3
0
    def testGetHacked(self, promiscuous_client):
        seed = libnacl.randombytes(libnacl.crypto_sign_SEEDBYTES)
        vk, sk, did, body = eddsa.genDidHistory(seed,
                                                signer=0,
                                                numSigners=2,
                                                method="fake")
        vk = h.bytesToStr64u(vk)

        signature = eddsa.signResource(body, sk)

        headers = {"Signature": 'signer="{0}"'.format(signature)}

        response = promiscuous_client.simulate_post(HISTORY_BASE_PATH,
                                                    body=body,
                                                    headers=headers)

        assert response.status == falcon.HTTP_201

        seed = libnacl.randombytes(libnacl.crypto_sign_SEEDBYTES)
        vk2, sk2, did2, body2 = eddsa.genDidHistory(seed,
                                                    signer=0,
                                                    numSigners=2)
        vk2 = h.bytesToStr64u(vk2)

        body2 = json.loads(body2)
        body2["id"] = did
        body2 = json.dumps(body2).encode()

        signature2 = eddsa.signResource(body2, sk2)

        headers2 = {"Signature": 'signer="{0}"'.format(signature2)}

        response = promiscuous_client.simulate_post(HISTORY_BASE_PATH,
                                                    body=body2,
                                                    headers=headers2)

        assert response.status == falcon.HTTP_201

        response = promiscuous_client.simulate_get("{}/{}".format(
            EVENTS_BASE_PATH, did))

        exp_result = [
            [{
                "event": json.loads(body2.decode()),
                "signatures": {
                    "signer": signature2
                }
            }],
            [{
                "event": json.loads(body.decode()),
                "signatures": {
                    "signer": signature
                }
            }],
        ]

        assert response.status == falcon.HTTP_200
        assert json.loads(response.content) == exp_result
Example #4
0
    def testGetAll(self, race_client):
        seed = libnacl.randombytes(libnacl.crypto_sign_SEEDBYTES)
        vk, sk, did, body = eddsa.genDidHistory(seed, signer=0, numSigners=2)
        vk = h.bytesToStr64u(vk)

        signature = eddsa.signResource(body, sk)

        headers = {"Signature": 'signer="{0}"'.format(signature)}

        race_client.simulate_post(HISTORY_BASE_PATH,
                                  body=body,
                                  headers=headers)

        seed = libnacl.randombytes(libnacl.crypto_sign_SEEDBYTES)
        vk2, sk2, did2, body2 = eddsa.genDidHistory(seed,
                                                    signer=0,
                                                    numSigners=2)
        vk2 = h.bytesToStr64u(vk2)

        signature2 = eddsa.signResource(body2, sk2)

        headers2 = {"Signature": 'signer="{0}"'.format(signature2)}

        race_client.simulate_post(HISTORY_BASE_PATH,
                                  body=body2,
                                  headers=headers2)

        response = race_client.simulate_get(EVENTS_BASE_PATH)

        exp_result = {
            "data": [[[{
                "event": json.loads(body.decode()),
                "signatures": {
                    "signer": signature
                }
            }]],
                     [[{
                         "event": json.loads(body2.decode()),
                         "signatures": {
                             "signer": signature2
                         }
                     }]]]
        }

        response_data = json.loads(response.content)
        assert response.status == falcon.HTTP_200
        assert len(response_data["data"]) == 2
        # response_data order is unreliable
        # make sure that each history exists only once in response
        for result in exp_result['data']:
            matches = 0
            for data in response_data['data']:
                if data == result:
                    matches += 1

            assert matches == 1
Example #5
0
def testSendNymFailsIfAbbrevVerkeySizeIs17Bytes(
        looper, sdk_pool_handle, txnPoolNodeSet, nym_request, sdk_wallet_trustee):
    parameters = {
        'dest': rawToFriendly(randombytes(16)),
        'verkey': '~' + rawToFriendly(randombytes(17)),
        'role': TRUST_ANCHOR
    }
    nym_request[OPERATION].update(parameters)
    request_couple = sdk_sign_and_send_prepared_request(looper, sdk_wallet_trustee,
                                                        sdk_pool_handle, json.dumps(nym_request))
    sdk_get_and_check_replies(looper, [request_couple])
Example #6
0
def testSendNymFailsIfAbbrevVerkeySizeIs17Bytes(
        be, do, poolNodesStarted, trusteeCli):

    parameters = {
        'dest': rawToFriendly(randombytes(16)),
        'verkey': '~' + rawToFriendly(randombytes(17)),
        'role': Roles.TRUST_ANCHOR.name
    }

    be(trusteeCli)
    do('send NYM dest={dest} role={role}',
       mapper=parameters, expect=ERROR, within=2)
def testSendNymFailsIfAbbrevVerkeySizeIs17Bytes(
        be, do, poolNodesStarted, trusteeCli):

    parameters = {
        'dest': rawToFriendly(randombytes(16)),
        'verkey': '~' + rawToFriendly(randombytes(17)),
        'role': Roles.TRUST_ANCHOR.name
    }

    be(trusteeCli)
    do('send NYM dest={dest} role={role}',
       mapper=parameters, expect=ERROR, within=2)
Example #8
0
def testHackerRevocation(client):
    # Make sure that a hacker can't revoke someone elses keys.
    seed = libnacl.randombytes(libnacl.crypto_sign_SEEDBYTES)
    vk, sk, did, body = eddsa.genDidHistory(seed, signer=0, numSigners=2)
    vk = h.bytesToStr64u(vk)

    headers = {
        "Signature":
        'signer="{0}"; rotation="{1}"'.format(eddsa.signResource(body, sk),
                                              eddsa.signResource(body, sk))
    }

    # send inception event
    client.simulate_post(HISTORY_BASE_PATH, body=body,
                         headers=headers)  # Add did to database

    seed = libnacl.randombytes(libnacl.crypto_sign_SEEDBYTES)
    hacked_vk, hacked_sk = eddsa.generateByteKeys(seed)
    hacked_vk = h.bytesToStr64u(hacked_vk)
    body = json.loads(body)
    body['changed'] = "2000-01-01T00:00:02+00:00"
    body['signer'] = 5
    body['signers'].append(hacked_vk)
    body['signers'].append(hacked_vk)
    body['signers'].append(hacked_vk)
    body['signers'].append(None)

    headers = {
        "Signature":
        'signer="{0}"; rotation="{1}"'.format(
            eddsa.signResource(
                json.dumps(body, ensure_ascii=False).encode(), hacked_sk),
            eddsa.signResource(
                json.dumps(body, ensure_ascii=False).encode(), hacked_sk))
    }

    exp_result = {
        "title":
        "Authorization Error",
        "description":
        "Could not validate the request signature for rotation field. Unverifiable signature."
    }

    verifyRequest(client.simulate_put,
                  "{0}/{1}".format(HISTORY_BASE_PATH, did),
                  body,
                  headers,
                  exp_result=exp_result,
                  exp_status=falcon.HTTP_401)
Example #9
0
    def test_020_crypto_write(self):
        """ Verify whether message packet is properly build. """
        payload = libnacl.randombytes(40)
        data = self.crypt.crypto_write(payload)

        identifier, = struct.unpack("<8s", data[:8])
        self.assertEqual(identifier.decode('ascii'), "oqQN2kaM")

        nonce, = struct.unpack("<Q", data[8:16])
        self.assertEqual(
            nonce + 2,  # add two since nonce is increased
            # to boxing the payload (and not
            # only the length)
            self.crypt.nonce)
        self.assertTrue(nonce % 2 == 1)

        nonceexpanded = struct.pack("<16sQ", b"splonebox-client", nonce)
        length = libnacl.crypto_box_open(data[16:40], nonceexpanded,
                                         self.crypt.clientshorttermpk,
                                         self.servershorttermsk)
        self.assertEqual(struct.unpack("Q", length)[0], len(data))

        nonceexpanded = struct.pack("<16sQ", b"splonebox-client", nonce + 2)
        plaintext = libnacl.crypto_box_open(data[40:], nonceexpanded,
                                            self.crypt.clientshorttermpk,
                                            self.servershorttermsk)
        self.assertEqual(plaintext, payload)
Example #10
0
    def test_060_initiate_packet(self):
        """ Verify that the correct initiate packet is build. """
        cookie = libnacl.randombytes(96)
        self.crypt._verify_cookiepacket = mock.Mock(return_value=cookie)
        data = self.crypt.crypto_initiate(b'dummy')

        identifier = struct.unpack("<8s", data[:8])[0]
        self.assertEqual(b"oqQN2kaI", identifier)

        cookie_extracted = struct.unpack("<96s", data[8:104])[0]
        self.assertEqual(cookie_extracted, cookie)

        nonce = struct.unpack("Q", data[104:112])[0]
        nonce_expanded = struct.pack("<16sQ", b"splonebox-client", nonce)
        payload = libnacl.crypto_box_open(data[112:], nonce_expanded,
                                          self.crypt.clientshorttermpk,
                                          self.servershorttermsk)

        clientlongtermpk = struct.unpack("<32s", payload[:32])[0]
        self.assertEqual(clientlongtermpk, self.crypt.clientlongtermpk)

        nonce = struct.unpack("16s", payload[32:48])[0]
        nonce_expanded = struct.pack("<8s16s", b"splonePV", nonce)
        vouch = libnacl.crypto_box_open(payload[48:], nonce_expanded,
                                        self.crypt.clientlongtermpk,
                                        self.serverlongtermsk)

        self.assertEqual(vouch[:32], self.crypt.clientshorttermpk)
        self.assertEqual(vouch[32:], self.crypt.servershorttermpk)
Example #11
0
    def __init__(self, identifier, seed=None):

        """
        Initialize the signer with an identifier and a seed.

        :param identifier: some identifier that directly or indirectly references this client
        :param seed: the seed used to generate a signing key.
        """

        self.identifier = identifier

        # should be stored securely/privately
        self.seed = seed if seed else randombytes(32)

        # generates key pair based on seed
        self.sk = SigningKey(seed=self.seed)

        # helper for signing
        self.naclSigner = NaclSigner(self.sk)

        # this is the public key used to verify signatures (securely shared
        # before-hand with recipient)
        self.verkey = self.naclSigner.verhex

        self.verstr = base64_encode(self.naclSigner.keyraw).decode('utf-8')
Example #12
0
    def test_051_listen_one_two_packets(self):
        """ verify correct handling of PackageTooShortException"""
        con = self.con
        con._disconnected.clear()
        buf = mocks.connection_socket_fake_recv(con)

        data = libnacl.randombytes(64)

        # the callback function called after decrypting packet
        callback = mock.Mock()

        # mock length
        crypto_verify = mock.Mock()
        crypto_verify.side_effect = [PacketTooShortException(), len(data)]
        con.crypto_context.crypto_verify_length = crypto_verify

        # mock crypto_read function to return full data in two packets
        crypto_read = mock.Mock()
        crypto_read.side_effect = [data]
        con.crypto_context.crypto_read = crypto_read

        # put data on to mocked socket (socket will return b'' afterwards)
        buf.append(data[:10])
        buf.append(data[10:])

        con._listen(callback)

        # verify that crypto_verify is called with incomming packet
        crypto_verify.assert_has_calls([mock.call(data[:10]), mock.call(data)])

        # verify that crypto_read is called with incoming data
        crypto_read.assert_has_calls([mock.call(data)])

        # verify that callback is called
        callback.assert_has_calls([mock.call(data)])
Example #13
0
    def __init__(self, seed=None, sk=None, vk=None, did=None):
        if (sk is None and vk) or (sk and vk is None):
            raise ValueError('Both private and public keys required')

        if did and sk is None and vk is None:
            raise ValueError('Keys required with did')

        if sk and len(sk) != DidBox.crypto_didbox_SKBYTES or vk and len(
                vk) != DidBox.crypto_didbox_VKBYTES:
            raise ValueError('Invalid key')

        if sk is None and vk is None and seed is None:
            seed = libnacl.randombytes(libnacl.crypto_sign_SEEDBYTES)

            vk, sk = libnacl.crypto_sign_seed_keypair(seed)

            did = didering.didGen(vk)

        if seed and sk is None and vk is None:
            vk, sk = libnacl.crypto_sign_seed_keypair(seed)

            did = didering.didGen(vk)

        if sk and vk and did is None:
            did = didering.didGen(vk)

        self.seed = seed
        self.sk = sk
        self.vk = vk
        self.did = did
Example #14
0
    def __init__(self, identifier=None, seed=None, alias=None):
        """
        Initialize the signer with an identifier and a seed.

        :param identifier: some identifier that directly or indirectly
        references this client
        :param seed: the seed used to generate a signing key.
        """

        # should be stored securely/privately
        self.seed = seed if seed else randombytes(32)

        # generates key pair based on seed
        self.sk = SigningKey(seed=self.seed)

        # helper for signing
        self.naclSigner = NaclSigner(self.sk)

        verraw = self.naclSigner.verraw

        if identifier:
            self._identifier = identifier
            self._verkey = rawToFriendly(verraw)
            self.abbreviated = False
        else:
            self._identifier = rawToFriendly(verraw[:16])
            self._verkey = rawToFriendly(verraw[16:])
            self.abbreviated = True

        self._alias = alias
Example #15
0
 def encrypt(self, key: bytes,
             nonce: Optional[bytes] = None) -> EncryptedWallet:
     serialized = jsonpickle.encode(self)
     byts = serialized.encode()
     nonce = nonce if nonce else randombytes(crypto_secretbox_NONCEBYTES)
     raw = crypto_secretbox(byts, nonce, key)
     return EncryptedWallet(raw, nonce)
Example #16
0
 def encrypt(self, key: bytes,
             nonce: Optional[bytes] = None) -> EncryptedWallet:
     serialized = jsonpickle.encode(self)
     byts = serialized.encode()
     nonce = nonce if nonce else randombytes(crypto_secretbox_NONCEBYTES)
     raw = crypto_secretbox(byts, nonce, key)
     return EncryptedWallet(raw, nonce)
Example #17
0
def testFullSigning():
    # stored securely/privately
    seed = randombytes(32)

    # generates key pair based on seed
    sk = SigningKey(seed=seed)

    # helper for signing
    signer = Signer(sk)

    # this is the public key used to verify signatures (securely shared before-hand with recipient)
    verkey = signer.verhex

    # the message to be signed
    msg = b'1234'

    # the signature
    sig = signer.signature(msg)

    # helper for verification
    vr = Verifier(verkey)

    # verification
    isVerified = vr.verify(sig, msg)

    assert isVerified
Example #18
0
def testDidGen():
    seed = libnacl.randombytes(libnacl.crypto_sign_SEEDBYTES)
    vk, sk = libnacl.crypto_sign_seed_keypair(seed)

    did = didering.didGen(vk)

    assert did == "did:dad:{}".format(gen.keyToKey64u(vk))
Example #19
0
    def __init__(self, identifier=None, seed=None, alias=None):
        """
        Initialize the signer with an identifier and a seed.

        :param identifier: some identifier that directly or indirectly
        references this client
        :param seed: the seed used to generate a signing key.
        """

        # should be stored securely/privately
        self.seed = seed if seed else randombytes(32)

        # generates key pair based on seed
        self.sk = SigningKey(seed=self.seed)

        # helper for signing
        self.naclSigner = NaclSigner(self.sk)

        # this is the public key used to verify signatures (securely shared
        # before-hand with recipient)
        hex_verkey = hexlify(self.naclSigner.verraw)
        self.verkey = hexToFriendly(hex_verkey)

        self._identifier = identifier or self.verkey

        self._alias = alias
Example #20
0
    def generate(cls):
        """
        Generates a random :class:`~PrivateKey` object

        :rtype: :class:`~PrivateKey`
        """
        return cls(libnacl.randombytes(PrivateKey.SIZE), encoder=encoding.RawEncoder)
Example #21
0
    def __init__(self, identifier=None, seed=None, alias=None):
        """
        Initialize the signer with an identifier and a seed.

        :param identifier: some identifier that directly or indirectly
        references this client
        :param seed: the seed used to generate a signing key.
        """

        # should be stored securely/privately
        self.seed = seed if seed else randombytes(32)

        # generates key pair based on seed
        self.sk = SigningKey(seed=self.seed)

        # helper for signing
        self.naclSigner = NaclSigner(self.sk)

        # this is the public key used to verify signatures (securely shared
        # before-hand with recipient)
        hex_verkey = hexlify(self.naclSigner.verraw)
        self.verkey = hexToFriendly(hex_verkey)

        self._identifier = identifier or self.verkey

        self._alias = alias
Example #22
0
 def _rand_data(self):
     raw = libnacl.randombytes(16)
     submitter_did = rawToFriendly(raw)
     cred_def_id = ':'.join([submitter_did, '03', 'CL', '1'])
     def_revoc_id = ':'.join(
         [submitter_did, '04', cred_def_id, 'CL_ACCUM', 'reg1'])
     return def_revoc_id
Example #23
0
 def new(cls, prev, seq, counterparty, m, vk, sk, nonce=None):
     # type: (str, int, str, str, str, str, str) -> pb.TxBlock
     if nonce is None:
         nonce = libnacl.randombytes(32)
     inner = pb.TxBlock.Inner(prev=prev, seq=seq, counterparty=counterparty, nonce=nonce, m=m)
     s = Signature.new(vk, sk, libnacl.crypto_hash_sha256(inner.SerializeToString()))
     return cls(pb.TxBlock(inner=inner, s=s.pb))
Example #24
0
def testPutPreRotationIsEmpty(client):
    seed = libnacl.randombytes(libnacl.crypto_sign_SEEDBYTES)
    vk, sk, did, body = h.genDidHistory(seed, signer=0, numSigners=2)

    headers = {"Signature": 'signer="{0}"'.format(h.signResource(body, sk))}

    client.simulate_post(HISTORY_BASE_PATH, body=body,
                         headers=headers)  # Add did to database

    body = json.loads(body)
    body['changed'] = "2000-01-01T00:00:02+00:00"
    body['signer'] = 1
    body['signers'].append("")

    headers = {
        "Signature":
        'signer="{0}"; rotation="{1}"'.format(
            h.signResource(json.dumps(body, ensure_ascii=False).encode(), sk),
            h.signResource(json.dumps(body, ensure_ascii=False).encode(), sk))
    }

    exp_result = {
        "title": "Validation Error",
        "description": "signers keys cannot be empty."
    }

    verifyRequest(client.simulate_put,
                  "{0}/{1}".format(HISTORY_BASE_PATH, did),
                  body,
                  headers,
                  exp_result=exp_result,
                  exp_status=falcon.HTTP_400)
Example #25
0
def testFullSigning():
    # stored securely/privately
    seed = randombytes(32)

    # generates key pair based on seed
    sk = SigningKey(seed=seed)

    # helper for signing
    signer = Signer(sk)

    # this is the public key used to verify signatures (securely shared before-hand with recipient)
    verkey = signer.verhex

    # the message to be signed
    msg = b'1234'

    # the signature
    sig = signer.signature(msg)

    # helper for verification
    vr = Verifier(verkey)

    # verification
    isVerified = vr.verify(sig, msg)

    assert isVerified
Example #26
0
    def testGet(self, race_client):
        seed = libnacl.randombytes(libnacl.crypto_sign_SEEDBYTES)
        vk, sk, did, body = eddsa.genDidHistory(seed, signer=0, numSigners=2)
        vk = h.bytesToStr64u(vk)

        signature = eddsa.signResource(body, sk)

        headers = {"Signature": 'signer="{0}"'.format(signature)}

        race_client.simulate_post(HISTORY_BASE_PATH,
                                  body=body,
                                  headers=headers)

        response = race_client.simulate_get("{}/{}".format(
            EVENTS_BASE_PATH, did))

        exp_result = [[{
            "event": json.loads(body.decode()),
            "signatures": {
                "signer": signature
            }
        }]]

        assert response.status == falcon.HTTP_200
        assert json.loads(response.content) == exp_result
Example #27
0
    def generate(cls):
        """
        Generates a random :class:`~PrivateKey` object

        :rtype: :class:`~PrivateKey`
        """
        return cls(libnacl.randombytes(PrivateKey.SIZE), encoder=encoding.RawEncoder)
Example #28
0
 def _rand_data(self):
     raw = libnacl.randombytes(16)
     submitter_did = rawToFriendly(raw)
     cred_def_id = ':'.join([submitter_did, '03', 'CL', str(random.randint(1, 100))])
     def_revoc_id = ':'.join([submitter_did, '04', cred_def_id, 'CL_ACCUM', 'reg1'])
     entry_revoc_id = ':'.join([submitter_did, '05', def_revoc_id])
     return entry_revoc_id
Example #29
0
    def sign(self, data: bytes, nonce: Optional[Nonce] = None) -> Signature:
        """
        Sign data using the Montgomery private key stored in this XEdDSA instance.

        Args:
            data: The data to sign.
            nonce: The nonce to use while signing. If omitted or set to :obj:`None`, a nonce is generated.

        Returns:
            The signature of the data, not including the data itself.

        Raises:
            MissingKeyException: If the Montgomery private key is not available.
        """

        if self.__mont_priv is None:
            raise MissingKeyException(
                "Cannot sign, the Montgomery private key is not available.")

        if nonce is None:
            nonce = libnacl.randombytes(64)

        if len(nonce) != 64:
            raise ValueError("The nonce must consist of 64 bytes if given.")

        ed_priv, ed_pub = self._mont_priv_to_ed_pair(self.__mont_priv)

        return self._sign(data, nonce, ed_priv, ed_pub)
Example #30
0
def testPutUnchangedSignerField(client):
    # send updated history with new public key but unchanged signer field
    seed = libnacl.randombytes(libnacl.crypto_sign_SEEDBYTES)
    vk, sk, did, body = eddsa.genDidHistory(seed, signer=0, numSigners=2)
    vk = h.bytesToStr64u(vk)

    headers = {
        "Signature":
        'signer="{0}"; rotation="{1}"'.format(eddsa.signResource(body, sk),
                                              eddsa.signResource(body, sk))
    }

    # send inception event
    client.simulate_post(HISTORY_BASE_PATH, body=body,
                         headers=headers)  # Add did to database

    body = json.loads(body)
    body['changed'] = "2000-01-01T00:00:02+00:00"
    body['signer'] = 1
    body['signers'].append(vk)

    headers = {
        "Signature":
        'signer="{0}"; rotation="{1}"'.format(
            eddsa.signResource(
                json.dumps(body, ensure_ascii=False).encode(), sk),
            eddsa.signResource(
                json.dumps(body, ensure_ascii=False).encode(), sk))
    }

    # rotate once
    client.simulate_put("{0}/{1}".format(HISTORY_BASE_PATH, did),
                        body=json.dumps(body).encode(),
                        headers=headers)

    # Add new pre-rotated key but don't update signer field
    body['signers'].append(vk)
    body['changed'] = "2000-01-01T00:00:03+00:00"

    headers = {
        "Signature":
        'signer="{0}"; rotation="{1}"'.format(
            eddsa.signResource(
                json.dumps(body, ensure_ascii=False).encode(), sk),
            eddsa.signResource(
                json.dumps(body, ensure_ascii=False).encode(), sk))
    }

    exp_result = {
        "title": "Validation Error",
        "description": "signer field must be one greater than previous."
    }

    verifyRequest(client.simulate_put,
                  "{0}/{1}".format(HISTORY_BASE_PATH, did),
                  body,
                  headers,
                  exp_result=exp_result,
                  exp_status=falcon.HTTP_400)
Example #31
0
File: urc.py Project: suqdiq/urc.py
def nacl_keygen(seed=None):
    """
    generate nacl keypair
    """
    if not seed:
        seed = libnacl.randombytes(libnacl.crypto_sign_SEEDBYTES)
    sk, vk = libnacl.crypto_sign_seed_keypair(seed)
    return sk, vk, seed
Example #32
0
def testSendNymFailsIfIdentifierSizeIs15Bytes(looper, sdk_pool_handle,
                                              txnPoolNodeSet, nym_request,
                                              sdk_wallet_trustee):
    parameters = {'dest': rawToFriendly(randombytes(15)), 'role': TRUST_ANCHOR}
    nym_request[OPERATION].update(parameters)
    request_couple = sdk_sign_and_send_prepared_request(
        looper, sdk_wallet_trustee, sdk_pool_handle, json.dumps(nym_request))
    sdk_get_bad_response(looper, [request_couple], RequestNackedException, '')
Example #33
0
 def _rand_data(self):
     raw = libnacl.randombytes(16)
     target_did = self.rawToFriendly(raw)
     schema_marker = '02'
     name = super()._rand_data()
     version = '1.0'
     schema_id = ':'.join([target_did, schema_marker, name, version])
     return schema_id
Example #34
0
def testSendAttribFailsForHashLongerThanSha256(
        looper, sdk_pool_handle, sdk_wallet_trustee):
    new_wallet = sdk_add_new_nym(looper, sdk_pool_handle, sdk_wallet_trustee)
    parameters = None
    with pytest.raises(RequestNackedException) as e:
        sdk_add_attribute_and_check(looper, sdk_pool_handle, new_wallet, parameters,
                                    xhash=hexlify(randombytes(33)).decode())
    e.match('not a valid hash')
Example #35
0
def testSendNymFailsIfIdentifierSizeIs17Bytes(looper, sdk_pool_handle,
                                              txnPoolNodeSet, nym_request,
                                              sdk_wallet_trustee):
    parameters = {'dest': rawToFriendly(randombytes(17)), 'role': ENDORSER}
    nym_request[OPERATION].update(parameters)
    request_couple = sdk_sign_and_send_prepared_request(
        looper, sdk_wallet_trustee, sdk_pool_handle, json.dumps(nym_request))
    sdk_get_and_check_replies(looper, [request_couple])
Example #36
0
 def _rand_data(self):
     raw = libnacl.randombytes(16)
     origin = self.rawToFriendly(raw)
     cred_def_marker = '03'
     signature_type = 'CL'
     schema_id = '1'
     cred_def_id = ':'.join([origin, cred_def_marker, signature_type, schema_id])
     return cred_def_id
Example #37
0
    def test_randombytes(self):
        'copied from libsodium default/randombytes.c'

        data = libnacl.randombytes(65536)

        freq = {x: 1 for x in data}

        self.assertEqual(256, len(freq))
        self.assertTrue(all(freq.values()))
Example #38
0
    def randomStr(size):
        if not isinstance(size, int):
            raise PlenumTypeError('size', size, int)
        if not size > 0:
            raise PlenumValueError('size', size, '> 0')
        # Approach 1
        rv = randombytes(size // 2).hex()

        return rv if size % 2 == 0 else rv + hex(randombytes_uniform(15))[-1]
Example #39
0
def testSimpleSigning():
    sik = SigningKey(randombytes(32))
    sigkey = sik._signing_key
    assert len(sigkey) == 64  # why is a signing key 64 bytes and not 32?
    verkey = sik.verify_key._key
    assert len(verkey) == 32
    msg = b'1234'
    cmsg = crypto_sign(msg, sigkey)
    dmsg = crypto_sign_open(cmsg, verkey)
    assert msg == dmsg
Example #40
0
    def generate(cls):
        """
        Generates a random :class:`~SigningKey` object.

        :rtype: :class:`~SigningKey`
        """
        return cls(
            libnacl.randombytes(libnacl.crypto_sign_SEEDBYTES),
            encoder=encoding.RawEncoder,
        )
Example #41
0
 def nonce(self):
     '''
     Generate a safe nonce value (safe assuming only this method is used to
     create nonce values)
     '''
     now = str(time.time() * 1000000)
     nonce = '{0}{1}'.format(
                     libnacl.randombytes(Box.NONCE_SIZE - len(now)),
                     now)
     return nonce
def testSendNymFailsIfIdentifierSizeIs15Bytes(
        be, do, poolNodesStarted, trusteeCli):

    parameters = {
        'dest': rawToFriendly(randombytes(15)),
        'role': Roles.TRUST_ANCHOR.name
    }

    be(trusteeCli)
    do('send NYM dest={dest} role={role}',
       mapper=parameters, expect=ERROR, within=2)
Example #43
0
def uuid(size=16):
    '''
    Generate univerally unique id hex string with size characters
    Timebased with random bytes
    Minimum size is 16
    '''
    size = max(int(size), 16)
    front =  "{0:0x}".format(int(time.time() * 1000000)) # microseconds
    extra = size - len(front)
    back = binascii.hexlify(libnacl.randombytes(extra // 2 + extra % 2))
    return ((front + back)[:size])
Example #44
0
 def __init__(self, seed=None):
     '''
     Create a signing key, if not seed it supplied a keypair is generated
     '''
     if seed:
         if len(seed) != libnacl.crypto_sign_SEEDBYTES:
             raise ValueError('Invalid seed bytes')
         self.vk, self.sk = libnacl.crypto_sign_seed_keypair(seed)
     else:
         seed = libnacl.randombytes(libnacl.crypto_sign_SEEDBYTES)
         self.vk, self.sk = libnacl.crypto_sign_seed_keypair(seed)
     self.seed = seed
def testSendAttribFailsForHashLongerThanSha256(
        be, do, poolNodesStarted, trusteeCli):

    uuidIdentifier = createUuidIdentifier()
    addNym(be, do, trusteeCli, idr=uuidIdentifier)

    parameters = {
        'dest': uuidIdentifier,
        'hash': hexlify(randombytes(33)).decode()
    }

    be(trusteeCli)
    do('send ATTRIB dest={dest} hash={hash}',
       mapper=parameters, expect=ERROR, within=2)
def testSendAttribFailsIfRawIsHex(
        be, do, poolNodesStarted, trusteeCli):

    uuidIdentifier = createUuidIdentifier()
    addNym(be, do, trusteeCli, idr=uuidIdentifier)

    parameters = {
        'dest': uuidIdentifier,
        'raw': hexlify(randombytes(32)).decode()
    }

    be(trusteeCli)
    do('send ATTRIB dest={dest} raw={raw}',
       mapper=parameters, expect=INVALID_SYNTAX, within=2)
Example #47
0
    async def gen_nym(self):
        # print("gen_signed_nym")
        if self._closing is True:
            return

        raw = libnacl.randombytes(16)
        did = self.rawToFriendly(raw)
        req = ""

        self._stat.preparing(did)
        try:
            req = await ledger.build_nym_request(self._test_did, did, None, None, None)
            self._stat.prepared(did)
        except Exception as e:
            self._stat.reply(did, e)
        return (did, req)
Example #48
0
def uuid(size=16):
    '''
    Generate universally unique id hex string with size characters
    Timebased with random bytes
    Minimum size is 16

    Uses time.clock instead of time.time on windows.
    Tests of rapid uuid generation fail to generate unique uuids
    on Windows with time.time().
    See http://www.pythoncentral.io/measure-time-in-python-time-time-vs-time-clock/
    for discussion.
    '''
    size = max(int(size), 16)
    if sys.platform == 'win32':
        front = ns2b("{0:0x}".format(int(time.clock() * 1000000)))  # microseconds
    else:
        front = ns2b("{0:0x}".format(int(time.time() * 1000000)))  # microseconds
    extra = size - len(front)
    back = binascii.hexlify(libnacl.randombytes(extra // 2 + extra % 2))
    return ((front + back)[:size]).decode('ISO-8859-1')
Example #49
0
def testSimpleSigningIsHasConsistentVerKey():
    seed = randombytes(32)

    sik = SigningKey(seed)
    sigkey = sik._signing_key
    verkey = sik.verify_key._key

    msg = b'1234'
    cmsg = crypto_sign(msg, sigkey)
    dmsg = crypto_sign_open(cmsg, verkey)
    cmsg2 = crypto_sign(msg, sigkey)
    dmsg2 = crypto_sign_open(cmsg2, verkey)
    assert msg == dmsg
    assert dmsg == dmsg2

    sik2 = SigningKey(seed)
    sigkey2 = sik2._signing_key
    verkey2 = sik2.verify_key._key

    assert sigkey2 == sigkey
    assert verkey2 == verkey
Example #50
0
    def __init__(self, identifier=None, seed=None, alias=None):
        """
        Initialize the signer with an identifier and a seed.

        :param identifier: some identifier that directly or indirectly
        references this client
        :param seed: the seed used to generate a signing key.
        """

        # should be stored securely/privately
        self.seed = seed if seed else randombytes(32)

        # generates key pair based on seed
        self.sk = SigningKey(seed=self.seed)

        # helper for signing
        self.naclSigner = NaclSigner(self.sk)

        Signer.__init__(self)
        DidIdentity.__init__(
            self, identifier, rawVerkey=self.naclSigner.verraw)

        self._alias = alias
Example #51
0
def rand_nonce():
    '''
    Generates and returns a random bytestring of the size defined in libsodium
    as crypto_box_NONCEBYTES
    '''
    return libnacl.randombytes(libnacl.crypto_box_NONCEBYTES)
Example #52
0
def salsa_key():
    '''
    Generates a salsa2020 key
    '''
    return libnacl.randombytes(libnacl.crypto_secretbox_KEYBYTES)
Example #53
0
 def random_string(self, sz: int) -> str:
     assert (sz > 0), "Expected random string size cannot be less than 1"
     rv = libnacl.randombytes(sz // 2).hex()
     return rv if sz % 2 == 0 else rv + hex(libnacl.randombytes_uniform(15))[-1]
Example #54
0
def createUuidIdentifier():
    return rawToFriendly(randombytes(16))
Example #55
0
def rand_aead_nonce():
    '''
    Generates and returns a random bytestring of the size defined in libsodium
    as crypto_aead_aes256gcm_NPUBBYTES and crypto_aead_chacha20poly1305_ietf_NPUBBYTES
    '''
    return libnacl.randombytes(libnacl.crypto_aead_aes256gcm_NPUBBYTES)
Example #56
0
def aead_key():
    '''
    Generates an AEAD key (both implementations use the same size)
    '''
    return libnacl.randombytes(libnacl.crypto_aead_aes256gcm_KEYBYTES)
Example #57
0
 def nonce(self):
     '''
     Generate a safe nonce value (safe assuming only this method is used to
     create nonce values)
     '''
     return libnacl.randombytes(Box.NONCE_SIZE)