Ejemplo n.º 1
0
    def create(self, cb, pwd, user, host, char_classes, size=0):
        if set(char_classes) - {'u', 'l', 's', 'd'}:
            raise ValueError("error: rules can only contain ulsd.")
        try:
            size = int(size)
        except:
            raise ValueError("error: size has to be integer.")
        self.namesite = {'name': user, 'site': host}

        rules = sum(1 << i for i, c in enumerate(('u', 'l', 's', 'd'))
                    if c in char_classes)
        # pack rule
        rule = struct.pack('>H', (rules << 7) | (size & 0x7f))
        # encrypt rule
        sk = self.getkey()
        rk = pysodium.crypto_generichash(sk, self.getsalt())
        nonce = pysodium.randombytes(pysodium.crypto_secretbox_NONCEBYTES)
        rule = nonce + pysodium.crypto_secretbox(rule, nonce, rk)

        b, c = sphinxlib.challenge(pwd)
        message = b''.join([
            CREATE,
            self.getid(host, user), c, rule,
            pysodium.crypto_sign_sk_to_pk(sk)
        ])
        self.doSphinx(message, b, pwd, cb)
Ejemplo n.º 2
0
def _blake2b_ed25519_deploy_data(current_height,
                                 bytecode,
                                 privatekey,
                                 receiver=None):
    sender = get_sender(private_key, True)
    print(sender)
    nonce = get_nonce(sender)
    print("nonce is {}".format(nonce))

    tx = Transaction()
    tx.valid_until_block = current_height + 88
    tx.nonce = nonce
    if receiver is not None:
        tx.to = receiver
    tx.data = hex2bytes(bytecode)

    message = _blake2b(tx.SerializeToString())
    print("msg is {}".format(message))
    sig = pysodium.crypto_sign_detached(message, hex2bytes(privatekey))
    print("sig {}".format(binascii.b2a_hex(sig)))

    pubkey = pysodium.crypto_sign_sk_to_pk(hex2bytes(privatekey))
    print("pubkey is {}".format(binascii.b2a_hex(pubkey)))
    signature = binascii.hexlify(sig[:]) + binascii.hexlify(pubkey[:])
    print("signature is {}".format(signature))

    unverify_tx = UnverifiedTransaction()
    unverify_tx.transaction.CopyFrom(tx)
    unverify_tx.signature = hex2bytes(signature)
    unverify_tx.crypto = Crypto.Value('SECP')

    print("unverify_tx is {}".format(
        binascii.hexlify(unverify_tx.SerializeToString())))
    return binascii.hexlify(unverify_tx.SerializeToString())
Ejemplo n.º 3
0
    def from_secret_key(cls, secret_key: bytes, curve=b'ed'):
        """
        Creates a key object from a secret exponent.
        :param secret_key: secret exponent or seed
        :param curve: an elliptic curve used, default is ed25519
        """
        # Ed25519
        if curve == b'ed':
            # Dealing with secret key or seed?
            if len(secret_key) == 64:
                public_key = pysodium.crypto_sign_sk_to_pk(sk=secret_key)
            else:
                public_key, secret_key = pysodium.crypto_sign_seed_keypair(seed=secret_key)
        # Secp256k1
        elif curve == b'sp':
            sk = secp256k1.PrivateKey(secret_key)
            public_key = sk.pubkey.serialize()
        # P256
        elif curve == b'p2':
            pk = get_public_key(bytes_to_int(secret_key), curve=P256)
            public_key = SEC1Encoder.encode_public_key(pk)
        else:
            assert False

        return cls(public_key, secret_key, curve=curve)
Ejemplo n.º 4
0
    def from_secret_exponent(cls,
                             secret_exponent: bytes,
                             curve=b'ed',
                             activation_code=None):
        """
        Creates a key object from a secret exponent.
        :param secret_exponent: secret exponent or seed
        :param curve: b'sp' for Secp251k1, b'p2' for P256/Secp256r1, b'ed' for Ed25519 (default)
        :param activation_code: secret for initializing account balance
        """
        # Ed25519
        if curve == b'ed':
            # Dealing with secret exponent or seed?
            if len(secret_exponent) == 64:
                public_point = pysodium.crypto_sign_sk_to_pk(
                    sk=secret_exponent)
            else:
                public_point, secret_exponent = pysodium.crypto_sign_seed_keypair(
                    seed=secret_exponent)
        # Secp256k1
        elif curve == b'sp':
            sk = secp256k1.PrivateKey(secret_exponent)
            public_point = sk.pubkey.serialize()
        # P256
        elif curve == b'p2':
            pk = get_public_key(bytes_to_int(secret_exponent), curve=P256)
            public_point = SEC1Encoder.encode_public_key(pk)
        else:
            assert False

        return cls(public_point,
                   secret_exponent,
                   curve=curve,
                   activation_code=activation_code)
Ejemplo n.º 5
0
 def __init__(self, file):
   self._logger = logging.getLogger(__name__)
   if (isinstance(file, (str))):
     if (not path.exists(file)):
       self.__init_cryptokey(file)
     with open(file, 'rb') as file:
       data = file.read()
   else:
     data = file.read()
   datalen = len(data)
   # this should be legacy
   contents = None
   while len(data) and contents is None:
     try:
       contents = msgpack.unpackb(data,raw=True)
     except msgpack.exceptions.ExtraData:
       data = data[:-1]
   if len(data) != datalen:
     self._logger.warning("Cryptokey file had extraneous bytes at end, attempting load anyways.")
   self.__eklock = Lock()
   self.__esk = {}
   self.__epk = {}
   self.__ssk = contents[0]
   self.__spk = pysodium.crypto_sign_sk_to_pk(self.__ssk)
   self.__ek = contents[1]
Ejemplo n.º 6
0
 def __init_cryptokey(self, file):
   self._logger.warning("Initializing new CryptoKey file %s", file)
   pk,sk = pysodium.crypto_sign_keypair()
   self._logger.warning("  Public key: %s", pysodium.crypto_sign_sk_to_pk(sk).hex())
   with open(file, "wb") as f:
     f.write(msgpack.packb([sk,pysodium.randombytes(pysodium.crypto_secretbox_KEYBYTES)], use_bin_type=True))
   self._logger.warning("  CryptoKey Initialized. Provisioning required for successful operation.")
Ejemplo n.º 7
0
def getkey(keydir):
    datadir = os.path.expanduser(keydir)
    esk = None
    try:
        with open(datadir + 'server-key', 'rb') as fd:
            esk = fd.read(pysodium.crypto_sign_SECRETKEYBYTES)
        with open(datadir + 'server-xkey', 'rb') as fd:
            xsk = fd.read(pysodium.crypto_box_SECRETKEYBYTES)
        with open(datadir + 'server-xkey.pub', 'rb') as fd:
            xpk = fd.read(pysodium.crypto_box_PUBLICKEYBYTES)
        return esk, xsk, xpk
    except FileNotFoundError:
        print("no server key found, generating...")
        if not os.path.exists(datadir):
            os.mkdir(datadir, 0o700)
        if esk is None:
            epk, esk = pysodium.crypto_sign_keypair()
        else:
            epk = pysodium.crypto_sign_sk_to_pk(esk)
        xsk = pysodium.crypto_sign_sk_to_box_sk(esk)
        xpk = pysodium.crypto_sign_pk_to_box_pk(epk)
        with open(datadir + 'server-key', 'wb') as fd:
            os.fchmod(fd.fileno(), 0o600)
            fd.write(esk)
        with open(datadir + 'server-key.pub', 'wb') as fd:
            fd.write(epk)
        with open(datadir + 'server-xkey', 'wb') as fd:
            os.fchmod(fd.fileno(), 0o600)
            fd.write(xsk)
        with open(datadir + 'server-xkey.pub', 'wb') as fd:
            fd.write(xpk)
        print("please share `%s` with all clients" %
              (datadir + 'server-key.pub'))
        return esk, xsk, xpk
Ejemplo n.º 8
0
def test_sk_to_pk():
    #pk, sk = pysodium.crypto_box_keypair()

    pk, sk = pysodium.crypto_sign_keypair()

    pk2 = pysodium.crypto_sign_sk_to_pk(sk)

    print(pk == pk2)
Ejemplo n.º 9
0
def _blake2b_ed25519_deploy_data(current_height,
                                 bytecode,
                                 value,
                                 quota,
                                 privatekey,
                                 version,
                                 receiver=None):
    sender = get_sender(private_key, True)
    logger.debug(sender)
    nonce = get_nonce()
    logger.debug("nonce is {}".format(nonce))

    tx = Transaction()
    tx.valid_until_block = current_height + 88
    tx.nonce = nonce
    tx.version = version
    if version == 0:
        chainid = get_chainid()
        logger.info("version is {}".format(version))
        logger.info("chainid is {}".format(chainid))
        tx.chain_id = chainid
    elif version < 3:
        chainid = get_chainid_v1()
        logger.info("version is {}".format(version))
        logger.info("chainid_v1 is {}".format(chainid))
        tx.chain_id_v1 = chainid.to_bytes(32, byteorder='big')
    else:
        logger.error("unexpected version {}".format(version))
    if receiver is not None:
        if version == 0:
            tx.to = receiver
        elif version < 3:
            tx.to_v1 = hex2bytes(receiver)
        else:
            logger.error("unexpected version {}".format(version))
    tx.data = hex2bytes(bytecode)
    tx.value = value.to_bytes(32, byteorder='big')
    tx.quota = quota

    message = _blake2b(tx.SerializeToString())
    logger.debug("blake2b msg")
    sig = pysodium.crypto_sign_detached(message, hex2bytes(privatekey))
    logger.debug("sig {}".format(binascii.b2a_hex(sig)))

    pubkey = pysodium.crypto_sign_sk_to_pk(hex2bytes(privatekey))
    logger.debug("pubkey is {}".format(binascii.b2a_hex(pubkey)))
    signature = binascii.hexlify(sig[:]) + binascii.hexlify(pubkey[:])
    logger.debug("signature is {}".format(signature))

    unverify_tx = UnverifiedTransaction()
    unverify_tx.transaction.CopyFrom(tx)
    unverify_tx.signature = hex2bytes(signature)
    unverify_tx.crypto = Crypto.Value('DEFAULT')

    logger.info("unverify_tx is {}".format(
        binascii.hexlify(unverify_tx.SerializeToString())))
    return binascii.hexlify(unverify_tx.SerializeToString())
Ejemplo n.º 10
0
    def data_received(self, data):
        if verbose: print('Data received: ', data, file=sys.stderr)

        try:
            data = pysodium.crypto_sign_open(data, self.handler.getserverkey())
        except ValueError:
            raise ValueError('invalid signature.\nabort')

        if data != b'ok' and (data[:-42] == b'fail' or
                              len(data) != sphinxlib.DECAF_255_SER_BYTES + 90):
            raise ValueError('fail')

        if not self.b:
            self.cb()
            return

        rwd = sphinxlib.finish(self.pwd, self.b,
                               data[:sphinxlib.DECAF_255_SER_BYTES])

        if self.handler.namesite is not None:
            if self.handler.namesite['name'].encode() not in self.handler.list(
                    self.handler.namesite['site']):
                self.handler.cacheuser(self.handler.namesite)

        rule = data[sphinxlib.DECAF_255_SER_BYTES:]
        esk = self.handler.getkey()
        sk = pysodium.crypto_sign_sk_to_box_sk(esk)
        epk = pysodium.crypto_sign_sk_to_pk(esk)
        pk = pysodium.crypto_sign_pk_to_box_pk(epk)
        rule = pysodium.crypto_box_seal_open(rule, pk, sk)
        if len(rule) != 42:
            raise ValueError('fail')
        rk = pysodium.crypto_generichash(self.handler.getkey(),
                                         self.handler.getsalt())
        rule = pysodium.crypto_secretbox_open(rule[24:], rule[:24], rk)
        rule = struct.unpack(">H", rule)[0]
        size = (rule & 0x7f)
        rule = {
            c
            for i, c in enumerate(('u', 'l', 's', 'd'))
            if (rule >> 7) & (1 << i)
        }
        self.cb(bin2pass.derive(rwd, rule, size).decode())
Ejemplo n.º 11
0
        )
        print('Escrow public key:', hexlify(_ss0_escrow))
        print(nodeID + ' escrow value: ',
              hexlify(pysodium.crypto_box_seal(rb, _ss0_escrow)),
              " (key index", idx, ")")
    else:
        print(
            'No escrow key for initial shared secret. If you lose connectivity for an extended period of time, you may lose access to data unless you store the following value in a secure location:'
        )
        print(nodeID + ':', hexlify(rb), " (key index", idx, ")")

# Second, generate identify keypair and chain, and write cryptokey config file
if path.exists(nodeID + ".crypto"):
    with open(nodeID + ".crypto", "rb+") as f:
        sk, rb = msgpack.unpackb(f.read(), raw=True)
        pk = pysodium.crypto_sign_sk_to_pk(sk)
        f.seek(0, 0)
        f.write(msgpack.packb([sk, rb], use_bin_type=True))
        f.flush()
        f.truncate()
else:
    pk, sk = pysodium.crypto_sign_keypair()
    with open(nodeID + ".crypto", "wb") as f:
        f.write(
            msgpack.packb(
                [sk,
                 pysodium.randombytes(pysodium.crypto_secretbox_KEYBYTES)],
                use_bin_type=True))

poison = [['usages', _usages[key]]]
if len(topics) > 0:
Ejemplo n.º 12
0
 def test_crypto_sign_sk_to_pk(self):
     pk, sk = pysodium.crypto_sign_keypair()
     pk2 = pysodium.crypto_sign_sk_to_pk(sk)
     self.assertEqual(pk, pk2)
Ejemplo n.º 13
0
 def test_crypto_sign_sk_to_pk(self):
     pk, sk = pysodium.crypto_sign_keypair()
     pk2 = pysodium.crypto_sign_sk_to_pk(sk)
     self.assertEqual(pk, pk2)
Ejemplo n.º 14
0
    if sys.argv[1] == 'create':
        # needs pubkey, id, challenge, sig(id)
        # returns output from ./response | fail
        if set(sys.argv[4]) - {'u', 'l', 's', 'd'}:
            print("error: rules can only contain ulsd.")
            usage()
        size = 0
        try:
            size = int(sys.argv[5])
        except:
            print("error: size has to be integer.")
            usage()
        saverules(datadir, id, sys.argv[4], size)
        b, c = challenge()
        message = [CREATE, id, c, pysodium.crypto_sign_sk_to_pk(sk)]
    elif sys.argv[1] == 'get':
        # needs id, challenge, sig(id)
        b, c = challenge()
        message = [GET, id, c]
        # returns output from ./response | fail
    elif sys.argv[1] == 'change':
        # needs id, challenge, sig(id)
        b, c = challenge()
        message = [CHANGE, id, c]
        # changes stored secret
        # returns output from ./response | fail
    elif sys.argv[1] == 'delete':
        # needs id, sig(id)
        message = [DELETE, id]
    else:
Ejemplo n.º 15
0
def signature_keys_generate_0 (_local_sign_priv_key) :
	
	_local_sign_pub_key = pysodium.crypto_sign_sk_to_pk (_local_sign_priv_key)
	
	return _local_sign_pub_key, _local_sign_priv_key