Exemple #1
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
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
def keysAndNames():
    alphaSigner = Signer()
    betaSigner = Signer()
    alphaPrikey = ed25519SkToCurve25519(alphaSigner.keyraw)
    betaPrikey = ed25519SkToCurve25519(betaSigner.keyraw)
    alphaPubkey = ed25519PkToCurve25519(alphaSigner.verraw)
    betaPubkey = ed25519PkToCurve25519(betaSigner.verraw)
    alphaName = 'alpha'
    betaName = 'beta'
    return alphaSigner.keyhex, alphaPrikey, alphaSigner.verhex, alphaPubkey, \
           alphaName, betaSigner.keyhex, betaPrikey, betaSigner.verhex, \
           betaPubkey, betaName
Exemple #4
0
def initLocalKeep(name, baseDir, pkseed, sigseed, override=False):
    """
    Initialize RAET local keep. Write local role data to file.

    :param name: name of the node
    :param baseDir: base directory
    :param pkseed: seed to generate public and private key pair
    :param sigseed: seed to generate signing and verification key pair
    :param override: overwrite the local role.json file if already exists
    :return: tuple(public key, verification key)
    """
    rolePath = os.path.join(baseDir, name, "role", "local", "role.json")
    if os.path.isfile(rolePath):
        if not override:
            raise FileExistsError("Keys exists for local role {}".format(name))

    if not isinstance(pkseed, bytes):
        pkseed = pkseed.encode()
    if not isinstance(sigseed, bytes):
        sigseed = sigseed.encode()

    priver = Privateer(pkseed)
    signer = Signer(sigseed)
    keep = RoadKeep(stackname=name, baseroledirpath=baseDir)
    prikey, pubkey = priver.keyhex, priver.pubhex
    sigkey, verkey = signer.keyhex, signer.verhex
    data = OrderedDict([("role", name), ("prihex", prikey),
                        ("sighex", sigkey)])
    keep.dumpLocalRoleData(data)
    return pubkey.decode(), verkey.decode()
Exemple #5
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
    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)

        self.verkey = hexToFriendly(hexlify(self.naclSigner.verraw))

        self._identifier = identifier or self.verkey

        self._alias = alias
Exemple #7
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')
Exemple #8
0
def getEd25519AndCurve25519Keys(seed=None):
    if seed:
        seed = cleanSeed(seed)
    signer = Signer(seed)
    sigkey, verkey = signer.keyhex, signer.verhex
    prikey, pubkey = hexlify(ed25519SkToCurve25519(signer.keyraw)), \
                     hexlify(ed25519PkToCurve25519(signer.verraw))
    return (sigkey, verkey), (prikey, pubkey)
class SimpleSigner(Signer):
    """
    A simple implementation of Signer.

    This signer creates a public key and a private key using the seed value
    provided in the constructor. It internally uses the NaclSigner to generate
    the signature and keys.
    """

    # TODO: Do we need both alias and identifier?
    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)

        self.verkey = hexToFriendly(hexlify(self.naclSigner.verraw))

        self._identifier = identifier or self.verkey

        self._alias = alias

    @property
    def alias(self) -> str:
        return self._alias

    @property
    def identifier(self) -> str:
        return self._identifier

    @property
    def seedHex(self) -> bytes:
        return hexlify(self.seed)

    def sign(self, msg: Dict) -> Dict:
        """
        Return a signature for the given message.
        """
        ser = serializeMsg(msg)
        bsig = self.naclSigner.signature(ser)
        sig = base58.b58encode(bsig)
        return sig
Exemple #10
0
class DidSigner(DidIdentity, Signer):
    """
    A simple implementation of Signer for DIDs (Distributed Identifiers).

    This signer creates a public key and a private key using the seed value
    provided in the constructor. It internally uses the NaclSigner to generate
    the signature and keys.
    """

    # TODO: Do we need both alias and identifier?
    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

    @property
    def alias(self) -> str:
        return self._alias

    @alias.setter
    def alias(self, value):
        self._alias = value

    @property
    def seedHex(self) -> bytes:
        return hexlify(self.seed)

    def sign(self, msg: Dict) -> Dict:
        """
        Return a signature for the given message.
        """
        ser = serializeMsg(msg)
        bsig = self.naclSigner.signature(ser)
        sig = base58.b58encode(bsig)
        return sig
def testKeyConversionFromEd25519ToCurve25519():
    signer = Signer()
    sk = signer.keyraw
    vk = signer.verraw
    # Check when keys are passed as raw bytes
    secretKey = ed25519SkToCurve25519(sk)
    publicKey = ed25519PkToCurve25519(vk)
    assert PrivateKey(secretKey).public_key.__bytes__() == publicKey
    assert ed25519PkToCurve25519(vk, toHex=True) == \
           hexlify(PrivateKey(secretKey).public_key.__bytes__())

    # Check when keys are passed as hex
    secretKey = ed25519SkToCurve25519(hexlify(sk))
    publicKey = ed25519PkToCurve25519(hexlify(vk))
    assert PrivateKey(secretKey).public_key.__bytes__() == publicKey
Exemple #12
0
class SimpleSigner(Signer):
    """
    A simple implementation of Signer.

    This signer creates a public key and a private key using the seed value provided in the constructor.
    It internally uses the NaclSigner to generate the signature and keys.
    """
    def __init__(self, identifier=None, 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.
        """

        # 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.verraw).decode('utf-8')

        self._identifier = identifier or self.verstr

    @property
    def identifier(self) -> str:
        return self._identifier

    def sign(self, msg: Dict) -> Dict:
        """
        Return a signature for the given message.
        """
        ser = serializeForSig(msg)
        bsig = self.naclSigner.signature(ser)
        b64sig = base64_encode(bsig)
        sig = b64sig.decode('utf-8')
        return sig
Exemple #13
0
class SimpleSigner(Signer):
    """
    A simple implementation of Signer.

    This signer creates a public key and a private key using the seed value provided in the constructor.
    It internally uses the NaclSigner to generate the signature and keys.
    """
    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')

    def sign(self, msg: Mapping) -> Mapping:
        """
        Return a signature for the given message.
        """
        ser = serializeForSig(msg)
        bsig = self.naclSigner.signature(ser)
        b64sig = base64_encode(bsig)
        sig = b64sig.decode('utf-8')
        return sig
Exemple #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)

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

        self._alias = alias
Exemple #15
0
def getLocalVerKey(roleName, baseDir=None):
    sighex = getLocalRoleKeyByName(roleName, baseDir, 'sighex')
    signer = Signer(sighex)
    return signer.verhex.decode()
Exemple #16
0
    def bootstrapTestNodesCore(config, envName, appendToLedgers,
                               domainTxnFieldOrder, ips, nodeCount,
                               clientCount, nodeNum, startingPort):

        baseDir = config.baseDir
        if not os.path.exists(baseDir):
            os.makedirs(baseDir, exist_ok=True)

        if not ips:
            ips = ['127.0.0.1'] * nodeCount
        else:
            ips = ips.split(",")
            if len(ips) != nodeCount:
                if len(ips) > nodeCount:
                    ips = ips[:nodeCount]
                else:
                    ips += ['127.0.0.1'] * (nodeCount - len(ips))

        if hasattr(config, "ENVS") and envName:
            poolTxnFile = config.ENVS[envName].poolLedger
            domainTxnFile = config.ENVS[envName].domainLedger
        else:
            poolTxnFile = config.poolTransactionsFile
            domainTxnFile = config.domainTransactionsFile

        poolLedger = Ledger(CompactMerkleTree(),
                            dataDir=baseDir,
                            fileName=poolTxnFile)

        domainLedger = Ledger(
            CompactMerkleTree(),
            serializer=CompactSerializer(fields=domainTxnFieldOrder),
            dataDir=baseDir,
            fileName=domainTxnFile)

        if not appendToLedgers:
            poolLedger.reset()
            domainLedger.reset()

        steward1Nym = None
        for num in range(1, nodeCount + 1):
            stewardName = "Steward" + str(num)
            sigseed = TestNetworkSetup.getSigningSeed(stewardName)
            verkey = Signer(sigseed).verhex
            stewardNym = TestNetworkSetup.getNymFromVerkey(verkey)
            txn = {
                TARGET_NYM: stewardNym,
                TXN_TYPE: NYM,
                ROLE: STEWARD,
                ALIAS: stewardName,
                TXN_ID: sha256(stewardName.encode()).hexdigest()
            }
            if num == 1:
                steward1Nym = stewardNym
            else:
                # The first steward adds every steward
                txn[f.IDENTIFIER.nm] = steward1Nym
            domainLedger.add(txn)

            nodeName = "Node" + str(num)
            nodePort, clientPort = startingPort + (num * 2 - 1), startingPort \
                                   + (num * 2)
            ip = ips[num - 1]
            sigseed = TestNetworkSetup.getSigningSeed(nodeName)
            if nodeNum == num:
                _, verkey = initLocalKeep(nodeName, baseDir, sigseed, True)
                verkey = verkey.encode()
                print("This node with name {} will use ports {} and {} for "
                      "nodestack and clientstack respectively".format(
                          nodeName, nodePort, clientPort))
            else:
                verkey = Signer(sigseed).verhex
            txn = {
                TARGET_NYM: TestNetworkSetup.getNymFromVerkey(verkey),
                TXN_TYPE: NODE,
                f.IDENTIFIER.nm: stewardNym,
                DATA: {
                    CLIENT_IP: ip,
                    ALIAS: nodeName,
                    CLIENT_PORT: clientPort,
                    NODE_IP: ip,
                    NODE_PORT: nodePort,
                    SERVICES: [VALIDATOR]
                },
                TXN_ID: sha256(nodeName.encode()).hexdigest()
            }
            poolLedger.add(txn)

        for num in range(1, clientCount + 1):
            clientName = "Client" + str(num)
            sigseed = TestNetworkSetup.getSigningSeed(clientName)
            verkey = Signer(sigseed).verhex
            txn = {
                f.IDENTIFIER.nm: steward1Nym,
                TARGET_NYM: TestNetworkSetup.getNymFromVerkey(verkey),
                TXN_TYPE: NYM,
                ALIAS: clientName,
                TXN_ID: sha256(clientName.encode()).hexdigest()
            }
            domainLedger.add(txn)

        poolLedger.stop()
        domainLedger.stop()
Exemple #17
0
class DidSigner(Signer):
    """
    A simple implementation of Signer for DIDs (Distributed Identifiers).

    This signer creates a public key and a private key using the seed value
    provided in the constructor. It internally uses the NaclSigner to generate
    the signature and keys.
    """

    # TODO: Do we need both alias and identifier?
    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

    @property
    def alias(self) -> str:
        return self._alias

    @alias.setter
    def alias(self, value):
        self._alias = value

    @property
    def identifier(self) -> str:
        return self._identifier

    @property
    def verkey(self) -> str:
        if self.abbreviated:
            return '~' + self._verkey
        else:
            return self._verkey

    @property
    def seedHex(self) -> bytes:
        return hexlify(self.seed)

    def sign(self, msg: Dict) -> Dict:
        """
        Return a signature for the given message.
        """
        ser = serializeMsg(msg)
        bsig = self.naclSigner.signature(ser)
        sig = base58.b58encode(bsig)
        return sig
Exemple #18
0
    def bootstrapTestNodesCore(baseDir,
                           poolTransactionsFile,
                           domainTransactionsFile,
                           domainTxnFieldOrder,
                           ips, nodeCount, clientCount,
                           nodeNum, startingPort):
        if not ips:
            ips = ['127.0.0.1'] * nodeCount
        else:
            ips = ips.split(",")
            if len(ips) != nodeCount:
                if len(ips) > nodeCount:
                    ips = ips[:nodeCount]
                else:
                    ips = ips + ['127.0.0.1'] * (nodeCount - len(ips))

        poolLedger = Ledger(CompactMerkleTree(),
                            dataDir=baseDir,
                            fileName=poolTransactionsFile)
        poolLedger.reset()

        domainLedger = Ledger(CompactMerkleTree(),
                              serializer=CompactSerializer(fields=
                                                           domainTxnFieldOrder),
                              dataDir=baseDir,
                              fileName=domainTransactionsFile)
        domainLedger.reset()

        steward1Nym = None
        for num in range(1, nodeCount + 1):
            stewardName = "Steward" + str(num)
            sigseed = TestNetworkSetup.getSigningSeed(stewardName)
            verkey = Signer(sigseed).verhex
            stewardNym = TestNetworkSetup.getNymFromVerkey(verkey)
            txn = {
                TARGET_NYM: stewardNym,
                TXN_TYPE: NYM,
                ROLE: STEWARD,
                ALIAS: stewardName,
                TXN_ID: sha256(stewardName.encode()).hexdigest()
            }
            if num == 1:
                steward1Nym = stewardNym
            else:
                # The first steward adds every steward
                txn[f.IDENTIFIER.nm] = steward1Nym
            domainLedger.add(txn)

            nodeName = "Node" + str(num)
            nodePort, clientPort = startingPort + (num * 2 - 1), startingPort \
                                   + (num * 2)
            ip = ips[num - 1]
            sigseed = TestNetworkSetup.getSigningSeed(nodeName)
            if nodeNum == num:
                _, verkey = initLocalKeep(nodeName, baseDir, sigseed, True)
                verkey = verkey.encode()
                print("This node with name {} will use ports {} and {} for "
                      "nodestack and clientstack respectively"
                      .format(nodeName, nodePort, clientPort))
            else:
                verkey = Signer(sigseed).verhex
            txn = {
                TARGET_NYM: TestNetworkSetup.getNymFromVerkey(verkey),
                TXN_TYPE: NEW_NODE,
                f.IDENTIFIER.nm: stewardNym,
                DATA: {
                    CLIENT_IP: ip,
                    ALIAS: nodeName,
                    CLIENT_PORT: clientPort,
                    NODE_IP: ip,
                    NODE_PORT: nodePort
                },
                TXN_ID: sha256(nodeName.encode()).hexdigest()
            }
            poolLedger.add(txn)

        for num in range(1, clientCount + 1):
            clientName = "Client" + str(num)
            sigseed = TestNetworkSetup.getSigningSeed(clientName)
            verkey = Signer(sigseed).verhex
            txn = {
                f.IDENTIFIER.nm: steward1Nym,
                TARGET_NYM: TestNetworkSetup.getNymFromVerkey(verkey),
                TXN_TYPE: NYM,
                ALIAS: clientName,
                TXN_ID: sha256(clientName.encode()).hexdigest()
            }
            domainLedger.add(txn)

        poolLedger.stop()
        domainLedger.stop()