Skip to content

Instantly share code, notes, and snippets.

@jedisct1
Created August 7, 2013 20:49
Show Gist options
  • Save jedisct1/6178503 to your computer and use it in GitHub Desktop.
Save jedisct1/6178503 to your computer and use it in GitHub Desktop.
crypto_secretbox_example.c
#include <stdio.h>
#include <string.h>
#include <sodium.h>
#define PLAINTEXT "123456789"
#define PLAINTEXT_LEN (sizeof PLAINTEXT)
int main(void)
{
sodium_init();
size_t mlen = PLAINTEXT_LEN + crypto_secretbox_ZEROBYTES;
unsigned char mpad[mlen];
unsigned char cwithnonce[crypto_secretbox_NONCEBYTES + mlen];
unsigned char *cpad = cwithnonce + crypto_secretbox_NONCEBYTES;
unsigned char key[crypto_secretbox_KEYBYTES];
randombytes_buf(key, sizeof key);
randombytes_buf(cwithnonce, crypto_secretbox_NONCEBYTES);
memset(mpad, 0, crypto_secretbox_ZEROBYTES);
memcpy(mpad + crypto_secretbox_ZEROBYTES, "123456789", PLAINTEXT_LEN);
crypto_secretbox(cpad, mpad, mlen, cwithnonce, key);
size_t clen = mlen;
unsigned char mpad2[clen];
cpad = cwithnonce + crypto_secretbox_NONCEBYTES;
memset(cpad, 0, crypto_secretbox_BOXZEROBYTES);
int res = crypto_secretbox_open(mpad2, cpad, clen,
cwithnonce, key);
printf("%d %s\n", res, mpad2 + crypto_secretbox_ZEROBYTES);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment