warp-vpn

point to point VPN implementation
git clone git://git.2f30.org/warp-vpn
Log | Files | Refs | README

crypto.c (1589B)


      1 #include <string.h>
      2 
      3 #include <sodium.h>
      4 
      5 #include "warp.h"
      6 
      7 static unsigned char key[crypto_aead_chacha20poly1305_IETF_KEYBYTES];
      8 
      9 void
     10 cryptoinit(void)
     11 {
     12 	if (sodium_init() == -1)
     13 		fatalx("failed to initialize crypto engine");
     14 }
     15 
     16 void
     17 derivekey(char *pw)
     18 {
     19 	unsigned char salt[crypto_pwhash_SALTBYTES];
     20 
     21 	memset(salt, 0, sizeof(salt)); /* XXX */
     22 	if (crypto_pwhash(key, sizeof(key), pw, strlen(pw), salt,
     23 	                  crypto_pwhash_OPSLIMIT_INTERACTIVE,
     24 	                  crypto_pwhash_MEMLIMIT_INTERACTIVE,
     25 	                  crypto_pwhash_ALG_DEFAULT) != 0)
     26 		fatalx("failed to derive key");
     27 }
     28 
     29 size_t
     30 cryptononcelen(void)
     31 {
     32 	return crypto_aead_chacha20poly1305_IETF_NPUBBYTES;
     33 }
     34 
     35 size_t
     36 cryptotaglen(void)
     37 {
     38 	return crypto_aead_chacha20poly1305_IETF_ABYTES;
     39 }
     40 
     41 int cryptoseal(unsigned char *c, unsigned long long *clen,
     42                const unsigned char *m, unsigned long long mlen,
     43                const unsigned char *ad, unsigned long long adlen,
     44                const unsigned char *npub)
     45 {
     46 	return crypto_aead_chacha20poly1305_ietf_encrypt(c, clen, m, mlen,
     47 	                                                 ad, adlen, NULL,
     48 	                                                 npub, key);
     49 }
     50 
     51 int cryptoopen(unsigned char *m, unsigned long long *mlen,
     52                const unsigned char *c, unsigned long long clen,
     53                const unsigned char *ad, unsigned long long adlen,
     54                const unsigned char *npub)
     55 {
     56 	return crypto_aead_chacha20poly1305_ietf_decrypt(m, mlen, NULL, c, clen,
     57 	                                                 ad, adlen, npub, key);
     58 }