XSalsa20Poly1305.c 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #include "XSalsa20Poly1305.h"
  2. #include <sodium.h>
  3. #include <glib.h>
  4. int decrypt_string_xs(const char *key, const char *str, char *dest, int len) {
  5. if (!key || !key[0])
  6. return 0;
  7. gsize out_len;
  8. guchar * nonce_ciphertext;
  9. /* base64 decode the message */
  10. nonce_ciphertext = g_base64_decode(str, &out_len);
  11. int MESSAGE_LEN = out_len-(crypto_secretbox_NONCEBYTES+crypto_secretbox_MACBYTES);
  12. int CIPHERTEXT_LEN = crypto_secretbox_MACBYTES + MESSAGE_LEN;
  13. /* split it into nonce and ciphertext again */
  14. unsigned char nonce[crypto_secretbox_NONCEBYTES];
  15. unsigned char ciphertext[CIPHERTEXT_LEN];
  16. memcpy(nonce, nonce_ciphertext, crypto_secretbox_NONCEBYTES);
  17. memcpy(ciphertext, nonce_ciphertext + crypto_secretbox_NONCEBYTES, CIPHERTEXT_LEN);
  18. g_free(nonce_ciphertext);
  19. /* decrypt the message */
  20. if (crypto_secretbox_open_easy((unsigned char*)dest, ciphertext, CIPHERTEXT_LEN, nonce, (unsigned char*)key) != 0) {
  21. /* cannot decrypt */
  22. return 1;
  23. }
  24. return 0;
  25. }
  26. int encrypt_string_xs(const char *key, const char *str, char *dest, int len) {
  27. if (!key || !key[0])
  28. return 0;
  29. unsigned char nonce[crypto_secretbox_NONCEBYTES];
  30. unsigned char ciphertext[crypto_secretbox_MACBYTES+len];
  31. /* choosing a random nonce */
  32. randombytes_buf(nonce, crypto_secretbox_NONCEBYTES);
  33. /* encrypt the message */
  34. crypto_secretbox_easy(ciphertext, (const unsigned char*)str, len, nonce, (const unsigned char*)key);
  35. /* put nonce and ciphertext together */
  36. guchar nonce_ciphertext[crypto_secretbox_MACBYTES + len + crypto_secretbox_NONCEBYTES];
  37. memcpy(nonce_ciphertext, nonce, crypto_secretbox_NONCEBYTES);
  38. memcpy(nonce_ciphertext+crypto_secretbox_NONCEBYTES, ciphertext, crypto_secretbox_MACBYTES + len);
  39. /* and base64 encode it */
  40. gchar * encoded_str;
  41. encoded_str = g_base64_encode(nonce_ciphertext, crypto_secretbox_MACBYTES + len + crypto_secretbox_NONCEBYTES);
  42. strncpy(dest, encoded_str, ((crypto_secretbox_MACBYTES + len + crypto_secretbox_NONCEBYTES + 2) / 3 * 4) + 1);
  43. /* clean up a bit (maybe not needed) */
  44. sodium_memzero(nonce_ciphertext, crypto_secretbox_MACBYTES + len + crypto_secretbox_NONCEBYTES);
  45. sodium_memzero(ciphertext, crypto_secretbox_MACBYTES+len);
  46. sodium_memzero(nonce, crypto_secretbox_NONCEBYTES);
  47. /* sodium_memzero encoded_str? */
  48. g_free(encoded_str);
  49. return 1;
  50. }
  51. void encrypt_key_xs(const char *key, char *encryptedKey) {
  52. }