本文整理汇总了Python中nacl.secret.SecretBox.decrypt方法的典型用法代码示例。如果您正苦于以下问题:Python SecretBox.decrypt方法的具体用法?Python SecretBox.decrypt怎么用?Python SecretBox.decrypt使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类nacl.secret.SecretBox
的用法示例。
在下文中一共展示了SecretBox.decrypt方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __enter__
# 需要导入模块: from nacl.secret import SecretBox [as 别名]
# 或者: from nacl.secret.SecretBox import decrypt [as 别名]
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
示例2: test_records_good
# 需要导入模块: from nacl.secret import SecretBox [as 别名]
# 或者: from nacl.secret.SecretBox import decrypt [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])
示例3: test_secret_box_wrong_lengths
# 需要导入模块: from nacl.secret import SecretBox [as 别名]
# 或者: from nacl.secret.SecretBox import decrypt [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"")
示例4: _decrypt_data
# 需要导入模块: from nacl.secret import SecretBox [as 别名]
# 或者: from nacl.secret.SecretBox import decrypt [as 别名]
def _decrypt_data(self, key, encrypted):
assert isinstance(key, type(b"")), type(key)
assert isinstance(encrypted, type(b"")), type(encrypted)
if len(key) != SecretBox.KEY_SIZE: raise UsageError
box = SecretBox(key)
data = box.decrypt(encrypted)
return data
示例5: EncryptedSerializer
# 需要导入模块: from nacl.secret import SecretBox [as 别名]
# 或者: from nacl.secret.SecretBox import decrypt [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'=')
示例6: test_secret_box_decryption_combined
# 需要导入模块: from nacl.secret import SecretBox [as 别名]
# 或者: from nacl.secret.SecretBox import decrypt [as 别名]
def test_secret_box_decryption_combined(key, nonce, plaintext, ciphertext):
box = SecretBox(key, encoder=HexEncoder)
combined = binascii.hexlify(binascii.unhexlify(nonce) + binascii.unhexlify(ciphertext))
decrypted = binascii.hexlify(box.decrypt(combined, encoder=HexEncoder))
assert decrypted == plaintext
示例7: decrypt
# 需要导入模块: from nacl.secret import SecretBox [as 别名]
# 或者: from nacl.secret.SecretBox import decrypt [as 别名]
def decrypt(ciphertext, keyPath):
"""
Decrypts a given message that was encrypted with the encrypt() method.
:param ciphertext: The encrypted message (as a string).
:param keyPath: A path to a file containing a 256-bit key (and nothing else).
:type keyPath: str
:rtype: str
Raises an error if ciphertext was modified
>>> import tempfile
>>> k = tempfile.mktemp()
>>> with open(k, 'w') as f:
... f.write(nacl.utils.random(SecretBox.KEY_SIZE))
>>> ciphertext = encrypt("testMessage", k)
>>> ciphertext = chr(ord(ciphertext[0]) ^ 1) + ciphertext[1:]
>>> decrypt(ciphertext, k)
Traceback (most recent call last):
...
CryptoError: Decryption failed. Ciphertext failed verification
Otherwise works correctly
>>> decrypt(encrypt("testMessage", k), k)
'testMessage'
"""
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)
# The nonce is kept with the message.
return sb.decrypt(ciphertext)
示例8: _decrypt_data
# 需要导入模块: from nacl.secret import SecretBox [as 别名]
# 或者: from nacl.secret.SecretBox import decrypt [as 别名]
def _decrypt_data(self, key, encrypted):
assert isinstance(key, type(b"")), type(key)
assert isinstance(encrypted, type(b"")), type(encrypted)
assert len(key) == SecretBox.KEY_SIZE, len(key)
box = SecretBox(key)
data = box.decrypt(encrypted)
return data
示例9: __init__
# 需要导入模块: from nacl.secret import SecretBox [as 别名]
# 或者: from nacl.secret.SecretBox import decrypt [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()
示例10: test_secret_box_optional_nonce
# 需要导入模块: from nacl.secret import SecretBox [as 别名]
# 或者: from nacl.secret.SecretBox import decrypt [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
示例11: handshake_initiate
# 需要导入模块: from nacl.secret import SecretBox [as 别名]
# 或者: from nacl.secret.SecretBox import decrypt [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': ''}
示例12: decrypt_list_entry
# 需要导入模块: from nacl.secret import SecretBox [as 别名]
# 或者: from nacl.secret.SecretBox import decrypt [as 别名]
def decrypt_list_entry(boxed, symkey, tmppub):
sbox = SecretBox(symkey)
msg = remove_prefix(sbox.decrypt(boxed),
"list:", NotListResponseError)
(got_tmppub, fetch_token, delete_token,
length) = struct.unpack(">32s32s32sQ", msg)
if not equal(got_tmppub, tmppub):
raise WrongPubkeyError
return fetch_token, delete_token, length
示例13: test_secret_box_decryption
# 需要导入模块: from nacl.secret import SecretBox [as 别名]
# 或者: from nacl.secret.SecretBox import decrypt [as 别名]
def test_secret_box_decryption(key, nonce, plaintext, ciphertext):
box = SecretBox(key, encoder=HexEncoder)
nonce = binascii.unhexlify(nonce)
decrypted = binascii.hexlify(
box.decrypt(ciphertext, nonce, encoder=HexEncoder),
)
assert decrypted == plaintext
示例14: PassphraseBox
# 需要导入模块: from nacl.secret import SecretBox [as 别名]
# 或者: from nacl.secret.SecretBox import decrypt [as 别名]
class PassphraseBox(object):
ITERATIONS = 90000
# Given passphrase and plaintext as strings, returns a dict
# containing the ciphertext and other values needed for later
# decryption. Binary values are encoded as hexadecimal strings.
@classmethod
def encrypt(cls, passphrase, plaintext):
box = cls(passphrase)
return box._encrypt(plaintext)
# encrypted = dict(salt=salt, nonce=nonce, ciphertext=ciphertext)
# PassphraseBox.decrypt("my great password", encrypted)
@classmethod
def decrypt(cls, passphrase, encrypted):
salt = encrypted['salt']
iterations = encrypted['iterations']
return cls(passphrase, salt, iterations)._decrypt(
encrypted['ciphertext'], encrypted['nonce'])
# Initialize with an existing salt and iterations to allow
# decryption. Otherwise, creates new values for these, meaning
# it creates an entirely new secret box.
def __init__(self, passphrase, salt=None, iterations=None):
passphrase = passphrase.encode('utf-8')
self.salt = salt.decode('hex') if salt else urandom(16)
if iterations:
self.iterations = iterations
else:
# per OWASP, use a random number of iterations between 90k and 110k
self.iterations = self.ITERATIONS + randint(0,20000)
key = pbkdf2_bin(passphrase,
salt=self.salt,
iterations=self.iterations,
keylen=32)
self.box = SecretBox(key)
def _encrypt(self, plaintext):
plaintext = plaintext.encode('utf-8')
nonce = urandom(SecretBox.NONCE_SIZE)
encrypted = self.box.encrypt(plaintext, nonce)
ciphertext = encrypted.ciphertext
return dict(
salt=self.salt.encode('hex'), iterations=self.iterations,
nonce=nonce.encode('hex'), ciphertext=ciphertext.encode('hex')
)
def _decrypt(self, ciphertext, nonce):
return self.box.decrypt(ciphertext.decode('hex'), nonce.decode('hex'))
示例15: test_secret_box_bad_decryption
# 需要导入模块: from nacl.secret import SecretBox [as 别名]
# 或者: from nacl.secret.SecretBox import decrypt [as 别名]
def test_secret_box_bad_decryption():
box = SecretBox(b"\x11" * 32)
ciphertext = box.encrypt(b"hello")
with pytest.raises(CryptoError):
# changes the nonce
box.decrypt(flip_byte(ciphertext, 0))
with pytest.raises(CryptoError):
# changes ciphertext
box.decrypt(flip_byte(ciphertext, 24))
with pytest.raises(CryptoError):
# changes MAC tag
box.decrypt(flip_byte(ciphertext, len(ciphertext) - 1))
with pytest.raises(CryptoError):
# completely changes ciphertext and tag
box.decrypt(ciphertext + b"\x00")
with pytest.raises(CryptoError):
# completely changes everything
box.decrypt(b"\x00" + ciphertext)