• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python public.PrivateKey类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中nacl.public.PrivateKey的典型用法代码示例。如果您正苦于以下问题:Python PrivateKey类的具体用法?Python PrivateKey怎么用?Python PrivateKey使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



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

示例1: add_new_channel

    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,代码行数:59,代码来源:common.py


示例2: test_nacl_encrypt_decrypt

def test_nacl_encrypt_decrypt():
    skbob = PrivateKey.generate()
    pkbob = skbob.public_key
    skalice = PrivateKey.generate()
    pkalice = skalice.public_key
    message_bytes = nacl.utils.random(SALT_SIZE)
    encrypted = nacl_encrypt(message_bytes, skbob, pkalice)
    decrypted = nacl_decrypt(encrypted, skalice, pkbob)
    assert decrypted == message_bytes
开发者ID:au9ustine,项目名称:org.au9ustine.elrond,代码行数:9,代码来源:test_crypto.py


示例3: test_box_seal

def test_box_seal(
        privalice, pubalice, privbob, pubbob, nonce, plaintext, ciphertext):
    pubalice = PublicKey(pubalice, encoder=HexEncoder)
    privalice = PrivateKey(privalice, encoder=HexEncoder)
    plaintext = binascii.unhexlify(plaintext)

    sealed = pubalice.seal(plaintext)
    unsealed = privalice.seal_open(sealed)
    assert plaintext == unsealed

    sealed2 = privalice.seal(plaintext)
    unsealed2 = privalice.seal_open(sealed2)
    assert plaintext == unsealed2
开发者ID:PreVeil,项目名称:pynacl,代码行数:13,代码来源:test_box.py


示例4: test_list_request

 def test_list_request(self):
     serverkey = PrivateKey.generate()
     RT = "01234567" # 8 bytes
     req, tmppub = retrieval.encrypt_list_request(serverkey.public_key.encode(), RT)
     got_tmppub, boxed0 = server.decrypt_list_request_1(req)
     ts, got_RT = server.decrypt_list_request_2(got_tmppub, boxed0, serverkey)
     self.failUnlessEqual(RT, got_RT)
开发者ID:warner,项目名称:petmail,代码行数:7,代码来源:test_retrieval.py


示例5: __new__

 def __new__(cls, microdescriptor):
     relay_identity = decodeMicrodescriptorIdentifier(microdescriptor)
     relay_ntor_onion_key = base64.b64decode(microdescriptor.ntor_onion_key)
     secret_key = PrivateKey.generate()
     public_key = secret_key.public_key
     return super(NTorState, cls).__new__(
         cls, relay_identity, relay_ntor_onion_key, secret_key, public_key)
开发者ID:nskinkel,项目名称:oppy,代码行数:7,代码来源:ntor.py


示例6: key_gen

	def key_gen(self):
		"""Generate a private key"""
		import base64, zlib
		from nacl.public import PrivateKey
		privObj = PrivateKey.generate()
		privKey = base64.b64encode(zlib.compress(str(privObj), 9))
		return privObj, privKey
开发者ID:stryngs,项目名称:scripts,代码行数:7,代码来源:keys.py


示例7: purchase

    def purchase(self, node_to_ask, contract):
        """
        Send an order message to the vendor.

        Args:
            node_to_ask: a `dht.node.Node` object
            contract: a complete `Contract` object containing the buyer's order
        """

        def parse_response(response):
            try:
                address = contract.contract["buyer_order"]["order"]["payment"]["address"]
                verify_key = nacl.signing.VerifyKey(node_to_ask.signed_pubkey[64:])
                verify_key.verify(str(address), response[1][0])
                return response[1][0]
            except Exception:
                return False

        public_key = contract.contract["vendor_offer"]["listing"]["id"]["pubkeys"]["encryption"]
        skephem = PrivateKey.generate()
        pkephem = skephem.public_key.encode(nacl.encoding.RawEncoder)
        box = Box(skephem, PublicKey(public_key, nacl.encoding.HexEncoder))
        nonce = nacl.utils.random(Box.NONCE_SIZE)
        ciphertext = box.encrypt(json.dumps(contract.contract, indent=4), nonce)
        d = self.protocol.callOrder(node_to_ask, pkephem, ciphertext)
        return d.addCallback(parse_response)
开发者ID:JimmyMow,项目名称:OpenBazaar-Server,代码行数:26,代码来源:network.py


示例8: __enter__

    def __enter__(self) -> typing.Tuple[PrivateKey, PrivateKey]:
        """
        Provides a pair of private keys.
        """
        # Derive the key from the passphrase.
        derived = util.derive_passphrase(self.passphrase)

        sign_box = SecretBox(derived)
        enc_box = SecretBox(derived)

        # Decrypt, using the two nonces.
        s_d = sign_box.decrypt(self.key._private_signing_seed, self.key._private_signing_nonce)
        e_d = enc_box.decrypt(self.key._private_key_raw, self.key._private_nonce)

        # Generate a SigningKey out of the seed.
        self.sign = SigningKey(s_d)
        self.encrypt = PrivateKey(e_d)

        # Update the key's public keys.
        if self.key._public_key is None:
            self.key._public_key = self.encrypt.public_key

        if self.key._public_signing_key is None:
            self.key._public_signing_key = self.sign.verify_key

        return self.encrypt, self.sign
开发者ID:SunDwarf,项目名称:Gluino,代码行数:26,代码来源:private.py


示例9: get_node

        def get_node(node_to_ask):
            def parse_response(response):
                if response[0] and response[1][0] == "True":
                    return True
                elif not response[0]:
                    contract_dict = json.loads(json.dumps(contract.contract, indent=4),
                                               object_pairs_hook=OrderedDict)
                    del contract_dict["vendor_order_confirmation"]
                    del contract_dict["buyer_receipt"]
                    order_id = digest(json.dumps(contract_dict, indent=4)).encode("hex")
                    self.send_message(Node(unhexlify(guid)),
                                      contract.contract["vendor_offer"]["listing"]["id"]["pubkeys"]["encryption"],
                                      objects.Plaintext_Message.Type.Value("RECEIPT"),
                                      json.dumps(contract.contract["buyer_receipt"]),
                                      order_id,
                                      store_only=True)
                    return True
                else:
                    return False

            if node_to_ask:
                public_key = contract.contract["vendor_offer"]["listing"]["id"]["pubkeys"]["encryption"]
                skephem = PrivateKey.generate()
                pkephem = skephem.public_key.encode(nacl.encoding.RawEncoder)
                box = Box(skephem, PublicKey(public_key, nacl.encoding.HexEncoder))
                nonce = nacl.utils.random(Box.NONCE_SIZE)
                ciphertext = box.encrypt(json.dumps(contract.contract, indent=4), nonce)
                d = self.protocol.callCompleteOrder(node_to_ask, pkephem, ciphertext)
                return d.addCallback(parse_response)
            else:
                return parse_response([False])
开发者ID:foxcarlos,项目名称:OpenBazaar-Server,代码行数:31,代码来源:network.py


示例10: storeAccount

def storeAccount(phrase, uid, auth, alias):
    """
    Store new account information

    @param phrase: new passphrase as bytes
    @param uid: user id
    @param auth: authentication token
    @param alias: user set alias for profile
    @return: Profile ID of newly created profile and safe
    """
    con = getCursor()

    # random phrase buffer
    buffer = nacl.utils.random(nacl.secret.SecretBox.KEY_SIZE)
    # create safe (db encryption)
    safe = SecretBox(b''.join((phrase, buffer[len(phrase) - 32:])))
    # create new signing_key and verify_key (message signing)
    skey = nacl.signing.SigningKey.generate()
    # create new private and public key (message encryption)
    mkey = PrivateKey.generate()

    con.execute("INSERT INTO profiles (uid, auth, signing_key, verify_key, private_key, public_key, buffer, alias) "
                "VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
                list(encrypt(safe, uid, auth, skey._seed, skey.verify_key.encode(encoder=nacl.encoding.HexEncoder),
                             mkey._private_key, mkey.public_key._public_key)) + [buffer, alias])

    profileId = con.lastrowid

    return profileId, safe
开发者ID:pombredanne,项目名称:quip,代码行数:29,代码来源:Database.py


示例11: create_node

def create_node(so, stdout=sys.stdout, stderr=sys.stderr):
    basedir = so["basedir"]
    if os.path.exists(basedir):
        print >>stderr, "basedir '%s' already exists, refusing to touch it" % basedir
        return 1
    os.mkdir(basedir)
    dbfile = os.path.join(basedir, "petmail.db")
    db = database.get_db(dbfile, stderr)
    db.execute("INSERT INTO node (webhost, webport) VALUES (?,?)",
               (so["webhost"], so["webport"]))
    db.execute("INSERT INTO services (name) VALUES (?)", ("client",))
    db.execute("INSERT INTO `client_profile`"
               " (`name`, `icon_data`) VALUES (?,?)",
               ("",""))
    privkey = PrivateKey.generate()
    TID_tokenid, TID_privkey, TID_token0 = rrid.create()
    server_desc = { "transport_privkey": privkey.encode().encode("hex"),
                    "TID_private_key": TID_privkey.encode("hex"),
                    "local_TID0": TID_token0.encode("hex"),
                    "local_TID_tokenid": TID_tokenid.encode("hex"),
                    }
    db.execute("INSERT INTO mailbox_server_config"
               " (private_descriptor_json, enable_retrieval)"
               " VALUES (?,?)",
               (json.dumps(server_desc), 0))
    db.commit()
    print >>stdout, "node created in %s" % basedir
    return 0
开发者ID:ggozad,项目名称:petmail,代码行数:28,代码来源:create_node.py


示例12: authenticate

    def authenticate(self, permissions=[]): #TODO check is needs to = None
        keys = PrivateKey.generate()
        nonce = nacl.utils.random(Box.NONCE_SIZE)
        payload = {
            'app': {
                'name': self.name,
                'version': self.version,
                'vendor': self.vendor,
                'id': self.id
            },
            'publicKey': base64.b64encode(keys.public_key.__bytes__()),
            'nonce': base64.b64encode(nonce),
            'permissions': permissions
        }
        headers = {
            'Content-Type': 'application/json'
        }
        r = self._post('auth', headers, payload)
        if r.status_code == 200:
            responseJson = r.json()
            cipherText = base64.b64decode(responseJson['encryptedKey'])
            self.token = responseJson['token']
            self.permissions = responseJson['permissions']
            self.publicKey = base64.b64decode(responseJson['publicKey'])

            box = Box(keys, PublicKey(self.publicKey))
            data = box.decrypt(cipherText, nonce=nonce)

            self.symmetricKey = data[0:PrivateKey.SIZE]
            self.symmetricNonce = data[PrivateKey.SIZE:]
            return True
        else:
            return False
开发者ID:PaulDStevenson,项目名称:PySafeAPI,代码行数:33,代码来源:safeAPI.py


示例13: send_message

    def send_message(self, receiving_node, public_key, message_type, message, subject=None):
        """
        Sends a message to another node. If the node isn't online it
        will be placed in the dht for the node to pick up later.
        """
        pro = Profile().get()
        if len(message) > 1500:
            return
        p = objects.Plaintext_Message()
        p.sender_guid = self.kserver.node.id
        p.signed_pubkey = self.kserver.node.signed_pubkey
        p.encryption_pubkey = PrivateKey(self.signing_key.encode()).public_key.encode()
        p.type = message_type
        p.message = message
        if subject is not None:
            p.subject = subject
        if pro.handle:
            p.handle = pro.handle
        if pro.avatar_hash:
            p.avatar_hash = pro.avatar_hash
        p.timestamp = int(time.time())
        signature = self.signing_key.sign(p.SerializeToString())[:64]
        p.signature = signature

        skephem = PrivateKey.generate()
        pkephem = skephem.public_key.encode(nacl.encoding.RawEncoder)
        box = Box(skephem, PublicKey(public_key, nacl.encoding.HexEncoder))
        nonce = nacl.utils.random(Box.NONCE_SIZE)
        ciphertext = box.encrypt(p.SerializeToString(), nonce)

        def get_response(response):
            if not response[0]:
                self.kserver.set(digest(receiving_node.id), pkephem, ciphertext)
        self.protocol.callMessage(receiving_node, pkephem, ciphertext).addCallback(get_response)
开发者ID:bglassy,项目名称:OpenBazaar-Server,代码行数:34,代码来源:network.py


示例14: respond_to_rekey

    def respond_to_rekey(self, message):
        # Verify length
        if not len(message) == 34 + self._mac_length:
            _logger.info('Invalid length of rekey')
            # TODO: Multi-byte asequence numbers should also be allowed
            return

        # Verify MAC
        msg, sig = message[:-self._mac_length], message[-self._mac_length:]
        if not self.verify_mac(message):
            _logger.info('Invalid MAC on rekey')
            return

        # Verify sequence number
        if not self.validate_and_update_others_seqnum(msg):
            _logger.info('Invalid sequence number on rekey')
            return

        client_pubkey = msg[2:]
        self.pkey = PrivateKey.generate()
        self.new_master_key = self.derive_shared_key(client_pubkey)
        msg = six.int2byte(Message.rekey_response) + encode_varint(self.my_seq) + self.pkey.public_key._public_key
        self.state = ServerState.rekey
        full_msg = msg + self.get_mac(msg)
        self._send(full_msg)
        self.my_seq += 1
开发者ID:thusoy,项目名称:nuts-auth,代码行数:26,代码来源:sessions.py


示例15: get_node

        def get_node(node_to_ask, recipient_guid, public_key):
            def parse_response(response):
                if not response[0]:
                    self.send_message(
                        Node(unhexlify(recipient_guid)),
                        nacl.signing.VerifyKey(public_key, encoder=nacl.encoding.HexEncoder)
                        .to_curve25519_public_key()
                        .encode(),
                        objects.PlaintextMessage.Type.Value("DISPUTE_OPEN"),
                        json.dumps(contract),
                        order_id,
                        store_only=True,
                    )

            if node_to_ask:
                enc_key = nacl.signing.VerifyKey(
                    public_key, encoder=nacl.encoding.HexEncoder
                ).to_curve25519_public_key()
                skephem = PrivateKey.generate()
                pkephem = skephem.public_key.encode(nacl.encoding.RawEncoder)
                box = Box(skephem, enc_key)
                nonce = nacl.utils.random(Box.NONCE_SIZE)
                ciphertext = box.encrypt(json.dumps(contract, indent=4), nonce)
                d = self.protocol.callDisputeOpen(node_to_ask, pkephem, ciphertext)
                return d.addCallback(parse_response)
            else:
                return parse_response([False])
开发者ID:tcharding,项目名称:OpenBazaar-Server,代码行数:27,代码来源:network.py


示例16: test_wrong_types

def test_wrong_types():
    priv = PrivateKey.generate()

    check_type_error(("PrivateKey must be created from a 32 bytes long "
                      "raw secret key"),
                     PrivateKey, 12)
    check_type_error(("PrivateKey must be created from a 32 bytes long "
                      "raw secret key"),
                     PrivateKey, priv)
    check_type_error(("PrivateKey must be created from a 32 bytes long "
                      "raw secret key"),
                     PrivateKey, priv.public_key)

    check_type_error("PublicKey must be created from 32 bytes",
                     PublicKey, 13)
    check_type_error("PublicKey must be created from 32 bytes",
                     PublicKey, priv)
    check_type_error("PublicKey must be created from 32 bytes",
                     PublicKey, priv.public_key)

    check_type_error("Box must be created from a PrivateKey and a PublicKey",
                     Box, priv, "not a public key")
    check_type_error("Box must be created from a PrivateKey and a PublicKey",
                     Box, priv.encode(), priv.public_key.encode())
    check_type_error("Box must be created from a PrivateKey and a PublicKey",
                     Box, priv, priv.public_key.encode())
    check_type_error("Box must be created from a PrivateKey and a PublicKey",
                     Box, priv.encode(), priv.public_key)

    check_type_error("seed must be a 32 bytes long",
                     PrivateKey.from_seed, b"1")
开发者ID:lmctv,项目名称:pynacl,代码行数:31,代码来源:test_box.py


示例17: send_rekey

 def send_rekey(self):
     self.pkey = PrivateKey.generate()
     msg = six.int2byte(Message.rekey) + encode_varint(self.my_seq) + self.pkey.public_key._public_key
     mac = self.get_mac(msg)
     self.my_seq += 1
     self._send(msg + mac)
     self.state = ClientState.rekey
开发者ID:thusoy,项目名称:nuts-auth,代码行数:7,代码来源:sessions.py


示例18: purchase

    def purchase(self, node_to_ask, contract):
        """
        Send an order message to the vendor.

        Args:
            node_to_ask: a `dht.node.Node` object
            contract: a complete `Contract` object containing the buyer's order
        """
        def parse_response(response):
            try:
                address = contract.contract["buyer_order"]["order"]["payment"]["address"]
                chaincode = contract.contract["buyer_order"]["order"]["payment"]["chaincode"]
                masterkey_b = contract.contract["buyer_order"]["order"]["id"]["pubkeys"]["bitcoin"]
                buyer_key = derive_childkey(masterkey_b, chaincode)
                amount = contract.contract["buyer_order"]["order"]["payment"]["amount"]
                listing_hash = contract.contract["buyer_order"]["order"]["ref_hash"]
                verify_key = nacl.signing.VerifyKey(node_to_ask.signed_pubkey[64:])
                verify_key.verify(
                    str(address) + str(amount) + str(listing_hash) + str(buyer_key), response[1][0])
                return response[1][0]
            except Exception:
                return False

        public_key = contract.contract["vendor_offer"]["listing"]["id"]["pubkeys"]["encryption"]
        skephem = PrivateKey.generate()
        pkephem = skephem.public_key.encode(nacl.encoding.RawEncoder)
        box = Box(skephem, PublicKey(public_key, nacl.encoding.HexEncoder))
        nonce = nacl.utils.random(Box.NONCE_SIZE)
        ciphertext = box.encrypt(json.dumps(contract.contract, indent=4), nonce)
        d = self.protocol.callOrder(node_to_ask, pkephem, ciphertext)
        self.log.info("purchasing contract %s from %s" % (contract.get_contract_id().encode("hex"), node_to_ask))
        return d.addCallback(parse_response)
开发者ID:foxcarlos,项目名称:OpenBazaar-Server,代码行数:32,代码来源:network.py


示例19: get_node

        def get_node(node_to_ask):
            def parse_response(response):
                if response[0] and response[1][0] == "True":
                    return True
                elif not response[0]:
                    contract_dict = json.loads(json.dumps(contract.contract, indent=4),
                                               object_pairs_hook=OrderedDict)
                    del contract_dict["vendor_order_confirmation"]
                    order_id = digest(json.dumps(contract_dict, indent=4)).encode("hex")
                    self.send_message(Node(unhexlify(guid)),
                                      nacl.signing.VerifyKey(
                                          contract.contract["buyer_order"]["order"]["id"]["pubkeys"]["guid"],
                                          encoder=nacl.encoding.HexEncoder).to_curve25519_public_key().encode(),
                                      objects.PlaintextMessage.Type.Value("ORDER_CONFIRMATION"),
                                      json.dumps(contract.contract["vendor_order_confirmation"]),
                                      order_id,
                                      store_only=True)
                    return True
                else:
                    return False

            if node_to_ask:
                public_key = nacl.signing.VerifyKey(
                    contract.contract["buyer_order"]["order"]["id"]["pubkeys"]["guid"],
                    encoder=nacl.encoding.HexEncoder).to_curve25519_public_key()
                skephem = PrivateKey.generate()
                pkephem = skephem.public_key.encode(nacl.encoding.RawEncoder)
                box = Box(skephem, public_key)
                nonce = nacl.utils.random(Box.NONCE_SIZE)
                ciphertext = box.encrypt(json.dumps(contract.contract, indent=4), nonce)
                d = self.protocol.callOrderConfirmation(node_to_ask, pkephem, ciphertext)
                return d.addCallback(parse_response)
            else:
                return parse_response([False])
开发者ID:jjeffryes,项目名称:OpenBazaar-Server,代码行数:34,代码来源:network.py


示例20: __init__

class IDPrivateKey:
    
    def __init__(self, password = None, email = None):
        if email is None:
            self.salt = defaultsalt
        else:
            self.salt = email
        if password is not None:
            self.generate_key(password)

    def generate_key(self, password):
        self.pri = PrivateKey(scrypt(sha512(password,encoder = RawEncoder),
                                     self.salt,
                                     N = 1<<17,
                                     r = 8,
                                     p = 1,
                                     buflen = 32),
                              encoder = RawEncoder)
        pub = PublicID()
        pub.salt = self.salt
        pub.key = self.pri.public_key.encode()
        self.pub = pub

    def to_private_key(self):
        return self.pri

    def to_public_key(self):
        return self.pub

    def pri_base58(self):
        return b58encode(self.pri.encode(encoder = RawEncoder))

    def pub_base58(self):
        return self.pub.base58()
开发者ID:sharph,项目名称:pyminilock,代码行数:34,代码来源:minilockid.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python secret.SecretBox类代码示例发布时间:2022-05-27
下一篇:
Python public.Box类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap