当前位置: 首页>>代码示例>>Python>>正文


Python SigningKey.generate方法代码示例

本文整理汇总了Python中nacl.signing.SigningKey.generate方法的典型用法代码示例。如果您正苦于以下问题:Python SigningKey.generate方法的具体用法?Python SigningKey.generate怎么用?Python SigningKey.generate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在nacl.signing.SigningKey的用法示例。


在下文中一共展示了SigningKey.generate方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: add_new_channel

# 需要导入模块: from nacl.signing import SigningKey [as 别名]
# 或者: from nacl.signing.SigningKey import generate [as 别名]
    def add_new_channel(self, nA, nB):
        a_signkey = SigningKey.generate()
        a_chankey = PrivateKey.generate()
        a_CIDkey = os.urandom(32)
        a_transports = nA.agent.individualize_transports(nA.agent.get_transports())

        b_signkey = SigningKey.generate()
        b_chankey = PrivateKey.generate()
        b_CIDkey = os.urandom(32)
        b_transports = nB.agent.individualize_transports(nB.agent.get_transports())

        a_rec = { "channel_pubkey": a_chankey.public_key.encode().encode("hex"),
                  "CID_key": a_CIDkey.encode("hex"),
                  "transports": a_transports.values(),
                  }

        b_rec = { "channel_pubkey": b_chankey.public_key.encode().encode("hex"),
                  "CID_key": b_CIDkey.encode("hex"),
                  "transports": b_transports.values(),
                  }

        q = ("INSERT INTO addressbook"
             " (petname, acked, next_outbound_seqnum,"
             "  my_signkey,"
             "  their_channel_record_json,"
             "  my_CID_key, next_CID_token,"
             "  highest_inbound_seqnum,"
             "  my_old_channel_privkey, my_new_channel_privkey,"
             "  they_used_new_channel_key, their_verfkey)"
             " VALUES(?,?,?,?,?,?,?,?,?,?,?,?)")

        vA=("petname-from-A", 1, 1,
            a_signkey.encode().encode("hex"),
            json.dumps(b_rec),
            a_CIDkey.encode("hex"), None,
            0,
            a_chankey.encode().encode("hex"),
            a_chankey.encode().encode("hex"),
            0, b_signkey.verify_key.encode().encode("hex"),
            )

        vB=("petname-from-A", 1, 1,
            b_signkey.encode().encode("hex"),
            json.dumps(a_rec),
            b_CIDkey.encode("hex"), None,
            0,
            b_chankey.encode().encode("hex"),
            b_chankey.encode().encode("hex"),
            0, a_signkey.verify_key.encode().encode("hex"),
            )

        nA.db.execute(q, vA)
        nA.db.commit()
        nB.db.execute(q, vB)
        nA.db.commit()

        entA = nA.db.execute("SELECT * FROM addressbook").fetchone()
        entB = nB.db.execute("SELECT * FROM addressbook").fetchone()
        return entA, entB
开发者ID:warner,项目名称:petmail,代码行数:61,代码来源:common.py

示例2: test_verify_with_prefix

# 需要导入模块: from nacl.signing import SigningKey [as 别名]
# 或者: from nacl.signing.SigningKey import generate [as 别名]
    def test_verify_with_prefix(self):
        sk = SigningKey.generate()
        vk = sk.verify_key
        m = "body"
        prefix = "prefix:"
        sk2 = SigningKey.generate()

        sm1 = sk.sign(prefix+m)
        sm2 = sk.sign("not the prefix"+m)
        sm3 = sk2.sign(prefix+m)

        self.failUnlessEqual(util.verify_with_prefix(vk, sm1, prefix), m)
        self.failUnlessRaises(errors.BadSignatureError,
                              util.verify_with_prefix, vk, sm2, prefix)
        self.failUnlessRaises(CryptoError,
                              util.verify_with_prefix, vk, sm3, prefix)
开发者ID:ggozad,项目名称:petmail,代码行数:18,代码来源:test_util.py

示例3: test_wrong_types

# 需要导入模块: from nacl.signing import SigningKey [as 别名]
# 或者: from nacl.signing.SigningKey import generate [as 别名]
def test_wrong_types():
    sk = SigningKey.generate()

    check_type_error("SigningKey must be created from a 32 byte seed", SigningKey, 12)
    check_type_error("SigningKey must be created from a 32 byte seed", SigningKey, sk)
    check_type_error("SigningKey must be created from a 32 byte seed", SigningKey, sk.verify_key)

    check_type_error("VerifyKey must be created from 32 bytes", VerifyKey, 13)
    check_type_error("VerifyKey must be created from 32 bytes", VerifyKey, sk)
    check_type_error("VerifyKey must be created from 32 bytes", VerifyKey, sk.verify_key)
开发者ID:fun-alex-alex2006hw,项目名称:pynacl,代码行数:12,代码来源:test_signing.py

示例4: test_invalid_signed_message

# 需要导入模块: from nacl.signing import SigningKey [as 别名]
# 或者: from nacl.signing.SigningKey import generate [as 别名]
    def test_invalid_signed_message(self):
        skey = SigningKey.generate()
        smessage = skey.sign(b"A Test Message!")
        signature, message = smessage.signature, b"A Forged Test Message!"

        # Small sanity check
        assert skey.verify_key.verify(smessage)

        with pytest.raises(BadSignatureError):
            skey.verify_key.verify(message, signature)

        with pytest.raises(BadSignatureError):
            forged = SignedMessage(signature + message)
            skey.verify_key.verify(forged)
开发者ID:lmctv,项目名称:pynacl,代码行数:16,代码来源:test_signing.py

示例5: test_hex_smessage_with_detached_sig_matches_with_attached_sig

# 需要导入模块: from nacl.signing import SigningKey [as 别名]
# 或者: from nacl.signing.SigningKey import generate [as 别名]
    def test_hex_smessage_with_detached_sig_matches_with_attached_sig(self):
        sk = SigningKey.generate()
        vk = sk.verify_key

        smsg = sk.sign(b"Hello World in hex", encoder=HexEncoder)

        msg = smsg.message
        hexsig = smsg.signature

        sig = HexEncoder.decode(hexsig)

        assert vk.verify(msg, sig, encoder=HexEncoder) == \
            vk.verify(smsg, encoder=HexEncoder)

        assert HexEncoder.decode(msg) == b"Hello World in hex"
开发者ID:lmctv,项目名称:pynacl,代码行数:17,代码来源:test_signing.py

示例6: test_base64_smessage_with_detached_sig_matches_with_attached_sig

# 需要导入模块: from nacl.signing import SigningKey [as 别名]
# 或者: from nacl.signing.SigningKey import generate [as 别名]
    def test_base64_smessage_with_detached_sig_matches_with_attached_sig(self):
        sk = SigningKey.generate()
        vk = sk.verify_key

        smsg = sk.sign(b"Hello World in base64", encoder=Base64Encoder)

        msg = smsg.message
        b64sig = smsg.signature

        sig = Base64Encoder.decode(b64sig)

        assert vk.verify(msg, sig, encoder=Base64Encoder) == \
            vk.verify(smsg, encoder=Base64Encoder)

        assert Base64Encoder.decode(msg) == b"Hello World in base64"
开发者ID:lmctv,项目名称:pynacl,代码行数:17,代码来源:test_signing.py

示例7: startInvitation

# 需要导入模块: from nacl.signing import SigningKey [as 别名]
# 或者: from nacl.signing.SigningKey import generate [as 别名]
    def startInvitation(self, petname, code, transports):
        #print "invite", petname, code.encode("hex")
        stretched = stretch(code)
        inviteKey = SigningKey(stretched)
        inviteID = inviteKey.verify_key.encode(Hex)
        mySigningKey = SigningKey.generate()
        myCIDkey = os.urandom(32)
        myTempPrivkey = PrivateKey.generate()

        # create my channel record
        tids = ",".join([str(tid) for tid in sorted(transports.keys())])
        channel_key = PrivateKey.generate()
        pub_crec = { "channel_pubkey": channel_key.public_key.encode(Hex),
                     "CID_key": myCIDkey.encode("hex"),
                     "transports": transports.values(),
                     }
        priv_data = { "my_signkey": mySigningKey.encode(Hex),
                      "my_CID_key": myCIDkey.encode("hex"),
                      "my_old_channel_privkey": channel_key.encode(Hex),
                      "my_new_channel_privkey": channel_key.encode(Hex),
                      "transport_ids": tids,
                      }

        db = self.db
        c = db.execute("SELECT inviteID FROM invitations")
        if inviteID in [str(row[0]) for row in c.fetchall()]:
            raise CommandError("invitation code already in use")
        iid = db.insert("INSERT INTO `invitations`"
                        " (code, petname, inviteKey,"
                        "  inviteID,"
                        "  myTempPrivkey, mySigningKey,"
                        "  my_channel_record, my_private_channel_data,"
                        "  myMessages, theirMessages, nextExpectedMessage)"
                        " VALUES (?,?,?, ?, ?,?, ?,?, ?,?,?)",
                        (code.encode("hex"), petname, stretched.encode("hex"),
                         inviteID,
                         myTempPrivkey.encode(Hex), mySigningKey.encode(Hex),
                         json.dumps(pub_crec), json.dumps(priv_data),
                         "", "", 1),
                        "invitations")
        self.subscribe(inviteID)
        i = Invitation(iid, self.db, self)
        i.sendFirstMessage()
        self.db.commit()
开发者ID:ggozad,项目名称:petmail,代码行数:46,代码来源:invitation.py

示例8: test_initialize_with_generate

# 需要导入模块: from nacl.signing import SigningKey [as 别名]
# 或者: from nacl.signing.SigningKey import generate [as 别名]
 def test_initialize_with_generate(self):
     SigningKey.generate()
开发者ID:lmctv,项目名称:pynacl,代码行数:4,代码来源:test_signing.py

示例9: maybe_generate_key

# 需要导入模块: from nacl.signing import SigningKey [as 别名]
# 或者: from nacl.signing.SigningKey import generate [as 别名]
    def maybe_generate_key(self, cbdir, privkey_path=u'key.priv', pubkey_path=u'key.pub'):

        privkey_path = os.path.join(cbdir, privkey_path)
        pubkey_path = os.path.join(cbdir, pubkey_path)

        if os.path.exists(privkey_path):

            # node private key seems to exist already .. check!

            priv_tags = _parse_keyfile(privkey_path, private=True)
            for tag in [u'creator', u'created-at', u'machine-id', u'public-key-ed25519', u'private-key-ed25519']:
                if tag not in priv_tags:
                    raise Exception("Corrupt node private key file {} - {} tag not found".format(privkey_path, tag))

            privkey_hex = priv_tags[u'private-key-ed25519']
            privkey = SigningKey(privkey_hex, encoder=HexEncoder)
            pubkey = privkey.verify_key
            pubkey_hex = pubkey.encode(encoder=HexEncoder).decode('ascii')

            if priv_tags[u'public-key-ed25519'] != pubkey_hex:
                raise Exception(
                    ("Inconsistent node private key file {} - public-key-ed25519 doesn't"
                     " correspond to private-key-ed25519").format(pubkey_path)
                )

            if os.path.exists(pubkey_path):
                pub_tags = _parse_keyfile(pubkey_path, private=False)
                for tag in [u'creator', u'created-at', u'machine-id', u'public-key-ed25519']:
                    if tag not in pub_tags:
                        raise Exception("Corrupt node public key file {} - {} tag not found".format(pubkey_path, tag))

                if pub_tags[u'public-key-ed25519'] != pubkey_hex:
                    raise Exception(
                        ("Inconsistent node public key file {} - public-key-ed25519 doesn't"
                         " correspond to private-key-ed25519").format(pubkey_path)
                    )
            else:
                self.log.info(
                    "Node public key file {pub_path} not found - re-creating from node private key file {priv_path}",
                    pub_path=pubkey_path,
                    priv_path=privkey_path,
                )
                pub_tags = OrderedDict([
                    (u'creator', priv_tags[u'creator']),
                    (u'created-at', priv_tags[u'created-at']),
                    (u'machine-id', priv_tags[u'machine-id']),
                    (u'public-key-ed25519', pubkey_hex),
                ])
                msg = u'Crossbar.io node public key\n\n'
                _write_node_key(pubkey_path, pub_tags, msg)

            self.log.debug("Node key already exists (public key: {hex})", hex=pubkey_hex)

        else:
            # node private key does not yet exist: generate one

            privkey = SigningKey.generate()
            privkey_hex = privkey.encode(encoder=HexEncoder).decode('ascii')
            pubkey = privkey.verify_key
            pubkey_hex = pubkey.encode(encoder=HexEncoder).decode('ascii')

            # first, write the public file
            tags = OrderedDict([
                (u'creator', _creator()),
                (u'created-at', utcnow()),
                (u'machine-id', _machine_id()),
                (u'public-key-ed25519', pubkey_hex),
            ])
            msg = u'Crossbar.io node public key\n\n'
            _write_node_key(pubkey_path, tags, msg)

            # now, add the private key and write the private file
            tags[u'private-key-ed25519'] = privkey_hex
            msg = u'Crossbar.io node private key - KEEP THIS SAFE!\n\n'
            _write_node_key(privkey_path, tags, msg)

            self.log.info("New node key pair generated!")

        # fix file permissions on node public/private key files
        # note: we use decimals instead of octals as octal literals have changed between Py2/3
        #
        if os.stat(pubkey_path).st_mode & 511 != 420:  # 420 (decimal) == 0644 (octal)
            os.chmod(pubkey_path, 420)
            self.log.info("File permissions on node public key fixed!")

        if os.stat(privkey_path).st_mode & 511 != 384:  # 384 (decimal) == 0600 (octal)
            os.chmod(privkey_path, 384)
            self.log.info("File permissions on node private key fixed!")

        self._node_key = cryptosign.SigningKey(privkey)

        return pubkey_hex
开发者ID:NinjaMSP,项目名称:crossbar,代码行数:94,代码来源:node.py

示例10: _prepare_node_keys

# 需要导入模块: from nacl.signing import SigningKey [as 别名]
# 或者: from nacl.signing.SigningKey import generate [as 别名]
    def _prepare_node_keys(self):
        from nacl.signing import SigningKey
        from nacl.encoding import HexEncoder

        # make sure CBDIR/.cdc exists
        #
        cdc_dir = os.path.join(self._cbdir, '.cdc')
        if os.path.isdir(cdc_dir):
            pass
        elif os.path.exists(cdc_dir):
            raise Exception(".cdc exists, but isn't a directory")
        else:
            os.mkdir(cdc_dir)
            self.log.info("CDC directory created")

        # load node ID, either from .cdc/node.id or from CDC_NODE_ID
        #
        def split_nid(nid_s):
            nid_c = nid_s.strip().split('@')
            if len(nid_c) != 2:
                raise Exception("illegal node principal '{}' - must follow the form <node id>@<management realm>".format(nid_s))
            node_id, realm = nid_c
            # FIXME: regex check node_id and realm
            return node_id, realm

        nid_file = os.path.join(cdc_dir, 'node.id')
        node_id, realm = None, None
        if os.path.isfile(nid_file):
            with open(nid_file, 'r') as f:
                node_id, realm = split_nid(f.read())
        elif os.path.exists(nid_file):
            raise Exception("{} exists, but isn't a file".format(nid_file))
        else:
            if 'CDC_NODE_ID' in os.environ:
                node_id, realm = split_nid(os.environ['CDC_NODE_ID'])
            else:
                raise Exception("Neither node ID file {} exists nor CDC_NODE_ID environment variable set".format(nid_file))

        # Load the node key, either from .cdc/node.key or from CDC_NODE_KEY.
        # The node key is a Ed25519 key in either raw format (32 bytes) or in
        # hex-encoded form (64 characters).
        #
        # Actually, what's loaded is not the secret Ed25519 key, but the _seed_
        # for that key. Private keys are derived from this 32-byte (256-bit)
        # random seed value. It is thus the seed value which is sensitive and
        # must be protected.
        #
        skey_file = os.path.join(cdc_dir, 'node.key')
        skey = None
        if os.path.isfile(skey_file):
            # FIXME: check file permissions are 0600!

            # This value is read in here.
            skey_len = os.path.getsize(skey_file)
            if skey_len in (32, 64):
                with open(skey_file, 'r') as f:
                    skey_seed = f.read()
                    encoder = None
                    if skey_len == 64:
                        encoder = HexEncoder
                    skey = SigningKey(skey_seed, encoder=encoder)
                self.log.info("Existing CDC node key loaded from {skey_file}.", skey_file=skey_file)
            else:
                raise Exception("invalid node key length {} (key must either be 32 raw bytes or hex encoded 32 bytes, hence 64 byte char length)")
        elif os.path.exists(skey_file):
            raise Exception("{} exists, but isn't a file".format(skey_file))
        else:
            skey = SigningKey.generate()
            skey_seed = skey.encode(encoder=HexEncoder)
            with open(skey_file, 'w') as f:
                f.write(skey_seed)

            # set file mode to read only for owner
            # 384 (decimal) == 0600 (octal) - we use that for Py2/3 reasons
            os.chmod(skey_file, 384)
            self.log.info("New CDC node key {skey_file} generated.", skey_file=skey_file)

        return realm, node_id, skey
开发者ID:FirefighterBlu3,项目名称:crossbar,代码行数:80,代码来源:node.py

示例11: maybe_generate_key

# 需要导入模块: from nacl.signing import SigningKey [as 别名]
# 或者: from nacl.signing.SigningKey import generate [as 别名]
def maybe_generate_key(log, cbdir, privkey_path=u'key.priv', pubkey_path=u'key.pub'):
    if not HAS_NACL:
        log.warn("Skipping node key generation - NaCl package not installed!")
        return

    from nacl.signing import SigningKey
    from nacl.encoding import HexEncoder

    privkey = None
    pubkey = None
    privkey_path = os.path.join(cbdir, privkey_path)
    pubkey_path = os.path.join(cbdir, pubkey_path)

    if os.path.exists(privkey_path):
        # node private key seems to exist already .. check!
        tags = _parse_keyfile(privkey_path, private=True)
        if u'private-key-ed25519' not in tags:
            raise Exception("Node private key file lacks a 'private-key-ed25519' tag!")

        privkey = tags[u'private-key-ed25519']
        # recreate a signing key from the base64 encoding
        privkey_obj = SigningKey(privkey, encoder=HexEncoder)
        pubkey = privkey_obj.verify_key.encode(encoder=HexEncoder).decode('ascii')

        # confirm we have the public key in the file, and that it is
        # correct
        if u'public-key-ed25519' in tags:
            if tags[u'public-key-ed25519'] != pubkey:
                raise Exception(
                    ("Inconsistent key file '{}': 'public-key-ed25519' doesn't"
                     " correspond to private-key-ed25519").format(privkey_path)
                )
        log.debug("Node key already exists (public key: {})".format(pubkey))

        if os.path.exists(pubkey_path):
            pubtags = _parse_keyfile(pubkey_path, private=False)
            if u'public-key-ed25519' not in pubtags:
                raise Exception(
                    ("Pubkey file '{}' exists but lacks 'public-key-ed25519'"
                     " tag").format(pubkey_path)
                )
            if pubtags[u'public-key-ed25519'] != pubkey:
                raise Exception(
                    ("Inconsistent key file '{}': 'public-key-ed25519' doesn't"
                     " correspond to private-key-ed25519").format(pubkey_path)
                )
        else:
            log.info("'{}' not found; re-creating from '{}'".format(pubkey_path, privkey_path))
            tags = OrderedDict([
                (u'creator', _creator()),
                (u'created-at', utcnow()),
                (u'machine-id', _machine_id()),
                (u'public-key-ed25519', pubkey),
            ])
            msg = u'Crossbar.io public key for node authentication\n\n'
            _write_node_key(pubkey_path, tags, msg)

    else:
        # node private key does NOT yet exist: generate one
        privkey_obj = SigningKey.generate()
        privkey = privkey_obj.encode(encoder=HexEncoder).decode('ascii')
        pubkey = privkey_obj.verify_key.encode(encoder=HexEncoder).decode('ascii')

        # first, write the public file
        tags = OrderedDict([
            (u'creator', _creator()),
            (u'created-at', utcnow()),
            (u'machine-id', _machine_id()),
            (u'public-key-ed25519', pubkey),
        ])
        msg = u'Crossbar.io public key for node authentication\n\n'
        _write_node_key(pubkey_path, tags, msg)

        # now, add the private key and write the private file
        tags[u'private-key-ed25519'] = privkey
        msg = u'Crossbar.io private key for node authentication - KEEP THIS SAFE!\n\n'
        _write_node_key(privkey_path, tags, msg)

        log.info("New node key generated!")

    return pubkey
开发者ID:FirefighterBlu3,项目名称:crossbar,代码行数:83,代码来源:node.py

示例12: maybe_generate_key

# 需要导入模块: from nacl.signing import SigningKey [as 别名]
# 或者: from nacl.signing.SigningKey import generate [as 别名]
def maybe_generate_key(log, cbdir, privkey_path=u'node.key'):
    if not HAS_NACL:
        log.warn("Skipping node key generation - NaCl package not installed!")
        return

    from nacl.signing import SigningKey
    from nacl.encoding import HexEncoder

    privkey = None
    privkey_path = os.path.join(cbdir, privkey_path)

    if os.path.exists(privkey_path):
        # node private key seems to exist already .. check!
        if os.path.isfile(privkey_path):
            with open(privkey_path, 'r') as privkey_file:
                privkey = None
                # parse key file lines, looking for tag "ed25519-privkey"
                got_blankline = False
                for line in privkey_file.read().splitlines():
                    if line.strip() == '':
                        got_blankline = True
                    elif got_blankline:
                        tag, value = line.split(':', 1)
                        tag = tag.strip().lower()
                        value = value.strip()
                        if tag not in [u'private-key-ed25519', u'public-key-ed25519', u'machine-id', u'created-at', u'creator']:
                            raise Exception("Invalid tag '{}' in node private key file {}".format(tag, privkey_path))
                        if tag == u'private-key-ed25519':
                            privkey = value
                            break

                if not privkey:
                    raise Exception("Node private key file lacks a 'ed25519-privkey' tag!")

                # recreate a signing key from the base64 encoding
                privkey_obj = SigningKey(privkey, encoder=HexEncoder)
                pubkey = privkey_obj.verify_key.encode(encoder=HexEncoder).decode('ascii')

            log.debug("Node key already exists (public key: {})".format(pubkey))
        else:
            raise Exception("Node private key path '{}' exists, but isn't a file".format(privkey_path))
    else:
        # node private key does NOT yet exist: generate one
        privkey_obj = SigningKey.generate()
        privkey = privkey_obj.encode(encoder=HexEncoder).decode('ascii')
        privkey_created_at = utcnow()

        pubkey = privkey_obj.verify_key.encode(encoder=HexEncoder).decode('ascii')

        # for informational purposes, try to get a machine unique id thing ..
        machine_id = None
        try:
            # why this? see: http://0pointer.de/blog/projects/ids.html
            with open('/var/lib/dbus/machine-id', 'r') as f:
                machine_id = f.read().strip()
        except:
            pass

        # for informational purposes, try to identify the creator ([email protected])
        creator = None
        try:
            creator = u'{}@{}'.format(getpass.getuser(), socket.gethostname())
        except:
            pass

        # write out the private key file
        with open(privkey_path, 'w') as privkey_file:
            privkey_file.write(u'Crossbar.io private key for node authentication - KEEP THIS SAFE!\n\n')
            if creator:
                privkey_file.write(u'creator: {}\n'.format(creator))
            privkey_file.write(u'created-at: {}\n'.format(privkey_created_at))
            if machine_id:
                privkey_file.write(u'machine-id: {}\n'.format(machine_id))
            privkey_file.write(u'public-key-ed25519: {}\n'.format(pubkey))
            privkey_file.write(u'private-key-ed25519: {}\n'.format(privkey))

        # set file mode to read only for owner
        # 384 (decimal) == 0600 (octal) - we use that for Py2/3 reasons
        os.chmod(privkey_path, 384)

        log.info("New node key generated!")

    return pubkey
开发者ID:yegorich,项目名称:crossbar,代码行数:85,代码来源:node.py

示例13: key_generate

# 需要导入模块: from nacl.signing import SigningKey [as 别名]
# 或者: from nacl.signing.SigningKey import generate [as 别名]
	def key_generate(): return SigningKey.generate()

def key_test( msg='test',
开发者ID:mk-fg,项目名称:tinydns-dynamic-dns-updater,代码行数:5,代码来源:tddu-server.py

示例14: create_new_key

# 需要导入模块: from nacl.signing import SigningKey [as 别名]
# 或者: from nacl.signing.SigningKey import generate [as 别名]
def create_new_key():
    # We use a signkey to get a 64bit key, instead of a 32bit key...
    #  because nacl?
    key = SigningKey.generate()
    return str(key._signing_key)
开发者ID:b1naryth1ef,项目名称:hackle,代码行数:7,代码来源:hackle.py

示例15: init

# 需要导入模块: from nacl.signing import SigningKey [as 别名]
# 或者: from nacl.signing.SigningKey import generate [as 别名]
def init(server, username, keydir, action, message, recipients):
    """ SHSM CLI client. """

    global serverurl
    serverurl = server

    if action == "register":
        master_signing_key = SigningKey.generate()
        device_signing_key = SigningKey.generate()
        device_private_key = PrivateKey.generate()

        enc_master_verify_key = master_signing_key.verify_key.encode(encoder=HexEncoder)
        register(username, enc_master_verify_key)

        # TODO: make sure keydir exists

        save_key(master_signing_key.encode(encoder=HexEncoder), keydir + "/master_signing_key")
        save_key(device_signing_key.encode(encoder=HexEncoder), keydir + "/device_signing_key")
        save_key(device_private_key.encode(encoder=HexEncoder), keydir + "/device_private_key")

    else:
        try:
            master_signing_key = SigningKey(load_key(keydir + "/master_signing_key"), encoder=HexEncoder)
            device_signing_key = SigningKey(load_key(keydir + "/device_signing_key"), encoder=HexEncoder)
            device_private_key = PrivateKey(load_key(keydir + "/device_private_key"), encoder=HexEncoder)
        except TypeError:
            print "bad key, exiting."
            exit()

        if action == "add-device":

            enc_device_verify_key = device_signing_key.verify_key.encode(encoder=HexEncoder)
            enc_signed_device_verify_key = b64encode(master_signing_key.sign(enc_device_verify_key))

            enc_device_public_key = device_private_key.public_key.encode(encoder=HexEncoder)
            enc_signed_device_public_key = b64encode(master_signing_key.sign(enc_device_public_key))

            add_device(username, enc_signed_device_verify_key, enc_signed_device_public_key)

        if action == "send-message":

            ephemeral_key = PrivateKey.generate()
            enc_ephemeral_public_key = b64encode(
                device_signing_key.sign(ephemeral_key.public_key.encode(encoder=HexEncoder))
            )

            # TODO:: should sign binary text, no? b"bob"
            destination_usernames = recipients.split(",")
            enc_dest_usernames = b64encode(
                device_signing_key.sign(json.dumps({"destination_usernames": destination_usernames}))
            )
            symmetric_key = random(SecretBox.KEY_SIZE)
            symmetric_box = SecretBox(symmetric_key)
            nonce = random(SecretBox.NONCE_SIZE)
            msg_manifest = {}
            msg_manifest["recipients"] = {}
            msg_manifest["msg"] = b64encode(symmetric_box.encrypt(str(message), nonce))

            for dest_user in destination_usernames:
                msg_manifest["recipients"][dest_user] = {}

                for recipient_key in get_recipient_keys(
                    device_signing_key.verify_key.encode(encoder=HexEncoder),
                    b64encode(device_signing_key.sign(str(dest_user))),
                ):

                    # TODO:: should sign binary text, no?
                    crypt_box = Box(ephemeral_key, recipient_key)
                    nonce = random(Box.NONCE_SIZE)
                    crypt_key = b64encode(crypt_box.encrypt(symmetric_key, nonce))
                    dest_key = recipient_key.encode(encoder=HexEncoder)
                    msg_manifest["recipients"][dest_user][dest_key] = crypt_key

            enc_signed_crypt_msg = b64encode(device_signing_key.sign(json.dumps(msg_manifest)))

            send_message(
                device_signing_key.verify_key.encode(encoder=HexEncoder),
                enc_dest_usernames,
                enc_signed_crypt_msg,
                enc_ephemeral_public_key,
            )

        if action == "get-messages":

            enc_device_verify_key = device_signing_key.verify_key.encode(encoder=HexEncoder)
            enc_signed_device_verify_key = b64encode(device_signing_key.sign(enc_device_verify_key))
            messages = get_messages(enc_device_verify_key, enc_signed_device_verify_key)

            for message_public_key in messages["messages"].keys():
                try:
                    crypto_box = Box(device_private_key, PublicKey(b64decode(message_public_key), encoder=HexEncoder))
                except TypeError:
                    print "not a valid public key"
                    exit()
                packed_msg = json.loads(messages["messages"][message_public_key])
                msg_manifest = json.loads(b64decode(packed_msg["message_manifest"]))
                dest_pub_key = device_private_key.public_key.encode(encoder=HexEncoder)
                symmetric_key = crypto_box.decrypt(b64decode(msg_manifest["recipients"][username][dest_pub_key]))
                symmetric_box = SecretBox(symmetric_key)
                print ("From: %s\nMessage: %s") % (
#.........这里部分代码省略.........
开发者ID:sinner-,项目名称:shsmc,代码行数:103,代码来源:shsmc.py


注:本文中的nacl.signing.SigningKey.generate方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。