Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
async def test_explicit_permanent_key_unavailable(
self, server_no_key, server, client_factory
):
"""
Check that the server rejects a permanent key if the server
has none.
"""
key = libnacl.public.SecretKey()
# Expect invalid key
with pytest.raises(websockets.ConnectionClosed) as exc_info:
await client_factory(
server=server_no_key, permanent_key=key.pk, explicit_permanent_key=True,
initiator_handshake=True)
assert exc_info.value.code == CloseCode.invalid_key
await server.wait_connections_closed()
def __init__(self, crypt=None, sign=None):
self.crypt = libnacl.public.SecretKey(crypt)
self.signer = libnacl.sign.Signer(sign)
self.sk = self.crypt.sk
self.seed = self.signer.seed
self.pk = self.crypt.pk
self.vk = self.signer.vk
"""
# Read key file (if any)
try:
with open(key) as file:
key = file.readline().strip()
except IOError:
pass
# Un-hexlify
try:
key = binascii.unhexlify(key)
except binascii.Error as exc:
raise ValueError('Could not decode key') from exc
# Convert to private key (raises ValueError on its own)
return libnacl.public.SecretKey(sk=key)
salt-call nacl.keygen
salt-call nacl.keygen sk_file=/etc/salt/pki/master/nacl
salt-call nacl.keygen sk_file=/etc/salt/pki/master/nacl pk_file=/etc/salt/pki/master/nacl.pub
salt-call --local nacl.keygen
'''
if 'keyfile' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'keyfile\' argument has been deprecated and will be removed in Salt '
'{version}. Please use \'sk_file\' argument instead.'
)
sk_file = kwargs['keyfile']
if sk_file is None:
kp = libnacl.public.SecretKey()
return {'sk': base64.b64encode(kp.sk), 'pk': base64.b64encode(kp.pk)}
if pk_file is None:
pk_file = '{0}.pub'.format(sk_file)
if sk_file and pk_file is None:
if not os.path.isfile(sk_file):
kp = libnacl.public.SecretKey()
with salt.utils.files.fopen(sk_file, 'wb') as keyf:
keyf.write(base64.b64encode(kp.sk))
if salt.utils.platform.is_windows():
cur_user = salt.utils.win_functions.get_current_user()
salt.utils.win_dacl.set_owner(sk_file, cur_user)
salt.utils.win_dacl.set_permissions(sk_file, cur_user, 'full_control', 'grant', reset_perms=True, protected=True)
else:
# chmod 0600 file
Nonce = NewType('Nonce', bytes)
# A packet including nonce and payload as bytes as received/sent
Packet = NewType('Packet', bytes)
# An encrypted payload (can be decrypted to a raw payload)
EncryptedPayload = NewType('EncryptedPayload', bytes)
# A raw payload (can be unpacked to a payload)
RawPayload = NewType('RawPayload', bytes)
# The payload as expected by the protocol (always dict-like in our implementation)
Payload = MutableMapping[str, Any]
# Protocol
# --------
# One of the server's secret permanent key pairs
ServerSecretPermanentKey = NewType('ServerSecretPermanentKey', libnacl.public.SecretKey)
# The server's secret session key pair
ServerSecretSessionKey = NewType('ServerSecretSessionKey', libnacl.public.SecretKey)
# Box for encrypting/decrypting messages
MessageBox = NewType('MessageBox', libnacl.public.Box)
# Box for "signing" the keys in the 'server-auth' message
SignBox = NewType('SignBox', libnacl.public.Box)
# A job of the job queue
Job = Awaitable[None]
# Task
# ----
# A consolidated result
Result = NewType('Result', BaseException)
def generate(key_file: str) -> None:
# Generate key pair
key_pair = libnacl.public.SecretKey()
# Write hex-encoded private key to file using proper permissions (0o400)
perm_other = stat.S_IROTH | stat.S_IWOTH | stat.S_IXOTH
perm_group = stat.S_IRGRP | stat.S_IWGRP | stat.S_IXGRP
current_umask = os.umask(perm_other | perm_group)
with open(key_file, 'wb') as file:
file.write(key_pair.hex_sk())
os.umask(current_umask)
# Print public key
click.echo('Public permanent key: {}'.format(key_pair.hex_pk().decode('ascii')))
:param pubkey: Public key of the recipient
:param nonce: Unique nonce used by the sender
:param text: Encrypted message
:return:
"""
sender_pubkey = PublicKey(pubkey)
nonce_bytes = ensure_bytes(nonce)
encrypt_bytes = Base58Encoder.decode(text)
decrypt_bytes = libnacl.public.Box(self, sender_pubkey).decrypt(
encrypt_bytes, nonce_bytes
)
return decrypt_bytes.decode("utf-8")
class PublicKey(libnacl.public.PublicKey):
def __init__(self, pubkey: str) -> None:
"""
Create instance of libnacl ed25519 sign PublicKey from a base58 public key
:param pubkey: Base58 public key
"""
key = Base58Encoder.decode(pubkey)
super().__init__(key)
def base58(self) -> str:
"""
Return a base58 encoded string of the public key
"""
return Base58Encoder.encode(self.pk)
def encrypt_seal(self, data: Union[str, bytes]) -> bytes:
def init_pubkey(hexpk, fname=None):
"""Create a pubkey object from a
hex formatted string.
Save to file fname if specified.
"""
try:
bin_pk = binascii.unhexlify(hexpk)
except TypeError:
raise NaclError("Invalid hex")
if not len(bin_pk) == 32:
raise NaclError("Public key must be 32 bytes")
pk = public.PublicKey(binascii.unhexlify(hexpk))
if fname:
pk.save(fname)
return pk