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


Python SecretBox.encrypt方法代码示例

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


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

示例1: __exit__

# 需要导入模块: from nacl.secret import SecretBox [as 别名]
# 或者: from nacl.secret.SecretBox import encrypt [as 别名]
    def __exit__(self, exc_type, exc_val, exc_tb):
        """
        Re-encrypt.
        """
        # Derive the key from the passphrase.
        derived = util.derive_passphrase(self.passphrase)

        # Generate two random nonces.
        nonce1 = random(SecretBox.NONCE_SIZE)
        nonce2 = random(SecretBox.NONCE_SIZE)

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

        s_p = self.sign.encode()
        e_p = self.encrypt.encode()

        s_e = sign_box.encrypt(s_p, nonce1)
        e_e = enc_box.encrypt(e_p, nonce2)

        # Update `self.key`.
        self.key._private_key_raw = e_e.ciphertext
        self.key._private_signing_key_raw = s_e.ciphertext

        # Bit of a mixed up name.
        self.key._private_nonce = e_e.nonce
        self.key._private_signing_nonce = s_e.nonce

        if exc_type is not None:
            raise exc_type(exc_val)
开发者ID:SunDwarf,项目名称:Gluino,代码行数:32,代码来源:private.py

示例2: test_secret_box_encryption_generates_different_nonces

# 需要导入模块: from nacl.secret import SecretBox [as 别名]
# 或者: from nacl.secret.SecretBox import encrypt [as 别名]
def test_secret_box_encryption_generates_different_nonces(key, nonce, plaintext, ciphertext):
    box = SecretBox(key, encoder=HexEncoder)

    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:pyca,项目名称:pynacl,代码行数:10,代码来源:test_secret.py

示例3: test_records_good

# 需要导入模块: from nacl.secret import SecretBox [as 别名]
# 或者: from nacl.secret.SecretBox import encrypt [as 别名]
    def test_records_good(self):
        # now make sure that outbound records are encrypted properly
        t, c, owner = self.make_connection()

        RECORD1 = b"record"
        c.send_record(RECORD1)
        buf = t.read_buf()
        expected = ("%08x" % (24+len(RECORD1)+16)).encode("ascii")
        self.assertEqual(hexlify(buf[:4]), expected)
        encrypted = buf[4:]
        receive_box = SecretBox(owner._sender_record_key())
        nonce_buf = encrypted[:SecretBox.NONCE_SIZE] # assume it's prepended
        nonce = int(hexlify(nonce_buf), 16)
        self.assertEqual(nonce, 0) # first message gets nonce 0
        decrypted = receive_box.decrypt(encrypted)
        self.assertEqual(decrypted, RECORD1)

        # second message gets nonce 1
        RECORD2 = b"record2"
        c.send_record(RECORD2)
        buf = t.read_buf()
        expected = ("%08x" % (24+len(RECORD2)+16)).encode("ascii")
        self.assertEqual(hexlify(buf[:4]), expected)
        encrypted = buf[4:]
        receive_box = SecretBox(owner._sender_record_key())
        nonce_buf = encrypted[:SecretBox.NONCE_SIZE] # assume it's prepended
        nonce = int(hexlify(nonce_buf), 16)
        self.assertEqual(nonce, 1)
        decrypted = receive_box.decrypt(encrypted)
        self.assertEqual(decrypted, RECORD2)

        # and that we can receive records properly
        inbound_records = []
        c.recordReceived = inbound_records.append

        RECORD3 = b"record3"
        send_box = SecretBox(owner._receiver_record_key())
        nonce_buf = unhexlify("%048x" % 0) # first nonce must be 0
        encrypted = send_box.encrypt(RECORD3, nonce_buf)
        length = unhexlify("%08x" % len(encrypted)) # always 4 bytes long
        c.dataReceived(length[:2])
        c.dataReceived(length[2:])
        c.dataReceived(encrypted[:-2])
        self.assertEqual(inbound_records, [])
        c.dataReceived(encrypted[-2:])
        self.assertEqual(inbound_records, [RECORD3])

        RECORD4 = b"record4"
        send_box = SecretBox(owner._receiver_record_key())
        nonce_buf = unhexlify("%048x" % 1) # nonces increment
        encrypted = send_box.encrypt(RECORD4, nonce_buf)
        length = unhexlify("%08x" % len(encrypted)) # always 4 bytes long
        c.dataReceived(length[:2])
        c.dataReceived(length[2:])
        c.dataReceived(encrypted[:-2])
        self.assertEqual(inbound_records, [RECORD3])
        c.dataReceived(encrypted[-2:])
        self.assertEqual(inbound_records, [RECORD3, RECORD4])
开发者ID:joejoeknight,项目名称:magic-wormhole,代码行数:60,代码来源:test_transit_twisted.py

示例4: test_secret_box_wrong_lengths

# 需要导入模块: from nacl.secret import SecretBox [as 别名]
# 或者: from nacl.secret.SecretBox import encrypt [as 别名]
def test_secret_box_wrong_lengths():
    with pytest.raises(ValueError):
        SecretBox(b"")

    box = SecretBox(b"ec2bee2d5be613ca82e377c96a0bf2220d823ce980cdff6279473edc52862798", encoder=HexEncoder)
    with pytest.raises(ValueError):
        box.encrypt(b"", b"")
    with pytest.raises(ValueError):
        box.decrypt(b"", b"")
开发者ID:pyca,项目名称:pynacl,代码行数:11,代码来源:test_secret.py

示例5: _encrypt_data

# 需要导入模块: from nacl.secret import SecretBox [as 别名]
# 或者: from nacl.secret.SecretBox import encrypt [as 别名]
 def _encrypt_data(self, key, data):
     assert isinstance(key, type(b"")), type(key)
     assert isinstance(data, type(b"")), type(data)
     if len(key) != SecretBox.KEY_SIZE: raise UsageError
     box = SecretBox(key)
     nonce = utils.random(SecretBox.NONCE_SIZE)
     return box.encrypt(data, nonce)
开发者ID:vikas-parashar,项目名称:magic-wormhole,代码行数:9,代码来源:transcribe.py

示例6: __init__

# 需要导入模块: from nacl.secret import SecretBox [as 别名]
# 或者: from nacl.secret.SecretBox import encrypt [as 别名]
class RecordPipe:
    def __init__(self, skt, send_key, receive_key):
        self.skt = skt
        self.send_box = SecretBox(send_key)
        self.send_nonce = 0
        self.receive_buf = ReceiveBuffer(self.skt)
        self.receive_box = SecretBox(receive_key)
        self.next_receive_nonce = 0

    def send_record(self, record):
        if not isinstance(record, type(b"")): raise UsageError
        assert SecretBox.NONCE_SIZE == 24
        assert self.send_nonce < 2**(8*24)
        assert len(record) < 2**(8*4)
        nonce = unhexlify("%048x" % self.send_nonce) # big-endian
        self.send_nonce += 1
        encrypted = self.send_box.encrypt(record, nonce)
        length = unhexlify("%08x" % len(encrypted)) # always 4 bytes long
        send_to(self.skt, length)
        send_to(self.skt, encrypted)

    def receive_record(self):
        length_buf = self.receive_buf.read(4)
        length = int(hexlify(length_buf), 16)
        encrypted = self.receive_buf.read(length)
        nonce_buf = encrypted[:SecretBox.NONCE_SIZE] # assume it's prepended
        nonce = int(hexlify(nonce_buf), 16)
        if nonce != self.next_receive_nonce:
            raise BadNonce("received out-of-order record")
        self.next_receive_nonce += 1
        record = self.receive_box.decrypt(encrypted)
        return record

    def close(self):
        self.skt.close()
开发者ID:vikas-parashar,项目名称:magic-wormhole,代码行数:37,代码来源:transit.py

示例7: add_third_party_caveat

# 需要导入模块: from nacl.secret import SecretBox [as 别名]
# 或者: from nacl.secret.SecretBox import encrypt [as 别名]
 def add_third_party_caveat(self,
                            macaroon,
                            location,
                            key,
                            key_id,
                            **kwargs):
     derived_key = truncate_or_pad(
         generate_derived_key(convert_to_bytes(key))
     )
     old_key = truncate_or_pad(binascii.unhexlify(macaroon.signature_bytes))
     box = SecretBox(key=old_key)
     verification_key_id = box.encrypt(
         derived_key, nonce=kwargs.get('nonce')
     )
     caveat = Caveat(
         caveat_id=key_id,
         location=location,
         verification_key_id=verification_key_id,
         version=macaroon.version
     )
     macaroon.caveats.append(caveat)
     encode_key = binascii.unhexlify(macaroon.signature_bytes)
     macaroon.signature = sign_third_party_caveat(
         encode_key,
         caveat._verification_key_id,
         caveat._caveat_id
     )
     return macaroon
开发者ID:ecordell,项目名称:pymacaroons,代码行数:30,代码来源:third_party.py

示例8: encrypt

# 需要导入模块: from nacl.secret import SecretBox [as 别名]
# 或者: from nacl.secret.SecretBox import encrypt [as 别名]
def encrypt(message, keyPath):
    """
    Encrypts a message given a path to a local file containing a key.

    :param message: The message to be encrypted.
    :param keyPath: A path to a file containing a 256-bit key (and nothing else).
    :type message: str
    :type keyPath: str
    :rtype: str

    A constant overhead is added to every encrypted message (for the nonce and MAC).
    >>> import tempfile
    >>> k = tempfile.mktemp()
    >>> with open(k, 'w') as f:
    ...     f.write(nacl.utils.random(SecretBox.KEY_SIZE))
    >>> message = 'test'
    >>> len(encrypt(message, k)) == encryptionOverhead + len(message)
    True
    """
    with open(keyPath) as f:
        key = f.read()
    if len(key) != SecretBox.KEY_SIZE:
        raise ValueError("Key is %d bytes, but must be exactly %d bytes" % (len(key),
                                                                            SecretBox.KEY_SIZE))
    sb = SecretBox(key)
    # We generate the nonce using secure random bits. For long enough
    # nonce size, the chance of a random nonce collision becomes
    # *much* smaller than the chance of a subtle coding error causing
    # a nonce reuse. Currently the nonce size is 192 bits--the chance
    # of a collision is astronomically low. (This approach is
    # recommended in the libsodium documentation.)
    nonce = nacl.utils.random(SecretBox.NONCE_SIZE)
    assert len(nonce) == SecretBox.NONCE_SIZE
    return str(sb.encrypt(message, nonce))
开发者ID:adamnovak,项目名称:toil,代码行数:36,代码来源:_nacl.py

示例9: encrypt_data

# 需要导入模块: from nacl.secret import SecretBox [as 别名]
# 或者: from nacl.secret.SecretBox import encrypt [as 别名]
def encrypt_data(key, plaintext):
    assert isinstance(key, type(b"")), type(key)
    assert isinstance(plaintext, type(b"")), type(plaintext)
    assert len(key) == SecretBox.KEY_SIZE, len(key)
    box = SecretBox(key)
    nonce = utils.random(SecretBox.NONCE_SIZE)
    return box.encrypt(plaintext, nonce)
开发者ID:dandes3,项目名称:magic-wormhole,代码行数:9,代码来源:_key.py

示例10: _encrypt_data

# 需要导入模块: from nacl.secret import SecretBox [as 别名]
# 或者: from nacl.secret.SecretBox import encrypt [as 别名]
 def _encrypt_data(self, key, data):
     assert isinstance(key, type(b"")), type(key)
     assert isinstance(data, type(b"")), type(data)
     assert len(key) == SecretBox.KEY_SIZE, len(key)
     box = SecretBox(key)
     nonce = utils.random(SecretBox.NONCE_SIZE)
     return box.encrypt(data, nonce)
开发者ID:asymmetric,项目名称:magic-wormhole,代码行数:9,代码来源:transcribe.py

示例11: add_third_party_caveat

# 需要导入模块: from nacl.secret import SecretBox [as 别名]
# 或者: from nacl.secret.SecretBox import encrypt [as 别名]
 def add_third_party_caveat(self,
                            macaroon,
                            location,
                            key,
                            key_id,
                            nonce=None,
                            **kwargs):
     derived_key = truncate_or_pad(
         generate_derived_key(convert_to_bytes(key))
     )
     old_key = truncate_or_pad(binascii.unhexlify(macaroon.signature_bytes))
     box = SecretBox(key=old_key)
     nonce = nonce or nacl.utils.random(box.NONCE_SIZE)
     verification_key_id = box.encrypt(
         derived_key, nonce=nonce
     )
     caveat = Caveat(
         caveat_id=key_id,
         location=location,
         verification_key_id=verification_key_id
     )
     macaroon.caveats.append(caveat)
     encode_key = binascii.unhexlify(macaroon.signature_bytes)
     macaroon.signature = sign_third_party_caveat(
         encode_key,
         caveat._verification_key_id,
         caveat._caveat_id
     )
     return macaroon
开发者ID:matrix-org,项目名称:pymacaroons,代码行数:31,代码来源:third_party.py

示例12: EncryptedSerializer

# 需要导入模块: from nacl.secret import SecretBox [as 别名]
# 或者: from nacl.secret.SecretBox import encrypt [as 别名]
class EncryptedSerializer(object):
    """Encrypt session state using PyNaCl.

    :type secret: bytes
    :param secret: a 32-byte random secret for encrypting/decrypting the
                   pickled session state.
    :param serializer:
        An object with two methods: ``loads`` and ``dumps``. The ``loads``
        method should accept bytes and return a Python object. The ``dumps``
        method should accept a Python object and return bytes. A ``ValueError``
        should be raised for malformed inputs. Default: ``None``, which will
        use :class:`pyramid.session.PickleSerializer`.
    """
    def __init__(self, secret, serializer=None):
        if len(secret) != SecretBox.KEY_SIZE:
            raise ValueError(
                "Secret should be a random bytes string of length %d" %
                SecretBox.KEY_SIZE)
        self.box = SecretBox(secret)

        if serializer is None:
            serializer = PickleSerializer()

        self.serializer = serializer

    def loads(self, bstruct):
        """Decrypt session state.

        :type encrypted_state: bytes
        :param encrypted_state: the encrypted session state.

        :rtype: :class:`dict` / picklable mapping
        :returns: the decrypted, unpickled session state, as passed as
                  ``session_state`` to :meth:`dumps`.
        """
        try:
            b64padding = b'=' * (-len(bstruct) % 4)
            fstruct = urlsafe_b64decode(bstruct + b64padding)
        except (binascii.Error, TypeError) as e:
            raise ValueError('Badly formed base64 data: %s' % e)

        try:
            payload = self.box.decrypt(fstruct)
        except CryptoError as e:
            raise ValueError('Possible tampering: %s' % e)
        return self.serializer.loads(payload)

    def dumps(self, session_state):
        """Encrypt session state.

        :type session_state: :class:`dict` / picklable mapping
        :param session_state: the session state to be encrypted.

        :rtype: bytes
        :returns: the encrypted session state
        """
        cstruct = self.serializer.dumps(session_state)
        nonce = random(SecretBox.NONCE_SIZE)
        fstruct = self.box.encrypt(cstruct, nonce)
        return urlsafe_b64encode(fstruct).rstrip(b'=')
开发者ID:Pylons,项目名称:pyramid_nacl_session,代码行数:62,代码来源:serializer.py

示例13: test_secret_box_optional_nonce

# 需要导入模块: from nacl.secret import SecretBox [as 别名]
# 或者: from nacl.secret.SecretBox import encrypt [as 别名]
def test_secret_box_optional_nonce(key, nonce, plaintext, ciphertext):
    box = SecretBox(key, encoder=HexEncoder)

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

    decrypted = binascii.hexlify(box.decrypt(encrypted, encoder=HexEncoder))

    assert decrypted == plaintext
开发者ID:pyca,项目名称:pynacl,代码行数:10,代码来源:test_secret.py

示例14: test_secret_box_encryption

# 需要导入模块: from nacl.secret import SecretBox [as 别名]
# 或者: from nacl.secret.SecretBox import encrypt [as 别名]
def test_secret_box_encryption(key, nonce, plaintext, ciphertext):
    box = SecretBox(key, encoder=HexEncoder)
    encrypted = box.encrypt(binascii.unhexlify(plaintext), binascii.unhexlify(nonce), encoder=HexEncoder)

    expected = binascii.hexlify(binascii.unhexlify(nonce) + binascii.unhexlify(ciphertext))

    assert encrypted == expected
    assert encrypted.nonce == nonce
    assert encrypted.ciphertext == ciphertext
开发者ID:pyca,项目名称:pynacl,代码行数:11,代码来源:test_secret.py

示例15: create_list_entry

# 需要导入模块: from nacl.secret import SecretBox [as 别名]
# 或者: from nacl.secret.SecretBox import encrypt [as 别名]
def create_list_entry(symkey, tmppub, length,
                      nonce=None, fetch_token=None, delete_token=None):
    assert len(tmppub) == 32
    fetch_token = fetch_token or os.urandom(32)
    delete_token = delete_token or os.urandom(32)
    msg = "list:" + struct.pack(">32s32s32sQ",
                                tmppub, fetch_token, delete_token, length)
    nonce = nonce or os.urandom(24)
    sbox = SecretBox(symkey)
    return sbox.encrypt(msg, nonce), fetch_token, delete_token
开发者ID:warner,项目名称:petmail,代码行数:12,代码来源:server.py


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