Salsa20
Salsa20 is a stream cipher designed by Daniel J. Bernstein. The secret key is by preference 256 bits long, but it can also work with 128 bit keys.
This is an example of how Salsa20
can encrypt data:
>>> from Crypto.Cipher import Salsa20
>>>
>>> plaintext = b'Attack at dawn'
>>> secret = b'*Thirty-two byte (256 bits) key*'
>>> cipher = Salsa20.new(key=secret)
>>> msg = cipher.nonce + cipher.encrypt(plaintext)
And this is how you would decrypt it:
>>> from Crypto.Cipher import Salsa20
>>>
>>> secret = b'*Thirty-two byte (256 bits) key*'
>>> msg_nonce = msg[:8]
>>> ciphertext = msg[8:]
>>> cipher = Salsa20.new(key=secret, nonce=msg_nonce)
>>> plaintext = cipher.decrypt(ciphertext)
Warning
Salsa20
does not guarantee authenticity of the data you decrypt!
In other words, an attacker may manipulate the data in transit.
In order to prevent that, you must also use a Message Authentication
Code (such as HMAC) to authenticate the ciphertext
(encrypt-then-mac).
- class Crypto.Cipher.Salsa20.Salsa20Cipher(key, nonce)
Salsa20 cipher object. Do not create it directly. Use
new()
instead.- Variables:
nonce (byte string) – The nonce with length 8
- decrypt(ciphertext, output=None)
Decrypt a piece of data.
- Parameters:
ciphertext (bytes/bytearray/memoryview) – The data to decrypt, of any size.
- Keyword Arguments:
output (bytes/bytearray/memoryview) – The location where the plaintext is written to. If
None
, the plaintext is returned.- Returns:
If
output
isNone
, the plaintext is returned asbytes
. Otherwise,None
.
- encrypt(plaintext, output=None)
Encrypt a piece of data.
- Parameters:
plaintext (bytes/bytearray/memoryview) – The data to encrypt, of any size.
- Keyword Arguments:
output (bytes/bytearray/memoryview) – The location where the ciphertext is written to. If
None
, the ciphertext is returned.- Returns:
If
output
isNone
, the ciphertext is returned asbytes
. Otherwise,None
.
- Crypto.Cipher.Salsa20.new(key, nonce=None)
Create a new Salsa20 cipher
- Keyword Arguments:
key – The secret key to use. It must be 16 or 32 bytes long.
nonce –
A value that must never be reused for any other encryption done with this key. It must be 8 bytes long.
If not provided, a random byte string will be generated (you can read it back via the
nonce
attribute of the returned object).
- Return:
a
Crypto.Cipher.Salsa20.Salsa20Cipher
object