Here is a Python implementation of the Salsa20 stream cipher. It is based on the reference implementation found in the eSTREAM Portfolio.
code
# Salsa20 implementation in Python
from struct import pack, unpack
def rotate(x, n):
return ((x << n) & 0xffffffff) | ((x >> (32 - n)) & 0xffffffff)
def quarter_round(a, b, c, d):
a = a + b
d = rotate(d ^ a, 16)
c = c + d
b = rotate(b ^ c, 12)
a = a + b
d = rotate(d ^ a, 8)
c = c + d
b = rotate(b ^ c, 7)
return a, b, c, d
def column_round(a, b, c, d):
a, b, c, d = quarter_round(a, b, c, d)
a, c = c, a
a, b, c, d = quarter_round(a, b, c, d)
a, c = c, a
return a, b, c, d
def row_round(a, b, c, d):
a, b, c, d = quarter_round(a, b, c, d)
b, d = d, b
a, b, c, d = quarter_round(a, b, c, d)
b, d = d, b
return a, b, c, d
def double_round(x):
for i in range(0, 4):
x[i], x[i+4], x[i+8], x[i+12] = column_round(x[i], x[i+4], x[i+8], x[i+12])
for i in range(0, 16):
x[i] = rotate(x[i] + x[(i+5) % 16] + x[(i+13) % 16], 32 - i % 32)
for i in range(0, 4):
x[i+16], x[i+20], x[i+24], x[i+28] = row_round(x[i+16], x[i+20], x[i+24], x[i+28])
for i in range(0, 16):
x[i+16] = rotate(x[i+16] + x[(i+9) % 16] + x[(i+17) % 16] + x[i], 32 - (i+16) % 32)
def salsa20_core(x):
for i in range(0, 10):
double_round(x)
def salsa20(key, nonce, block_count=0):
# Convert key and nonce to little-endian 32-bit words
key_words = [unpack("<I", key[i:i+4])[0] for i in range(0, len(key), 4)]
nonce_words = [unpack("<I", nonce[i:i+4])[0] for i in range(0, len(nonce), 4)]
# Expand key and nonce into Salsa20 state
x = [0] * 64
for i in range(0, 16):
x[i] = key_words[i] if i < len(key_words) else 0
x[i+16] = nonce_words[i // 2] << ((i % 2) * 16) | block_count if i < 4 else 0
x[i+32] = 0x61707865 if i == 0 else 0x3320646e if i == 1 else 0x79622d32 if i == 2 else 0x6b206574
# Run Salsa20 core function
salsa20_core(x)
# Ext