Exemple #1
0
int zmq::curve_server_t::produce_welcome (msg_t *msg_)
{
    uint8_t cookie_nonce [crypto_secretbox_NONCEBYTES];
    uint8_t cookie_plaintext [crypto_secretbox_ZEROBYTES + 64];
    uint8_t cookie_ciphertext [crypto_secretbox_BOXZEROBYTES + 80];

    //  Create full nonce for encryption
    //  8-byte prefix plus 16-byte random nonce
    memcpy (cookie_nonce, "COOKIE--", 8);
    randombytes (cookie_nonce + 8, 16);

    //  Generate cookie = Box [C' + s'](t)
    memset (cookie_plaintext, 0, crypto_secretbox_ZEROBYTES);
    memcpy (cookie_plaintext + crypto_secretbox_ZEROBYTES,
            cn_client, 32);
    memcpy (cookie_plaintext + crypto_secretbox_ZEROBYTES + 32,
            cn_secret, 32);

    //  Generate fresh cookie key
    randombytes (cookie_key, crypto_secretbox_KEYBYTES);

    //  Encrypt using symmetric cookie key
    int rc = crypto_secretbox (cookie_ciphertext, cookie_plaintext,
                               sizeof cookie_plaintext,
                               cookie_nonce, cookie_key);
    zmq_assert (rc == 0);

    uint8_t welcome_nonce [crypto_box_NONCEBYTES];
    uint8_t welcome_plaintext [crypto_box_ZEROBYTES + 128];
    uint8_t welcome_ciphertext [crypto_box_BOXZEROBYTES + 144];

    //  Create full nonce for encryption
    //  8-byte prefix plus 16-byte random nonce
    memcpy (welcome_nonce, "WELCOME-", 8);
    randombytes (welcome_nonce + 8, crypto_box_NONCEBYTES - 8);

    //  Create 144-byte Box [S' + cookie](S->C')
    memset (welcome_plaintext, 0, crypto_box_ZEROBYTES);
    memcpy (welcome_plaintext + crypto_box_ZEROBYTES, cn_public, 32);
    memcpy (welcome_plaintext + crypto_box_ZEROBYTES + 32,
            cookie_nonce + 8, 16);
    memcpy (welcome_plaintext + crypto_box_ZEROBYTES + 48,
            cookie_ciphertext + crypto_secretbox_BOXZEROBYTES, 80);

    rc = crypto_box (welcome_ciphertext, welcome_plaintext,
                     sizeof welcome_plaintext,
                     welcome_nonce, cn_client, secret_key);
    if (rc == -1)
        return -1;

    rc = msg_->init_size (168);
    errno_assert (rc == 0);

    uint8_t * const welcome = static_cast <uint8_t *> (msg_->data ());
    memcpy (welcome, "\x07WELCOME", 8);
    memcpy (welcome + 8, welcome_nonce + 8, 16);
    memcpy (welcome + 24, welcome_ciphertext + crypto_box_BOXZEROBYTES, 144);

    return 0;
}
Exemple #2
0
void measure(void)
{
  int i;
  int loop;
  int mlen;

  for (loop = 0;loop < LOOPS;++loop) {
    for (mlen = 0;mlen <= MAXTEST_BYTES;mlen += 1 + mlen / 8) {
      randombytes(k,crypto_secretbox_KEYBYTES);
      randombytes(n,crypto_secretbox_NONCEBYTES);
      randombytes(m + crypto_secretbox_ZEROBYTES,mlen);
      randombytes(c,mlen + crypto_secretbox_ZEROBYTES);
      for (i = 0;i <= TIMINGS;++i) {
        cycles[i] = cpucycles();
	crypto_secretbox(c,m,mlen + crypto_secretbox_ZEROBYTES,n,k);
      }
      for (i = 0;i < TIMINGS;++i) cycles[i] = cycles[i + 1] - cycles[i];
      printentry(mlen,"cycles",cycles,TIMINGS);
      for (i = 0;i <= TIMINGS;++i) {
        cycles[i] = cpucycles();
	crypto_secretbox_open(m,c,mlen + crypto_secretbox_ZEROBYTES,n,k);
      }
      for (i = 0;i < TIMINGS;++i) cycles[i] = cycles[i + 1] - cycles[i];
      printentry(mlen,"open_cycles",cycles,TIMINGS);
      ++c[crypto_secretbox_ZEROBYTES];
      for (i = 0;i <= TIMINGS;++i) {
        cycles[i] = cpucycles();
	crypto_secretbox_open(m,c,mlen + crypto_secretbox_ZEROBYTES,n,k);
      }
      for (i = 0;i < TIMINGS;++i) cycles[i] = cycles[i + 1] - cycles[i];
      printentry(mlen,"forgery_open_cycles",cycles,TIMINGS);
    }
  }
}
Exemple #3
0
int main(void)
{
    int i;

    crypto_secretbox(c, m, 163, nonce, firstkey);
    for (i = 16; i < 163; ++i) {
        printf(",0x%02x", (unsigned int)c[i]);
        if (i % 8 == 7)
            printf("\n");
    }
    printf("\n");

    assert(crypto_secretbox_keybytes() > 0U);
    assert(crypto_secretbox_noncebytes() > 0U);
    assert(crypto_secretbox_zerobytes() > 0U);
    assert(crypto_secretbox_boxzerobytes() > 0U);
    assert(crypto_secretbox_macbytes() > 0U);
    assert(strcmp(crypto_secretbox_primitive(), "xsalsa20poly1305") == 0);
    assert(crypto_secretbox_keybytes()
           == crypto_secretbox_xsalsa20poly1305_keybytes());
    assert(crypto_secretbox_noncebytes()
           == crypto_secretbox_xsalsa20poly1305_noncebytes());
    assert(crypto_secretbox_zerobytes()
           == crypto_secretbox_xsalsa20poly1305_zerobytes());
    assert(crypto_secretbox_boxzerobytes()
           == crypto_secretbox_xsalsa20poly1305_boxzerobytes());
    assert(crypto_secretbox_macbytes()
           == crypto_secretbox_xsalsa20poly1305_macbytes());

    return 0;
}
main()
{
  int mlen;
  int i;
  int caught;

  for (mlen = 0;mlen < 1000 && mlen + crypto_secretbox_ZEROBYTES < sizeof m;++mlen) {
    randombytes(k,crypto_secretbox_KEYBYTES);
    randombytes(n,crypto_secretbox_NONCEBYTES);
    randombytes(m + crypto_secretbox_ZEROBYTES,mlen);
    crypto_secretbox(c,m,mlen + crypto_secretbox_ZEROBYTES,n,k);
    caught = 0;
    while (caught < 10) {
      c[random() % (mlen + crypto_secretbox_ZEROBYTES)] = random();
      if (crypto_secretbox_open(m2,c,mlen + crypto_secretbox_ZEROBYTES,n,k) == 0) {
        for (i = 0;i < mlen + crypto_secretbox_ZEROBYTES;++i)
          if (m2[i] != m[i]) {
	    printf("forgery\n");
	    return 100;
	  }
      } else {
        ++caught;
      }
    }
  }
  return 0;
}
Exemple #5
0
// We encrypt like GDBE each sector has a random
// nonce prepended to each sector.
static int crypto_write(const char *path, const char *buf, size_t size,
                        off_t off, struct fuse_file_info *inf){
  size_t written = 0;

  while(size > 0) {
    int idx = off / (block_size - crypto_PADDING);

    // Grab a random nonce
    unsigned char nonce[crypto_secretbox_NONCEBYTES];
    randombytes(nonce, crypto_secretbox_NONCEBYTES);

    // Set up the necessary buffers
    size_t to_write = size < block_size - crypto_PADDING ? size + crypto_PADDING : block_size;
    size_t msize = to_write - crypto_PADDING;
    size_t fudge = 0;

    char padding[block_size];
    if(off % (block_size - crypto_PADDING) != 0) {
      // At partial block, have to read the rest of the data
      // and append the new stuff to our buffer.
      size_t leftovers = off % (block_size - crypto_PADDING);
      off_t  block_off = idx * (block_size - crypto_PADDING);
      struct fuse_file_info of = {.flags = O_RDONLY};
      int fd = crypto_open(path, &of);
      if(fd == -1) return -errno;
      int res = crypto_read(path, padding, leftovers, block_off, &of);
      if(res < 0) return res;
      close(fd);
      if(to_write + res < block_size - crypto_PADDING)
        to_write += res;
      fudge = res;
    }

    unsigned char mpad[to_write];
    unsigned char cpad[to_write];
    memset(mpad, 0, to_write);
    memset(cpad, 0, to_write);
    memcpy(mpad + crypto_secretbox_ZEROBYTES, padding, fudge);
    memcpy(mpad + crypto_secretbox_ZEROBYTES + fudge, buf + written, msize);

    int ohno = crypto_secretbox(cpad, mpad, msize + crypto_secretbox_ZEROBYTES, nonce, key);
    if(ohno < 0) return -ENXIO;

    unsigned char block[to_write];
    memset(block, 0, to_write);
    memcpy(block, nonce, crypto_secretbox_NONCEBYTES);
    memcpy(block + crypto_secretbox_NONCEBYTES, cpad + crypto_secretbox_BOXZEROBYTES, msize + crypto_secretbox_BOXZEROBYTES);

    int res = pwrite(inf->fh, block, to_write, block_size * idx);
    if(res == -1) return -errno;

    res     -= crypto_PADDING;
    written += res - fudge;
    size    -= res - fudge;
    off     += res - fudge;
  }
Exemple #6
0
String NaCl::secret_encrypt(String msg)
{
    try
    {
        std::string message = from_ruby<std::string>(msg);
        std::string encrypted_message = crypto_secretbox(message, remote_nonce, my_secret);
        return to_ruby<std::string>(encrypted_message);
    }
    catch (int e)
    {
        return to_ruby<std::string>("");
    }
}
Exemple #7
0
static nif_term_t
salt_secretbox(nif_heap_t *hp, int argc, const nif_term_t argv[])
{
	/* salt_secretbox(Plain_text, Nonce, Secret_key) -> Cipher_text. */
	nif_bin_t 		pt;
	nif_bin_t 		nc;
	nif_bin_t 		sk;
	nif_bin_t 		ct;
	nif_term_t 		raw;
	nif_term_t 		sub;

	if (argc != 3)
		return (BADARG);

	/* Unpack arguments ensuring they're suitably typed. */
	if (! enif_inspect_iolist_as_binary(hp, argv[0], &pt))
		return (BADARG);

	if (! enif_inspect_binary(hp, argv[1], &nc))
		return (BADARG);

	if (! enif_inspect_binary(hp, argv[2], &sk))
		return (BADARG);

	/* Check constraints on size and zero prefixing. */
	if (pt.size < crypto_secretbox_ZEROBYTES || pt.size > SALT_MAX_MESSAGE_SIZE)
		return (BADARG);
	if (memcmp((const void *)pt.data, &salt_secretbox_zerobytes[0], crypto_secretbox_ZEROBYTES) != 0)
		return (BADARG);

	if (nc.size != crypto_secretbox_NONCEBYTES)
		return (BADARG);

	if (sk.size != crypto_secretbox_KEYBYTES)
		return (BADARG);

	/* Allocate space for cipher text. NB: Passing ENOMEM as BADARG. */
	if (! enif_alloc_binary(pt.size, &ct))
		return (BADARG);

	/* Perform the crypto, strip leading zeros. */
	(void)crypto_secretbox(ct.data, pt.data, pt.size, nc.data, sk.data);

	raw = enif_make_binary(hp, &ct);
	sub = enif_make_sub_binary(hp, raw, crypto_secretbox_BOXZEROBYTES, ct.size - crypto_secretbox_BOXZEROBYTES);

	return (sub);
}
void encrypt_box(uint8_t *keys, box *outer, size_t len) {
    box *inner = (box *) outer->data;

    uint8_t *outer_key = keys;
    uint8_t *inner_key = keys + BOX_KEY_LEN;

    randombytes(outer->iv, BOX_IV_LEN);
    randombytes(inner->iv, BOX_IV_LEN);

    uint8_t *data = inner->tag;
    size_t inner_len = len + crypto_secretbox_ZEROBYTES;
    memset(data, 0, crypto_secretbox_ZEROBYTES);
    assert(crypto_secretbox(data, data, inner_len, inner->iv, inner_key) == 0);

    encrypt_gcm(outer_key, outer->iv, outer->data, sizeof(box) + len, outer->tag);
}
Exemple #9
0
int encrypt_data_symmetric(uint8_t *secret_key, uint8_t *nonce, uint8_t *plain, uint32_t length, uint8_t *encrypted)
{
    if (length == 0)
        return -1;

    uint8_t temp_plain[length + crypto_secretbox_ZEROBYTES];
    uint8_t temp_encrypted[length + crypto_secretbox_MACBYTES + crypto_secretbox_BOXZEROBYTES];

    memset(temp_plain, 0, crypto_secretbox_ZEROBYTES);
    memcpy(temp_plain + crypto_secretbox_ZEROBYTES, plain, length); // Pad the message with 32 0 bytes.

    crypto_secretbox(temp_encrypted, temp_plain, length + crypto_secretbox_ZEROBYTES, nonce, secret_key);
    /* Unpad the encrypted message. */
    memcpy(encrypted, temp_encrypted + crypto_secretbox_BOXZEROBYTES, length + crypto_secretbox_MACBYTES);
    return length + crypto_secretbox_MACBYTES;
}
EncryptedMessage CryptoEngine::Encrypt(const Message &message) {


    if (secret_key_.empty()) {
        std::cout << "The secret key for symmetric encryption has not been initialized" << std::endl;
        throw g_crypto_engine_encryption_failure;
    }

    if (nonce_master_key_.empty()) {
        std::cout << "The master key for deriving the nonce is not valid" << std::endl;
        throw g_crypto_engine_encryption_failure;
    }

    if (context_.empty()) {
        std::cout << "The context identifier for deriving the nonce is not valid" << std::endl;
        throw g_crypto_engine_encryption_failure;
    }

    if (salt_.empty()) {
        std::cout << "The salt for deriving the nonce is not valid" << std::endl;
        throw g_crypto_engine_encryption_failure;
    }

    try {
        // generate the Nonce
        std::string nonce = hkdf_.DeriveNonce(nonce_master_key_, salt_);

        // Add the additional data (tcp_verion, type, message) to the string
        std::string full_clear_text(message.ToBytesString());

        // encrypt the message
        std::string cipher_text = crypto_secretbox(full_clear_text, nonce, secret_key_);

        // return the Message object so that it can be serialized to bytes
        return EncryptedMessage(nonce, cipher_text);
    } catch (std::exception& e) {
        std::cout << "CryptoEngine::Encrypt exception: " << e.what() << std::endl;
        throw g_crypto_engine_encryption_failure;
    }
}
Exemple #11
0
int main(void)
{
  int mlen;
  int i;

  for (mlen = 0;mlen < 1000 && mlen + crypto_secretbox_ZEROBYTES < sizeof m;++mlen) {
    randombytes(k,crypto_secretbox_KEYBYTES);
    randombytes(n,crypto_secretbox_NONCEBYTES);
    randombytes(m + crypto_secretbox_ZEROBYTES,mlen);
    crypto_secretbox(c,m,mlen + crypto_secretbox_ZEROBYTES,n,k);
    if (crypto_secretbox_open(m2,c,mlen + crypto_secretbox_ZEROBYTES,n,k) == 0) {
      for (i = 0;i < mlen + crypto_secretbox_ZEROBYTES;++i)
        if (m2[i] != m[i]) {
	  printf("bad decryption\n");
	  break;
	}
    } else {
      printf("ciphertext fails verification\n");
    }
  }
  return 0;
}
PyObject *pycrypto_secretbox(PyObject *self, PyObject *args, PyObject *kw){
  char *m, *n, *k;
  Py_ssize_t msize=0, nsize=0, ksize=0;
  static const char *kwlist[] = {"m", "n", "k", 0};
  unsigned int i;
  PyObject *ret;
  size_t mlen;
  unsigned char *mpad;
  unsigned char *cpad;

  if (!PyArg_ParseTupleAndKeywords(args, kw, "|s#s#s#:crypto_secretbox", (char **) kwlist, &m, &msize, &n, &nsize, &k, &ksize)){
    return (PyObject *)0;}

  if (nsize != crypto_secretbox_NONCEBYTES) return Py_BuildValue("i", 0);
  if (ksize != crypto_secretbox_KEYBYTES) return Py_BuildValue("i", 0);

  mlen = msize + crypto_secretbox_ZEROBYTES;
  mpad = PyMem_Malloc(mlen);

  if (!mpad)
    return PyErr_NoMemory();

  cpad = PyMem_Malloc(mlen);

  if (!cpad){
    PyMem_Free(mpad);
    return PyErr_NoMemory();}

  for (i = 0;i < crypto_secretbox_ZEROBYTES;++i) mpad[i] = 0;
  for (i = crypto_secretbox_ZEROBYTES;i < mlen;++i) mpad[i] = m[i - crypto_secretbox_ZEROBYTES];

  crypto_secretbox(cpad, mpad, mlen, (const unsigned char *) n, (const unsigned char *) k);

  ret = PyBytes_FromStringAndSize((char *)cpad + crypto_secretbox_BOXZEROBYTES, mlen - crypto_secretbox_BOXZEROBYTES);

  PyMem_Free(mpad);
  PyMem_Free(cpad);
  return ret;}
Exemple #13
0
static ERL_NIF_TERM nacl_secretbox_padded(ErlNifEnv *env, int argc, ERL_NIF_TERM const argv[])
{
  ErlNifBinary key;
  ErlNifBinary nonce;
  ErlNifBinary padded_message;
  ErlNifBinary padded_ciphertext;

  if (!enif_inspect_iolist_as_binary(env, argv[0], &padded_message))
    return enif_make_badarg(env);

  if (!enif_inspect_iolist_as_binary(env, argv[1], &nonce))
    return enif_make_badarg(env);

  if (!enif_inspect_iolist_as_binary(env, argv[2], &key))
    return enif_make_badarg(env);

  if (key.size != crypto_secretbox_KEYBYTES) return enif_make_badarg(env);
  if (nonce.size !=  crypto_secretbox_NONCEBYTES) return enif_make_badarg(env);
  if (padded_message.size < crypto_secretbox_ZEROBYTES) return enif_make_badarg(env);

  if (!enif_alloc_binary(padded_message.size, &padded_ciphertext))
    return nacl_error_tuple(env, "alloc_failed");

  crypto_secretbox(
      padded_ciphertext.data, 
      padded_message.data,
      padded_message.size,
      nonce.data,
      key.data
  );

  return enif_make_sub_binary(env,
			      enif_make_binary(env, &padded_ciphertext),
			      crypto_secretbox_BOXZEROBYTES,
			      padded_message.size - crypto_secretbox_BOXZEROBYTES);
}
int zmq::curve_server_t::produce_welcome (msg_t *msg_)
{
    uint8_t cookie_nonce[crypto_secretbox_NONCEBYTES];
    uint8_t cookie_plaintext[crypto_secretbox_ZEROBYTES + 64];
    uint8_t cookie_ciphertext[crypto_secretbox_BOXZEROBYTES + 80];

    //  Create full nonce for encryption
    //  8-byte prefix plus 16-byte random nonce
    memcpy (cookie_nonce, "COOKIE--", 8);
    randombytes (cookie_nonce + 8, 16);

    //  Generate cookie = Box [C' + s'](t)
    memset (cookie_plaintext, 0, crypto_secretbox_ZEROBYTES);
    memcpy (cookie_plaintext + crypto_secretbox_ZEROBYTES, _cn_client, 32);
    memcpy (cookie_plaintext + crypto_secretbox_ZEROBYTES + 32, _cn_secret, 32);

    //  Generate fresh cookie key
    randombytes (_cookie_key, crypto_secretbox_KEYBYTES);

    //  Encrypt using symmetric cookie key
    int rc =
      crypto_secretbox (cookie_ciphertext, cookie_plaintext,
                        sizeof cookie_plaintext, cookie_nonce, _cookie_key);
    zmq_assert (rc == 0);

    uint8_t welcome_nonce[crypto_box_NONCEBYTES];
    uint8_t welcome_plaintext[crypto_box_ZEROBYTES + 128];
    uint8_t welcome_ciphertext[crypto_box_BOXZEROBYTES + 144];

    //  Create full nonce for encryption
    //  8-byte prefix plus 16-byte random nonce
    memcpy (welcome_nonce, "WELCOME-", 8);
    randombytes (welcome_nonce + 8, crypto_box_NONCEBYTES - 8);

    //  Create 144-byte Box [S' + cookie](S->C')
    memset (welcome_plaintext, 0, crypto_box_ZEROBYTES);
    memcpy (welcome_plaintext + crypto_box_ZEROBYTES, _cn_public, 32);
    memcpy (welcome_plaintext + crypto_box_ZEROBYTES + 32, cookie_nonce + 8,
            16);
    memcpy (welcome_plaintext + crypto_box_ZEROBYTES + 48,
            cookie_ciphertext + crypto_secretbox_BOXZEROBYTES, 80);

    rc = crypto_box (welcome_ciphertext, welcome_plaintext,
                     sizeof welcome_plaintext, welcome_nonce, _cn_client,
                     _secret_key);

    //  TODO I think we should change this back to zmq_assert (rc == 0);
    //  as it was before https://github.com/zeromq/libzmq/pull/1832
    //  The reason given there was that secret_key might be 0ed.
    //  But if it were, we would never get this far, since we could
    //  not have opened the client's hello box with a 0ed key.

    if (rc == -1)
        return -1;

    rc = msg_->init_size (168);
    errno_assert (rc == 0);

    uint8_t *const welcome = static_cast<uint8_t *> (msg_->data ());
    memcpy (welcome, "\x07WELCOME", 8);
    memcpy (welcome + 8, welcome_nonce + 8, 16);
    memcpy (welcome + 24, welcome_ciphertext + crypto_box_BOXZEROBYTES, 144);

    return 0;
}
Exemple #15
0
int main(){


	int s,b,on=1,i;
	
	struct sockaddr_in channel, server;
	unsigned char buf[BUF_SIZE];
     	unsigned char k[crypto_secretbox_KEYBYTES];
     	unsigned char n[crypto_secretbox_NONCEBYTES];
     	unsigned char m[BUF_SIZE]; unsigned long long mlen = BUF_SIZE;
     	unsigned char c[BUF_SIZE];




/* Address structure */

	memset(&channel,0,sizeof(channel));
	channel.sin_family = AF_INET;
	channel.sin_addr.s_addr = htonl(INADDR_ANY);
	channel.sin_port = htons(CLIENT_PORT);

/* Build socket and Bind */

	s = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); /* Create socket */
	if(s<0)
		fatal("Failed to create socket!");

	setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(char*)&on,sizeof(on));	//Osäker på denna

	b = bind(s,(struct sockaddr *)&channel,sizeof(channel));
	if(b<0){
		fatal("Bind failed ");
	}
	
	//Setting up server address
	
	memset(&server,0,sizeof(server));
	server.sin_family = AF_INET;
	server.sin_addr.s_addr = htonl(INADDR_LOOPBACK); 	//INADDR_LOOPBACK är denna datorns ip i.e 127.0.0.1 //inet_addr(serverIP); <- får användas över nätverk där serverIP ges som klassisk xxx.xxx.xxx.xxx
	server.sin_port = htons(SERVER_PORT);			//Serverns portnummer
	

	/*  Time to start sending  */

	if(connect(s,(struct sockaddr *)&server,sizeof(server))){
		fatal("Could not connect to server");
	}
		
	//usleep(1000);		//Ska tydligen ge server tid fast det funkar utan detta, iallafall när localhost-localhost




	// Här börjar diffie-hellman *************************************************************************


	if(!dh(k,crypto_secretbox_KEYBYTES,n,crypto_secretbox_NONCEBYTES,s)){
		fatal("Diffie-hellman fail!");
	}	

	// S**t på diffie-hellman *********************************************************

	// Här Börjar symetrisk krytering *************************************************
	
	while(1){						//Infinite message chain loop

		for(i=0;i<BUF_SIZE;i++){			//Reset message
			m[i] = 0;
		}
		i = crypto_secretbox_ZEROBYTES;			//Begin message at byte 32
		printf("\nWrite your message(q/Q to quit):\n");
		fgets((char *)&m[i],200,stdin);			// Get message from user max 200 charachters (should be enough)

		if((m[i] =='q' || m[i] == 'Q') && strlen((char *)&m[i]) == 2){
			break;
		}

		if(VISIBLE){
			printf("\n\n******  Symmetric encryption/decryption echo begin  ******\n\n");
			printf("\nClient plaintext:\n%s\n",&m[i]);
		}
	
		if(crypto_secretbox(c,m,mlen,n,k)!=0){
			fatal("Cryptobox fail!");
		}
		
		inc_nonce(n);

		if(VISIBLE){
			printf("\nClient ciphertext:\n%s\n",&c[crypto_secretbox_ZEROBYTES]); //Kolla om detta borde stämma
		}

		if(write(s,c,BUF_SIZE)==-1){		// Skriver meddelandet till server. _!check!_ check funkar ej  pröva annat (send)!
			fatal("Server not responding");
		}

		for(i=0;i<BUF_SIZE;i++){
			buf[i] = 0;
		}

		read(s,c,BUF_SIZE);				// Läser in svar _!check!_

		if(VISIBLE){
			printf("\nServer ciphertext:\n%s\n",&c[crypto_secretbox_ZEROBYTES]);
		}

		if(crypto_secretbox_open(buf,c,BUF_SIZE,n,k)==-1){
			fatal("Decryption fail!");
		}
		
		inc_nonce(n);

		if(VISIBLE){
			printf("\nServer plaintext:\n%s\n",&buf[crypto_secretbox_ZEROBYTES]);
			printf("\n\n******  Symmetric encrytion/decryption echo end  ******\n\n");
		}

		printf("\n\n");
		printf("Server says: %s\n", &buf[32]);
	}

	close(s);
	printf("Exiting program!\n");
	return 0;

}
Exemple #16
0
bool unit_test_crypto_secretbox(){
  // Global length
  uint64_t len = HACL_UNIT_TESTS_SIZE * sizeof(uint8_t);
  // Scratch buffers
  uint8_t hacl_cipher[HACL_UNIT_TESTS_SIZE + 32], expected_cipher[HACL_UNIT_TESTS_SIZE + 32];
  // Shared key
  uint8_t key[32];
  // Random plaintext
  uint8_t *plaintext = malloc((HACL_UNIT_TESTS_SIZE + crypto_secretbox_ZEROBYTES) * sizeof (uint8_t));
  READ_RANDOM_BYTES(len, plaintext + crypto_secretbox_ZEROBYTES);
  for (int i = 0; i < crypto_secretbox_ZEROBYTES; i++) plaintext[i] = 0;
  // Random plaintext
  uint8_t nonce[24];
  READ_RANDOM_BYTES(24, nonce);
  // Test 1
  int a;
  bool pass = true;
  for (int i = 0; i < 256; i++){
    tweet_crypto_secretbox(expected_cipher, plaintext, crypto_secretbox_ZEROBYTES + i, nonce, key);
    crypto_secretbox(hacl_cipher, plaintext, crypto_secretbox_ZEROBYTES + i, nonce, key);
    a = memcmp(hacl_cipher, expected_cipher, (crypto_secretbox_ZEROBYTES + i) * sizeof (uint8_t));
    if (a != 0){
      pass = false;
      break;
    }
    /* a = crypto_secretbox_open_detached(hacl_cipher/\* +32 *\/, expected_cipher/\* +32 *\/, expected_cipher + 16, i, nonce, key); */
    a = crypto_secretbox_open(hacl_cipher, expected_cipher, crypto_secretbox_ZEROBYTES + i, nonce, key);
    if (a != 0) {
      pass = false;
      printf("SECRETBOX OPEN ******* failed to verify on input of size %d\n", i);
      break;
    }
    a = memcmp(hacl_cipher, plaintext, (crypto_secretbox_ZEROBYTES + i) * sizeof (uint8_t));
    if (a != 0) {
      pass = false;
      printf("SECRETBOX OPEN failed on input of size %d\n", i);
      break;
    }
  }
  if (!pass) return pass;

  // Test 2
  tweet_crypto_secretbox(expected_cipher, plaintext, crypto_secretbox_ZEROBYTES + HACL_UNIT_TESTS_SIZE, nonce, key);
  crypto_secretbox(hacl_cipher, plaintext, crypto_secretbox_ZEROBYTES + HACL_UNIT_TESTS_SIZE, nonce, key);
  a = memcmp(hacl_cipher, expected_cipher, (crypto_secretbox_ZEROBYTES + HACL_UNIT_TESTS_SIZE) * sizeof (uint8_t));
  if (a != 0){
    pass = false;
    printf("SECRETBOX failed on input of size %d\n.", HACL_UNIT_TESTS_SIZE);
  }
  a = crypto_secretbox_open(hacl_cipher, expected_cipher, HACL_UNIT_TESTS_SIZE + crypto_secretbox_ZEROBYTES, nonce, key);
  if (a != 0) {
    pass = false;
    printf("SECRETBOX OPEN failed to verify on input of size %d\n", HACL_UNIT_TESTS_SIZE);
  }
  a = memcmp(hacl_cipher, plaintext, (crypto_secretbox_ZEROBYTES + HACL_UNIT_TESTS_SIZE) * sizeof (uint8_t));
  if (a != 0) {
    pass = false;
    printf("SECRETBOX OPEN failed on input of size %d\n", HACL_UNIT_TESTS_SIZE);
  }

  free(plaintext);

  return pass;
}
Exemple #17
0
const char *checksum_compute(void)
{
  long long i;
  long long j;

  for (j = 0;j < crypto_secretbox_ZEROBYTES;++j) m[j] = 0;

  for (i = 0;i < CHECKSUM_BYTES;++i) {
    long long mlen = i + crypto_secretbox_ZEROBYTES;
    long long tlen = i + crypto_secretbox_ZEROBYTES;
    long long clen = i + crypto_secretbox_ZEROBYTES;

    for (j = -16;j < 0;++j) k[j] = rand();
    for (j = -16;j < 0;++j) n[j] = rand();
    for (j = -16;j < 0;++j) m[j] = rand();
    for (j = klen;j < klen + 16;++j) k[j] = rand();
    for (j = nlen;j < nlen + 16;++j) n[j] = rand();
    for (j = mlen;j < mlen + 16;++j) m[j] = rand();
    for (j = -16;j < klen + 16;++j) k2[j] = k[j];
    for (j = -16;j < nlen + 16;++j) n2[j] = n[j];
    for (j = -16;j < mlen + 16;++j) m2[j] = m[j];
    for (j = -16;j < clen + 16;++j) c2[j] = c[j] = rand();

    if (crypto_secretbox(c,m,mlen,n,k) != 0) return "crypto_secretbox returns nonzero";

    for (j = -16;j < mlen + 16;++j) if (m2[j] != m[j]) return "crypto_secretbox overwrites m";
    for (j = -16;j < nlen + 16;++j) if (n2[j] != n[j]) return "crypto_secretbox overwrites n";
    for (j = -16;j < klen + 16;++j) if (k2[j] != k[j]) return "crypto_secretbox overwrites k";
    for (j = -16;j < 0;++j) if (c2[j] != c[j]) return "crypto_secretbox writes before output";
    for (j = clen;j < clen + 16;++j) if (c2[j] != c[j]) return "crypto_secretbox writes after output";
    for (j = 0;j < crypto_secretbox_BOXZEROBYTES;++j)
      if (c[j] != 0) return "crypto_secretbox does not clear extra bytes";

    for (j = -16;j < 0;++j) c[j] = rand();
    for (j = clen;j < clen + 16;++j) c[j] = rand();
    for (j = -16;j < clen + 16;++j) c2[j] = c[j];
    for (j = -16;j < tlen + 16;++j) t2[j] = t[j] = rand();

    if (crypto_secretbox_open(t,c,clen,n,k) != 0) return "crypto_secretbox_open returns nonzero";

    for (j = -16;j < clen + 16;++j) if (c2[j] != c[j]) return "crypto_secretbox_open overwrites c";
    for (j = -16;j < nlen + 16;++j) if (n2[j] != n[j]) return "crypto_secretbox_open overwrites n";
    for (j = -16;j < klen + 16;++j) if (k2[j] != k[j]) return "crypto_secretbox_open overwrites k";
    for (j = -16;j < 0;++j) if (t2[j] != t[j]) return "crypto_secretbox_open writes before output";
    for (j = tlen;j < tlen + 16;++j) if (t2[j] != t[j]) return "crypto_secretbox_open writes after output";
    for (j = 0;j < crypto_secretbox_ZEROBYTES;++j)
      if (t[j] != 0) return "crypto_secretbox_open does not clear extra bytes";

    for (j = 0;j < i;++j) if (t[j] != m[j]) return "plaintext does not match";

    for (j = 0;j < i;++j)
      k[j % klen] ^= c[j + crypto_secretbox_BOXZEROBYTES];
    crypto_secretbox(c,m,mlen,n,k);
    for (j = 0;j < i;++j)
      n[j % nlen] ^= c[j + crypto_secretbox_BOXZEROBYTES];
    crypto_secretbox(c,m,mlen,n,k);
    if (i == 0) m[crypto_secretbox_ZEROBYTES + 0] = 0;
    m[crypto_secretbox_ZEROBYTES + i] = m[crypto_secretbox_ZEROBYTES + 0];
    for (j = 0;j < i;++j)
      m[j + crypto_secretbox_ZEROBYTES] ^= c[j + crypto_secretbox_BOXZEROBYTES];
  }

  sodium_bin2hex(checksum, sizeof checksum, k, klen);

  return 0;
}
Exemple #18
0
void doit(void)
{
  crypto_secretbox(c,m,TUNE_BYTES + crypto_secretbox_ZEROBYTES,n,k);
  crypto_secretbox_open(t,c,TUNE_BYTES + crypto_secretbox_ZEROBYTES,n,k);
}
Exemple #19
0
static int _handle_hello (struct curvecpr_server *server, void *priv, const struct curvecpr_packet_hello *p)
{
    const struct curvecpr_server_cf *cf = &server->cf;
    struct curvecpr_session s; /* Used only as a temporary store to make what we're doing
                                  more clear. */

    unsigned char nonce[24];
    unsigned char data[96] = { 0 };

    /* Dummy initialization. */
    curvecpr_session_new(&s);
    curvecpr_session_set_priv(&s, priv);

    /* Verify initial connection parameters. */
    curvecpr_bytes_copy(s.their_session_pk, p->client_session_pk, 32);
    crypto_box_beforenm(s.my_global_their_session_key, s.their_session_pk, cf->my_global_sk);

    curvecpr_bytes_copy(nonce, "CurveCP-client-H", 16);
    curvecpr_bytes_copy(nonce + 16, p->nonce, 8);

    curvecpr_bytes_copy(data + 16, p->box, 80);
    if (crypto_box_open_afternm(data, data, 96, nonce, s.my_global_their_session_key))
        return -EINVAL;

    /* Set up session keys. */
    crypto_box_keypair(s.my_session_pk, s.my_session_sk);

    /* Prepare to send a cookie packet. */
    {
        struct curvecpr_packet_cookie po;
        struct curvecpr_packet_cookie_box po_box;

        curvecpr_bytes_zero(po_box._, 32);
        curvecpr_bytes_copy(po_box.server_session_pk, s.my_session_pk, 32);

        /* Generate the cookie. */
        curvecpr_bytes_zero(po_box.cookie, 32);
        curvecpr_bytes_copy(po_box.cookie + 32, s.their_session_pk, 32);
        curvecpr_bytes_copy(po_box.cookie + 64, s.my_session_sk, 32);

        /* Encrypt the cookie with our global nonce and temporary key. */
        curvecpr_bytes_copy(nonce, "minute-k", 8);
        if (cf->ops.next_nonce(server, nonce + 8, 16))
            return -EINVAL;

        crypto_secretbox(po_box.cookie, po_box.cookie, 96, nonce, server->my_temporal_key);
        curvecpr_bytes_copy(po_box.cookie, nonce + 8, 16);

        /* Now encrypt the whole box. */
        curvecpr_bytes_copy(nonce, "CurveCPK", 8);

        crypto_box_afternm((unsigned char *)&po_box, (const unsigned char *)&po_box, sizeof(struct curvecpr_packet_cookie_box), nonce, s.my_global_their_session_key);

        /* Build the rest of the packet. */
        curvecpr_bytes_copy(po.id, "RL3aNMXK", 8);
        curvecpr_bytes_copy(po.client_extension, p->client_extension, 16);
        curvecpr_bytes_copy(po.server_extension, cf->my_extension, 16);
        curvecpr_bytes_copy(po.nonce, nonce + 8, 16);
        curvecpr_bytes_copy(po.box, (const unsigned char *)&po_box + 16, 144);

        if (cf->ops.send(server, &s, (const unsigned char *)&po, sizeof(struct curvecpr_packet_cookie)))
            return -EINVAL;
    }

    return 0;
}