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


Python Box.encrypt方法代码示例

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


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

示例1: encrypt

# 需要导入模块: from nacl.public import Box [as 别名]
# 或者: from nacl.public.Box import encrypt [as 别名]
 def encrypt(self, message, public_key, base64=True):
     box = Box(self._private_key, public_key)
     nonce = nacl.utils.random(Box.NONCE_SIZE)
     # encrypted = box.encrypt(message, nonce)
     if base64:
         encrypted = box.encrypt(message, nonce,
                                 encoder=nacl.encoding.Base64Encoder)
     else:
         encrypted = box.encrypt(message, nonce)
     return encrypted
开发者ID:ivanalejandro0,项目名称:cabinet,代码行数:12,代码来源:person.py

示例2: test_box_encryption_generates_different_nonces

# 需要导入模块: from nacl.public import Box [as 别名]
# 或者: from nacl.public.Box import encrypt [as 别名]
def test_box_encryption_generates_different_nonces(
        privalice, pubalice, privbob, pubbob, nonce, plaintext, ciphertext):
    pubbob = PublicKey(pubbob, encoder=HexEncoder)
    privalice = PrivateKey(privalice, encoder=HexEncoder)

    box = Box(privalice, pubbob)

    nonce_0 = box.encrypt(binascii.unhexlify(plaintext),
                          encoder=HexEncoder).nonce

    nonce_1 = box.encrypt(binascii.unhexlify(plaintext),
                          encoder=HexEncoder).nonce

    assert nonce_0 != nonce_1
开发者ID:lmctv,项目名称:pynacl,代码行数:16,代码来源:test_box.py

示例3: get_node

# 需要导入模块: from nacl.public import Box [as 别名]
# 或者: from nacl.public.Box import encrypt [as 别名]
        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,代码行数:36,代码来源:network.py

示例4: storelogin

# 需要导入模块: from nacl.public import Box [as 别名]
# 或者: from nacl.public.Box import encrypt [as 别名]
def storelogin(identifier, passwordstring, host, port, auth, tls):

    logindata = {
        'user'		: identifier,
        'passwd'	: passwordstring,
        'host'		: host,
        'port'		: port,
        'auth'		: auth,
        'tls'		: tls
    }

    clear_text =  json.dumps(logindata)

    nonce = nacl.utils.random(Box.NONCE_SIZE)

    box = Box(me_seckey, user_pubkey)
    encrypted = box.encrypt(clear_text, nonce)

    signed = me_sigkey.sign(encrypted, encoder=Base64Encoder);

    data = {
        'id'		: me_identifier,
        'verkey'	: me_verkey64,
        'pubkey'	: me_pubkey64,
        'login'		: signed
    }

    path = '%s.ypom' % identifier
    fd = open(path, 'w')
    fd.write(json.dumps(data))
    fd.close()
开发者ID:jpmens,项目名称:ypom-cli,代码行数:33,代码来源:ypom-admin.py

示例5: get_node

# 需要导入模块: from nacl.public import Box [as 别名]
# 或者: from nacl.public.Box import encrypt [as 别名]
        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,代码行数:29,代码来源:network.py

示例6: send_message

# 需要导入模块: from nacl.public import Box [as 别名]
# 或者: from nacl.public.Box import encrypt [as 别名]
    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,代码行数:36,代码来源:network.py

示例7: purchase

# 需要导入模块: from nacl.public import Box [as 别名]
# 或者: from nacl.public.Box import encrypt [as 别名]
    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,代码行数:34,代码来源:network.py

示例8: get_node

# 需要导入模块: from nacl.public import Box [as 别名]
# 或者: from nacl.public.Box import encrypt [as 别名]
        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,代码行数:33,代码来源:network.py

示例9: purchase

# 需要导入模块: from nacl.public import Box [as 别名]
# 或者: from nacl.public.Box import encrypt [as 别名]
    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,代码行数:28,代码来源:network.py

示例10: login

# 需要导入模块: from nacl.public import Box [as 别名]
# 或者: from nacl.public.Box import encrypt [as 别名]
    def login(self, uid):
        a, q = self.pow()

        if a == -1:
            raise Exception("Failed to prove work!")

        if not self.server_key or not self.client_key:
            raise Exception("Must have keys set to login!")

        payload = json.dumps({
            "timestamp": time.time(),
        })

        box = Box(self.client_key, self.server_key)
        nonce = nacl.utils.random(Box.NONCE_SIZE)
        payload = box.encrypt(payload, nonce)

        r = requests.post(self.url + "/api/login", params={
            "powa": a,
            "powq": q,
            "nonce": nonce,
            "payload": base64.b64encode(payload),
            "uid": uid
        })

        try:
            r.raise_for_status()
        except:
            print r.content
            raise

        print r.json()
开发者ID:b1naryth1ef,项目名称:hackle,代码行数:34,代码来源:client.py

示例11: send

# 需要导入模块: from nacl.public import Box [as 别名]
# 或者: from nacl.public.Box import encrypt [as 别名]
    def send(self, msg, content_type=None):
        ''' Send the clear text 'msg' to this user '''

        box = Box(me.seckey, self.pubkey)

        if content_type == None:
            content_type = 'text/plain; charset:"utf-8"'

        data = {
            "_type" : "msg",
            "timestamp" : time.time(),
            "content" : b64encode(msg),
            "content-type" : content_type,
        }
        clear_text =  json.dumps(data)

        # This is a nonce, it *MUST* only be used once, but it is not considered
        #   secret and can be transmitted or stored alongside the ciphertext. A
        #   good source of nonce is just 24 random bytes.
        nonce = nacl.utils.random(Box.NONCE_SIZE)

        # print "NONCE = ", binascii.hexlify(nonce)

        encrypted = box.encrypt(clear_text, nonce)

        signed = me.sigkey.sign(encrypted, encoder=Base64Encoder);

        #   to/from
        topic = topicname(self.identifier, me.identifier)

        mqttc.publish(topic, signed, qos=2, retain=False)
开发者ID:jpmens,项目名称:ypom-cli,代码行数:33,代码来源:ypom-cli.py

示例12: processM1

# 需要导入模块: from nacl.public import Box [as 别名]
# 或者: from nacl.public.Box import encrypt [as 别名]
    def processM1(self, msg):
        #print "processM1", self.petname
        self.theirTempPubkey = PublicKey(msg)
        self.db.update("UPDATE invitations SET theirTempPubkey=?"
                       " WHERE id=?",
                       (self.theirTempPubkey.encode(Hex), self.iid),
                       "invitations", self.iid)
        # theirTempPubkey will committed by our caller, in the same txn as
        # the message send

        my_privkey = self.getMyTempPrivkey()
        my_channel_record = self.getMyPublicChannelRecord()
        b = Box(my_privkey, self.theirTempPubkey)
        signedBody = b"".join([self.theirTempPubkey.encode(),
                               my_privkey.public_key.encode(),
                               my_channel_record.encode("utf-8")])
        my_sign = self.getMySigningKey()
        body = b"".join([b"i0:m2a:",
                         my_sign.verify_key.encode(),
                         my_sign.sign(signedBody)
                         ])
        nonce = os.urandom(Box.NONCE_SIZE)
        nonce_and_ciphertext = b.encrypt(body, nonce)
        #print "ENCRYPTED n+c", len(nonce_and_ciphertext), nonce_and_ciphertext.encode("hex")
        #print " nonce", nonce.encode("hex")
        msg2 = "i0:m2:"+nonce_and_ciphertext
        self.send(msg2)
        self.nextExpectedMessage = 2
开发者ID:ggozad,项目名称:petmail,代码行数:30,代码来源:invitation.py

示例13: get_message_key_ciphertext

# 需要导入模块: from nacl.public import Box [as 别名]
# 或者: from nacl.public.Box import encrypt [as 别名]
    def get_message_key_ciphertext(self, captain_room_participant_privkey, room_message_key):
        """As the captain, encrypt the room_message_key for this particular room member."""
        encryption_box = Box(captain_room_participant_privkey, self.room_pubkey)
        message = room_message_key
        nonce = nacl.utils.random(Box.NONCE_SIZE)

        ciphertext = encryption_box.encrypt(message, nonce) # XXX move to crypto.py
        return ciphertext
开发者ID:adrianhust,项目名称:viola,代码行数:10,代码来源:room.py

示例14: handshake_initiate

# 需要导入模块: from nacl.public import Box [as 别名]
# 或者: from nacl.public.Box import encrypt [as 别名]
def handshake_initiate(private_key, redis_client):
    try:
        request = expect_json_request(bottle.request, INITIATE_SCHEMA)

        symmetric_key = redis_get_cookie(
            redis_client, request[INITIATE_COOKIE_FIELD])
        cookie_sbox = SecretBox(symmetric_key)
        cookie = cookie_sbox.decrypt(
            str(request[INITIATE_COOKIE_FIELD]), encoder=Base64Encoder)

        if len(cookie) != 2 * CURVE25519_KEY_BYTES:
            bottle.response.status = HTTP_INTERNAL_SERVER_ERROR
            return {'error': 'An invalid cookie was sent to the client.'}
        client_transient_pkey = PublicKey(cookie[0:CURVE25519_KEY_BYTES])
        transient_skey = PrivateKey(cookie[CURVE25519_KEY_BYTES:])

        if request[INITIATE_CLIENT_TRANSIENT_PKEY_FIELD] != \
           client_transient_pkey.encode(Base64Encoder):
            raise InvalidClientRequest(
                'Initiate: non matching transient public keys.')

        vouch_json = open_box(request[INITIATE_VOUCH_FIELD],
                              transient_skey, client_transient_pkey)
        vouch = parse_and_verify_json(vouch_json, VOUCH_SCHEMA)

        client_pkey = PublicKey(
            str(vouch[VOUCH_CLIENT_PKEY_FIELD]), encoder=Base64Encoder)
        vouch_for_transient_pkey = open_box(
            vouch[VOUCH_TRANSIENT_KEY_BOX_FIELD], private_key, client_pkey)
        if vouch_for_transient_pkey != client_transient_pkey.encode():
            raise InvalidClientRequest(
                'Initiate: non matching transient public keys.')

        resp = 'I believe you are {} and you want {}'.format(
            client_pkey.encode(Base64Encoder), vouch[VOUCH_MESSAGE_FIELD])
        print(resp)
        response_nonce = nacl.utils.random(Box.NONCE_SIZE)
        response_box = Box(transient_skey, client_transient_pkey)
        response_box_cipher = response_box.encrypt(
            resp, response_nonce, encoder=Base64Encoder)
        return {'response': response_box_cipher}
    except jsonschema.ValidationError as e:
        log.exception(e)
        bottle.response.status = HTTP_BAD_REQUEST
        return {'error': str(e)}
    except InvalidClientRequest as e:
        log.exception(e)
        bottle.response.status = HTTP_BAD_REQUEST
        return {'error': str(e)}
    except MissingCookie as e:
        log.exception(e)
        bottle.response.status = HTTP_BAD_REQUEST
        return {'error': str(e)}
    except CryptoError as e:
        log.exception(e)
        bottle.response.status = HTTP_BAD_REQUEST
        return {'error': 'Bad encryption in handshake.'}
    return {'error': ''}
开发者ID:mcobzarenco,项目名称:opake,代码行数:60,代码来源:opake-app.py

示例15: encrypt_data

# 需要导入模块: from nacl.public import Box [as 别名]
# 或者: from nacl.public.Box import encrypt [as 别名]
def encrypt_data(private_hex, public_hex, message):
    sk = PrivateKey(private_hex, nacl.encoding.HexEncoder)
    pk = PublicKey(public_hex, nacl.encoding.HexEncoder)

    box = Box(sk, pk)
    nonce = nacl.utils.random(Box.NONCE_SIZE)

    encoded = box.encrypt(message.encode(), nonce, encoder=nacl.encoding.HexEncoder)
    return encoded
开发者ID:ownpush,项目名称:rss_demo_server,代码行数:11,代码来源:tasks.py


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