Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def secretbox_encrypt(data, **kwargs):
'''
Encrypt data using a secret key generated from `nacl.keygen`.
The same secret key can be used to decrypt the data using `nacl.secretbox_decrypt`.
CLI Examples:
.. code-block:: bash
salt-run nacl.secretbox_encrypt datatoenc
salt-call --local nacl.secretbox_encrypt datatoenc sk_file=/etc/salt/pki/master/nacl
salt-call --local nacl.secretbox_encrypt datatoenc sk='YmFkcGFzcwo='
'''
sk = _get_sk(**kwargs)
b = libnacl.secret.SecretBox(sk)
return base64.b64encode(b.encrypt(data))
def generate_symmetric_key():
"""
Generate a random key for symmetric encryption.
:return:
"""
box = libnacl.secret.SecretBox()
return box.sk
'''
Decrypt data that was encrypted using `nacl.secretbox_encrypt` using the secret key
that was generated from `nacl.keygen`.
CLI Examples:
.. code-block:: bash
salt-call nacl.secretbox_decrypt pEXHQM6cuaF7A=
salt-call --local nacl.secretbox_decrypt data='pEXHQM6cuaF7A=' sk_file=/etc/salt/pki/master/nacl
salt-call --local nacl.secretbox_decrypt data='pEXHQM6cuaF7A=' sk='YmFkcGFzcwo='
'''
if data is None:
return None
key = _get_sk(**kwargs)
b = libnacl.secret.SecretBox(key=key)
return b.decrypt(base64.b64decode(data))
:param val: the value to encrypt
:param secretKey: Optional key, if provided should be either in hex or bytes
:return: Tuple of the encrypted value and secret key encoded in hex
"""
if isinstance(val, str):
val = val.encode("utf-8")
if secretKey:
if isHex(secretKey):
secretKey = bytes(bytearray.fromhex(secretKey))
elif not isinstance(secretKey, bytes):
error("Secret key must be either in hex or bytes")
box = libnacl.secret.SecretBox(secretKey)
else:
box = libnacl.secret.SecretBox()
return box.encrypt(val).hex(), box.sk.hex()
def _sk_encrypt(key, data, nonce=None):
"""
Encrypt data by using secret-key encryption.
Arguments:
- `key`: A secret key.
- `data`: Data (bytes).
- `nonce`: A predefined nonce.
Return a tuple of bytes containing the nonce and the encrypted
data.
"""
# Assemble and encrypt the payload
box = libnacl.secret.SecretBox(key=key)
# Note: Workaround for libnacl which lacks `pack_nonce` option
# (see: https://github.com/saltstack/libnacl/pull/61)
# return box.encrypt(data, nonce=nonce, pack_nonce=False)
data = box.encrypt(data, nonce=nonce)
nonce_length = libnacl.crypto_secretbox_NONCEBYTES
return data[:nonce_length], data[nonce_length:]