Here is the pseudocode for generating the XSalsa20 state:
Input: 256-bit key, 64-bit nonce
// Concatenate key and nonce to get 320-bit input
input = key || nonce
// Initialize state to hash input
state = Salsa20_Hash(input)
// Salsa20_Hash function:
function Salsa20_Hash(input):
// Initialize state to 16 32-bit words
state = [0x61707865, 0x3320646e, 0x79622d32, 0x6b206574,
0x6f2c2062, 0x72657320, 0x202, 0x6465666b,
0x73692077, 0x6f742061, 0x6e6f6974, 0x6172206f,
0x656d2074, 0x65722073, 0x61747320, 0x65636165]
// Add input words to state
state[4] += (input[0] & 0xffffffff)
state[5] += (input[1] & 0xffffffff)
state[6] += (input[2] & 0xffffffff)
state[7] += (input[3] & 0xffffffff)
// Apply 20 rounds of Salsa20
for i in 1 to 20:
// Compute salsa20 round
state = Salsa20Round(state)
// Return final state
return state
end function
// Salsa20Round function
function Salsa20Round(state):
// Apply circular rotation on state words
state = CircularRotate(state, 16)
// Add round constant to state
state[0] += 0x61707865
// Apply XOR based on a predefined matrix
for i in 0 to 15:
state[i] ^= ((state[(i + 4) % 16]) + (state[(i + 8) % 16]) + (state[i] >> 3)) & 0xffffffff
// Return state after round
return state
end function
This pseudocode shows how the initial state is generated by hashing the key and nonce using the Salsa20_Hash function. That function initializes the state, adds the key and nonce words, and applies 20 rounds of the Salsa20Round function. The Salsa20Round function rotates the state, adds a round constant, and applies XORs based on a predefined pattern. After 20 rounds, the final state is returned and used for keystream generation.
Let me know if you have any questions about this pseudocode!