Created
March 1, 2013 00:59
-
-
Save kballenegger/5061604 to your computer and use it in GitHub Desktop.
A working test of using NaCl's crypto_box.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <sodium/crypto_box.h> | |
#include <sodium/randombytes.h> | |
int main(int argc, char *argv[]) { | |
// payload | |
unsigned char payload[] = "Hello world, this is a test payload to test NaCl's cipher."; | |
unsigned char payload_padded[crypto_box_ZEROBYTES + sizeof(payload)] = {0}; | |
for (int i = 0; i < sizeof(payload); i++) | |
*(payload_padded + crypto_box_ZEROBYTES + i) = *(payload + i); | |
// print original | |
printf("Originally: "); | |
for (int i = 0; i < sizeof(payload_padded); i++) printf("%x ", payload_padded[i]); | |
printf("\n"); | |
// generate two key pairs | |
unsigned char public_key_client[crypto_box_PUBLICKEYBYTES]; | |
unsigned char secret_key_client[crypto_box_SECRETKEYBYTES]; | |
crypto_box_keypair(public_key_client, secret_key_client); | |
unsigned char public_key_server[crypto_box_PUBLICKEYBYTES]; | |
unsigned char secret_key_server[crypto_box_SECRETKEYBYTES]; | |
crypto_box_keypair(public_key_server, secret_key_server); | |
// generate a salt | |
unsigned char salt[crypto_box_NONCEBYTES]; | |
randombytes(salt, sizeof(salt)); | |
// output | |
unsigned char cipher_text[crypto_box_ZEROBYTES + sizeof(payload)] = {0}; | |
// encrypt a payload | |
crypto_box(cipher_text, payload_padded, sizeof(payload_padded), salt, public_key_server, secret_key_client); | |
// print ciphertext as hex | |
printf("Ciphered: "); | |
for (int i = 0; i < sizeof(cipher_text); i++) printf("%x ", cipher_text[i]); | |
printf("\n"); | |
// decrypt a payload | |
unsigned char decrypted_payload[crypto_box_ZEROBYTES + sizeof(payload)] = {0}; | |
crypto_box_open(decrypted_payload, cipher_text, sizeof(cipher_text), salt, public_key_client, secret_key_server); | |
// print deciphered | |
printf("Deciphered: "); | |
for (int i = 0; i < sizeof(decrypted_payload); i++) printf("%x ", decrypted_payload[i]); | |
printf("\n"); | |
// print string :) | |
printf("Plaintext: %s\n", (char *)(decrypted_payload + crypto_box_ZEROBYTES)); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment