irccrypt.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #include "base64.h"
  2. #include <string.h>
  3. #include <sodium.h>
  4. #define PASSWORD "Correct Horse Battery Staple"
  5. #define MESSAGE ((const unsigned char *) "We make files transfer!")
  6. #define MESSAGE_LEN 23
  7. #define CIPHERTEXT_LEN (crypto_secretbox_MACBYTES + MESSAGE_LEN)
  8. #define PREFIX_LEN 4
  9. unsigned char salt[crypto_pwhash_SALTBYTES];
  10. unsigned char nonce[crypto_secretbox_NONCEBYTES];
  11. unsigned char key[crypto_secretbox_KEYBYTES];
  12. unsigned char ciphertext[CIPHERTEXT_LEN];
  13. unsigned char decrypted[MESSAGE_LEN];
  14. int main () {
  15. /* let's derive the key from PASSWORD */
  16. randombytes_buf(salt, crypto_pwhash_SALTBYTES);
  17. if (crypto_pwhash
  18. (key, crypto_secretbox_KEYBYTES, PASSWORD, strlen(PASSWORD), salt,
  19. crypto_pwhash_OPSLIMIT_INTERACTIVE, crypto_pwhash_MEMLIMIT_INTERACTIVE,
  20. crypto_pwhash_ALG_DEFAULT) != 0) {
  21. /* out of memory */
  22. exit(2);
  23. }
  24. /* generate nonce and encrypt the message */
  25. randombytes_buf(nonce, crypto_secretbox_NONCEBYTES);
  26. crypto_secretbox_easy(ciphertext, MESSAGE, MESSAGE_LEN, nonce, key);
  27. /* put nonce and ciphertext together */
  28. unsigned char nonce_ciphertext[CIPHERTEXT_LEN + crypto_secretbox_NONCEBYTES];
  29. memcpy(nonce_ciphertext, nonce, crypto_secretbox_NONCEBYTES);
  30. memcpy(nonce_ciphertext+crypto_secretbox_NONCEBYTES, ciphertext, CIPHERTEXT_LEN);
  31. /* and base64 encode it */
  32. unsigned char base64_nonce_ciphertext[Base64encode_len(CIPHERTEXT_LEN + crypto_secretbox_NONCEBYTES)];
  33. Base64encode(base64_nonce_ciphertext, nonce_ciphertext, CIPHERTEXT_LEN + crypto_secretbox_NONCEBYTES);
  34. /*
  35. * mind the 512 byte limit!
  36. * :nickname!ident@userhostname.invalid PRIVMSG #ircchannel :+XS XXXXXX\r\n
  37. */
  38. /* now send base64_nonce_ciphertext to the other side */
  39. /* and base64 decode it */
  40. Base64decode(nonce_ciphertext, base64_nonce_ciphertext);
  41. /* split it into nonce and ciphertext again */
  42. memcpy(nonce, nonce_ciphertext, crypto_secretbox_NONCEBYTES);
  43. memcpy(ciphertext, nonce_ciphertext + crypto_secretbox_NONCEBYTES, MESSAGE_LEN);
  44. /* decrypt MESSAGE */
  45. if (crypto_secretbox_open_easy(decrypted, ciphertext, CIPHERTEXT_LEN, nonce, key) != 0) {
  46. /* cannot decrypt */
  47. exit(1);
  48. }
  49. printf("cleartext:%s\n:user!ident@hostname.invalid PRIVMSG #ircchannel :+XZ %s\ndecrypted:%s\n",MESSAGE, base64_nonce_ciphertext, decrypted);
  50. }