Skip to content

Instantly share code, notes, and snippets.

@hirokuma
Last active May 1, 2017 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hirokuma/cf6f9a00d9dfa228832f021b96b968de to your computer and use it in GitHub Desktop.
Save hirokuma/cf6f9a00d9dfa228832f021b96b968de to your computer and use it in GitHub Desktop.
//
// $ git clone https://github.com/jedisct1/libsodium
// $ cd libsodium
// $ mkdir mylib
// $ ./autogen.sh
// $ ./configure --prefix=`pwd`/mylib --disable-shared
// $ make
// $ make install
// $ cd mylib
// $ gcc -Iinclude -o tst test_chacha20.c -Llib -lsodium
// $ ./tst
//
#include <stdio.h>
#include <stdlib.h>
#include <sodium/crypto_stream_chacha20.h>
#include <sodium/crypto_aead_chacha20poly1305.h>
#include <sodium/randombytes.h>
#define MESSAGE "digital television"
#define MESSAGE_LEN (sizeof(MESSAGE) - 1)
#define ADDITIONAL_DATA "abcdef"
#define ADDITIONAL_DATA_LEN (sizeof(ADDITIONAL_DATA) - 1)
// https://download.libsodium.org/doc/secret-key_cryptography/original_chacha20-poly1305_construction.html
void func(void)
{
unsigned char nonce[crypto_aead_chacha20poly1305_NPUBBYTES];
unsigned char key[crypto_aead_chacha20poly1305_KEYBYTES];
unsigned char ciphertext[MESSAGE_LEN + crypto_aead_chacha20poly1305_ABYTES];
unsigned long long ciphertext_len;
randombytes_buf(key, sizeof key);
randombytes_buf(nonce, sizeof nonce);
crypto_aead_chacha20poly1305_encrypt(ciphertext, &ciphertext_len,
(unsigned char *)MESSAGE, MESSAGE_LEN,
(unsigned char *)ADDITIONAL_DATA, ADDITIONAL_DATA_LEN,
NULL, nonce, key);
printf("enc= ");
for (int lp = 0; lp < ciphertext_len; lp++) {
printf("%02x", ciphertext[lp]);
}
printf("\n\n");
unsigned char decrypted[MESSAGE_LEN];
unsigned long long decrypted_len;
if (crypto_aead_chacha20poly1305_decrypt(decrypted, &decrypted_len,
NULL,
ciphertext, ciphertext_len,
(unsigned char *)ADDITIONAL_DATA,
ADDITIONAL_DATA_LEN,
nonce, key) != 0) {
/* message forged! */
}
printf("dec= ");
for (int lp = 0; lp < decrypted_len; lp++) {
printf("%02x(%c) ", decrypted[lp], decrypted[lp]);
}
printf("\n\n");
}
int main(void)
{
const uint8_t NONCE[] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
const char STR[] = "abcdefghi";
int ret;
uint8_t out[8];
unsigned long long outlen = sizeof(out);
ret = crypto_stream_chacha20(out, outlen, NONCE, STR);
printf("crypto_stream_chacha20: ret=%d\n", ret);
for (int lp = 0; lp < sizeof(out); lp++) {
printf("%02x", out[lp]);
}
printf("\n\n");
ret = crypto_stream_chacha20_ietf(out, outlen, NONCE, STR);
printf("crypto_stream_chacha20_ietf: ret=%d\n", ret);
for (int lp = 0; lp < sizeof(out); lp++) {
printf("%02x", out[lp]);
}
printf("\n\n");
func();
return 0;
}
@hirokuma
Copy link
Author

hirokuma commented May 1, 2017

サイズを小さくしたくてenable-minimalしたけど、意味が違う。。。
ので、消した。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment