Stream Cipher ChaCha20 state and chunking #1435
-
I would like to encrypt/decrypt stream of data chunk by chunk using To demonstrate what I mean: #include <stdio.h>
#include <sodium.h>
#include <assert.h>
int main(void)
{
assert(!sodium_init());
unsigned char key[32] = { 0 };
unsigned char nonce[24] = { 0 };
const unsigned char input[] = "Hello World!";
unsigned char buff[sizeof(input)];
// This works.
assert(!crypto_stream_xchacha20_xor(buff, input, sizeof(input), nonce, key));
// Note: here would be state reset.
assert(!crypto_stream_xchacha20_xor(buff, buff, sizeof(input), nonce, key));
printf("%.*s\n", sizeof(buff), buff);
// This does not work.
assert(!crypto_stream_xchacha20_xor(buff, input, sizeof(input), nonce, key));
// Note: here would be state reset.
assert(!crypto_stream_xchacha20_xor(buff, buff, 5, nonce, key));
assert(!crypto_stream_xchacha20_xor(buff + 5, buff + 5, sizeof(input) - 5, nonce, key));
printf("%.*s\n", sizeof(buff), buff); // only first five bytes are correct
} For instance in func TestChaChaChunking(t *testing.T) {
var key [32]byte
var nonce [24]byte
// The `cipher` variable keeps the state.
cipher, err := chacha20.NewUnauthenticatedCipher(key[:], nonce[:])
if err != nil {
t.Fatal(err)
}
var buff []byte = make([]byte, 12)
cipher.XORKeyStream(buff, []byte("Hello World!"))
// Reset the state since we are switching from encryption to decryption part.
cipher, err = chacha20.NewUnauthenticatedCipher(key[:], nonce[:])
if err != nil {
t.Fatal(err)
}
// Decrypt in two chunks works all right.
cipher.XORKeyStream(buff[:5], buff[:5])
cipher.XORKeyStream(buff[5:], buff[5:])
t.Log(string(buff))f // This prints "Hello World!" correctly.
} Is there any way to do what I want ? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
I guess I could use |
Beta Was this translation helpful? Give feedback.
-
The |
Beta Was this translation helpful? Give feedback.
I guess I could use
crypto_stream_xchacha20_xor_ic()
but I must ensure chunking in multiples of block (64B) right? Then I could advance counter by chunksize/64.