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


Python SigningKey.sign方法代码示例

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


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

示例1: test_message_signing

# 需要导入模块: from nacl.signing import SigningKey [as 别名]
# 或者: from nacl.signing.SigningKey import sign [as 别名]
    def test_message_signing(self, seed, message, signature, expected):
        signing_key = SigningKey(seed, encoder=HexEncoder)
        signed = signing_key.sign(binascii.unhexlify(message), encoder=HexEncoder)

        assert signed == expected
        assert signed.message == message
        assert signed.signature == signature
开发者ID:fun-alex-alex2006hw,项目名称:pynacl,代码行数:9,代码来源:test_signing.py

示例2: decrypt_message

# 需要导入模块: from nacl.signing import SigningKey [as 别名]
# 或者: from nacl.signing.SigningKey import sign [as 别名]
def decrypt_message(encrypted_message, keying_material, private_key):
    encrypted_key = keying_material['encrypted_key']
    message_signature = keying_material['message_signature']
    temp_public_key = PublicKey(
        keying_material['temp_public_key'],
        Base64Encoder)

    box = PublicBox(private_key, temp_public_key)

    message_key = box.decrypt(
        encrypted_key,
        encoder=Base64Encoder)

    # We got the key, so let's get the message.
    message_box = nacl.secret.SecretBox(message_key)
    message = message_box.decrypt(
        encrypted_message,
        encoder=Base64Encoder)

    # Check the signature.
    mac_key = sha256(box._shared_key, RawEncoder)
    signing_key = SigningKey(mac_key)
    if signing_key.sign(message, Base64Encoder) != message_signature:
        raise SignatureError("The signature is not valid")

    return message
开发者ID:mozilla-services,项目名称:messaging,代码行数:28,代码来源:crypto.py

示例3: sign

# 需要导入模块: from nacl.signing import SigningKey [as 别名]
# 或者: from nacl.signing.SigningKey import sign [as 别名]
    def sign(self, message, private_key):
        """
        Sign the message.

        This method will take the currently configured values for the message
        prefix and suffix and create a signature using the provided Ed25519 private key.

        Args:
            message (bytes): message to be signed
            private_key (bytes) Ed25519 private key

        """
        sk = SigningKey(private_key)
        self.public_key = sk.verify_key.encode()
        self.signature = sk.sign(message).signature
        return self.signature
开发者ID:bigchaindb,项目名称:cryptoconditions,代码行数:18,代码来源:ed25519.py

示例4: encrypt_message

# 需要导入模块: from nacl.signing import SigningKey [as 别名]
# 或者: from nacl.signing.SigningKey import sign [as 别名]
def encrypt_message(message, identifier):
    """Encrypts a message so that it can be read by all the devices of the
    given identifier.

    :param message: the message itself, in clear text.
    :param identifier: the identifier of the message recipient.
    """
    # Cipher the message with a brand new random key.
    message_key = nacl.utils.random(nacl.secret.SecretBox.KEY_SIZE)
    message_box = nacl.secret.SecretBox(message_key)
    message_nonce = nacl.utils.random(nacl.secret.SecretBox.NONCE_SIZE)
    encrypted_message = message_box.encrypt(message, message_nonce,
                                            Base64Encoder)

    returned = []
    # Encrypt the message key with each recipient's public key.
    for recipient_device_pub_key in get_public_keys(identifier):

        # Generate a new keypair & cipher the key with it.
        temp_private_key, temp_public_key = generate_keypair()
        box = PublicBox(temp_private_key, recipient_device_pub_key)
        nonce = nacl.utils.random(PublicBox.NONCE_SIZE)
        encrypted_key = box.encrypt(message_key, nonce, Base64Encoder)

        # Sign the message.
        mac_key = sha256(box._shared_key, RawEncoder)
        signing_key = SigningKey(mac_key)
        message_sig = signing_key.sign(message, Base64Encoder)

        # Return the public key used to cipher the message key.
        returned.append({
            'encrypted_key': encrypted_key,
            'temp_public_key': temp_public_key.encode(Base64Encoder),
            'message_signature': message_sig
        })

    return {
        'encrypted_message': encrypted_message,
        'recipients': returned
    }
开发者ID:mozilla-services,项目名称:messaging,代码行数:42,代码来源:crypto.py

示例5: tick

# 需要导入模块: from nacl.signing import SigningKey [as 别名]
# 或者: from nacl.signing.SigningKey import sign [as 别名]

#.........这里部分代码省略.........

        # these handlers will update self.myMessages with sent messages, and
        # will increment self.nextExpectedMessage. We can handle multiple
        # (sequential) messages in a single pass.
        if self.nextExpectedMessage == 1:
            self.findPrefixAndCall("i0:m1:", bodies, self.processM1)
            # no elif here: self.nextExpectedMessage may have incremented
        if self.nextExpectedMessage == 2:
            self.findPrefixAndCall("i0:m2:", bodies, self.processM2)
        if self.nextExpectedMessage == 3:
            self.findPrefixAndCall("i0:m3:", bodies, self.processM3)

        self.db.update("UPDATE invitations SET"
                       "  myMessages=?,"
                       "  theirMessages=?,"
                       "  nextExpectedMessage=?"
                       " WHERE id=?",
                       (",".join(self.myMessages),
                        ",".join(self.theirMessages | newMessages),
                        self.nextExpectedMessage,
                        self.iid),
                       "invitations", self.iid)
        #print " db.commit"
        self.db.commit()

    def findPrefixAndCall(self, prefix, bodies, handler):
        for msg in bodies:
            if msg.startswith(prefix):
                return handler(msg[len(prefix):])
        return None

    def send(self, msg, persist=True):
        #print "send", repr(msg[:10]), "..."
        signed = "r0:%s" % self.inviteKey.sign(msg).encode("hex")
        if persist: # m4-destroy is not persistent
            self.myMessages.add(signed) # will be persisted by caller
            # This will be added to the DB, and committed, by our caller, to
            # get it into the same transaction as the update to which inbound
            # messages we've processed.
        assert VALID_MESSAGE.search(signed), signed
        self.manager.sendToAll(self.inviteID, signed)

    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")
开发者ID:ggozad,项目名称:petmail,代码行数:70,代码来源:invitation.py

示例6: init

# 需要导入模块: from nacl.signing import SigningKey [as 别名]
# 或者: from nacl.signing.SigningKey import sign [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.sign方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。