示例#1
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;
}
示例#2
0
文件: dht_test.c 项目: Ansa89/toxcore
void test_addto_lists_good(DHT            *dht,
                           Client_data    *list,
                           uint32_t        length,
                           IP_Port        *ip_port,
                           const uint8_t  *comp_client_id)
{
    uint8_t public_key[crypto_box_PUBLICKEYBYTES];
    uint8_t ipv6 = ip_port->ip.family == AF_INET6 ? 1 : 0;

    mark_all_good(list, length, ipv6);

    // check "good" client id replacement
    do {
        randombytes(public_key, sizeof(public_key));
    } while (is_furthest(comp_client_id, list, length, public_key));

    ip_port->port += 1;
    addto_lists(dht, *ip_port, public_key);
    ck_assert_msg(client_in_list(list, length, public_key) >= 0, "Good client id is not in the list");

    // check "good" client id skip
    do {
        randombytes(public_key, sizeof(public_key));
    } while (!is_furthest(comp_client_id, list, length, public_key));

    ip_port->port += 1;
    addto_lists(dht, *ip_port, public_key);
    ck_assert_msg(client_in_list(list, length, public_key) == -1, "Good client id is in the list");
}
示例#3
0
文件: measure.c 项目: 0x20c24/cjdns
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);
    }
  }
}
示例#4
0
/* key pair generation */
int crypto_dh_gls254_opt_keypair(unsigned char *pk, unsigned char *sk) {
    /* var */
    __m128i px0, px1, pl0, pl1;
    __m128i qx0, qx1, ql0, ql1, qz0, qz1;

    /* ini */
    randombytes(&sk[0], 16);
    randombytes(&sk[16], 16);
    sk[15] = sk[15] & 0x7F;
    sk[31] = sk[31] & 0x7F;

    /* generator */
    px0 = _mm_set_epi64x(0x9D1932CB5FA5B9BF, 0x5BE5F4EB93D8712A);
    px1 = _mm_set_epi64x(0x25F2F29FCBDEC78E, 0x47E70D2DCA8C7210);
    pl0 = _mm_set_epi64x(0x25BE90C01E0E9B06, 0x97FBBBBFEB3A8AB4);
    pl1 = _mm_set_epi64x(0xB3834B048C217C1, 0x1A1764D658204447);

    /* man */
    smu_5nf_dna_ltr(&qx0, &qx1, &ql0, &ql1, &qz0, &qz1, 
                    px0, px1, pl0, pl1, 
                    (uint64_t *) &sk[0], (uint64_t *) &sk[16]);

    /* end */
    _mm_store_si128((__m128i *) &pk[0], qx0);
    _mm_store_si128((__m128i *) &pk[16], qx1);
    _mm_store_si128((__m128i *) &pk[32], ql0);
    _mm_store_si128((__m128i *) &pk[48], ql1);

    return 0; 
}
示例#5
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;
}
示例#6
0
文件: measure.c 项目: 0x20c24/cjdns
void measure(void)
{
  int i;
  int loop;
  int mlen;

  for (loop = 0;loop < LOOPS;++loop) {
    for (mlen = 0;mlen <= MAXTEST_BYTES;mlen += 1 + mlen / MGAP) {
      randombytes(k,crypto_auth_KEYBYTES);
      randombytes(m,mlen);
      randombytes(h,crypto_auth_BYTES);
      for (i = 0;i <= TIMINGS;++i) {
        cycles[i] = cpucycles();
	crypto_auth(h,m,mlen,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_auth_verify(h,m,mlen,k);
      }
      for (i = 0;i < TIMINGS;++i) cycles[i] = cycles[i + 1] - cycles[i];
      printentry(mlen,"verify_cycles",cycles,TIMINGS);
    }
  }
}
示例#7
0
int main(void)
{
  size_t mlen;
  size_t i;
  int caught;

  for (mlen = 0;mlen < 1000 && mlen + crypto_box_ZEROBYTES < sizeof m;++mlen) {
    crypto_box_keypair(alicepk,alicesk);
    crypto_box_keypair(bobpk,bobsk);
    randombytes(n,crypto_box_NONCEBYTES);
    randombytes(m + crypto_box_ZEROBYTES,mlen);
    crypto_box(c,m,mlen + crypto_box_ZEROBYTES,n,bobpk,alicesk);
    caught = 0;
    while (caught < 10) {
      c[rand() % (mlen + crypto_box_ZEROBYTES)] = rand();
      if (crypto_box_open(m2,c,mlen + crypto_box_ZEROBYTES,n,alicepk,bobsk) == 0) {
        for (i = 0;i < mlen + crypto_box_ZEROBYTES;++i)
          if (m2[i] != m[i]) {
            printf("forgery\n");
            return 100;
          }
      } else {
        ++caught;
      }
    }
  }
  return 0;
}
示例#8
0
文件: dht_test.c 项目: mowgli/toxcore
void test_addto_lists_good(DHT            *dht,
                           Client_data    *list,
                           uint32_t        length,
                           IP_Port        *ip_port,
                           const uint8_t  *comp_client_id)
{
    uint8_t client_id[CLIENT_ID_SIZE];
    uint8_t ipv6 = ip_port->ip.family == AF_INET6 ? 1 : 0;

    mark_all_good(list, length, ipv6);

    // check "good" client id replacement
    do {
        randombytes(client_id, sizeof(client_id));
    } while (is_furthest(comp_client_id, list, length, client_id));

    ip_port->port += 1;
    addto_lists(dht, *ip_port, client_id);
    ck_assert_msg(client_in_list(list, length, client_id) >= 0, "Good client id is not in the list");

    // check "good" client id skip
    do {
        randombytes(client_id, sizeof(client_id));
    } while (!is_furthest(comp_client_id, list, length, client_id));

    ip_port->port += 1;
    addto_lists(dht, *ip_port, client_id);
    ck_assert_msg(client_in_list(list, length, client_id) == -1, "Good client id is in the list");
}
示例#9
0
int main(int argc, char **argv) {

    unsigned char *x;
    unsigned long long xlen;

    if (argv[0])
        if (argv[1]) {
            if (str_equal(argv[1], "-h"))
                die_usage(0);
        }

    /* get password  */
    x = (unsigned char *)env_get("PASSWORD");
    if (!x) { errno = 0; die_usage("$PASSWORD not set"); }
    xlen = str_len((char *)x);

    /* create salt */
    randombytes(s, sizeof s);

    /* derive key  */
    if (sha512hmacpbkdf2(h, sizeof h, x, xlen, s, sizeof s, ROUNDS) == -1) die_fatal("unable to derive keys", 0);
    byte_zero(x, xlen);

    /* create nonce */
    randombytes(n, sizeof n);
    uint64_pack(n, nanoseconds());
    sha512(nk, (unsigned char *)MAGIC, MAGICBYTES);
    crypto_block_aes256vulnerable(n, n, nk);

    /* initialize */
    crypto_init(&ctx, n, h, MAGIC);
    randombytes(h, sizeof h);
    sha512_init(&shactx);

    /* write header */
    if (writeall(1, MAGIC, MAGICBYTES) == -1) die_fatal("unable to write output", 0);
    if (writeall(1, s, sizeof s) == -1) die_fatal("unable to write output", 0);
    randombytes(s, sizeof s);
    if (writeall(1, n, sizeof n) == -1) die_fatal("unable to write output", 0);

    for (;;) {
        inlen = readblock(in, BLOCK);
        if (inlen != BLOCK) break;
        if (sha512_block(&shactx, in, inlen) != 0) die_fatal("unable to compute hash", 0);
        if (crypto_block(&ctx, in, inlen) != 0) die_fatal("unable to encrypt stream", 0);
        if (writeall(1, in, inlen) == -1) die_fatal("unable to write output", 0);
    }
    if (sha512_last(&shactx, h, in, inlen) != 0) die_fatal("unable to compute hash", 0);
    byte_copy(in + inlen, CHECKSUMBYTES, h);
    inlen += CHECKSUMBYTES;
    if (crypto_last(&ctx, in, inlen) != 0) die_fatal("unable to encrypt stream", 0);
    if (writeall(1, in, inlen) == -1) die_fatal("unable to write output", 0);

    if (fsyncfd(1) == -1) die_fatal("unable to write output", 0);
    cleanup();
    _exit(0);
}
示例#10
0
void curvecpr_server_new (struct curvecpr_server *server, const struct curvecpr_server_cf *cf)
{
    curvecpr_bytes_zero(server, sizeof(struct curvecpr_server));

    /* Copy in the configuration. */
    if (cf)
        curvecpr_bytes_copy(&server->cf, cf, sizeof(struct curvecpr_server_cf));

    /* Generate brand new temporal keys. */
    randombytes(server->my_temporal_key, sizeof(server->my_temporal_key));
    randombytes(server->my_last_temporal_key, sizeof(server->my_last_temporal_key));
}
void test_fe25519_mul()
{
  fe25519 fa, fb, fr;
  int i,n;

  for(n=0;n<NTESTS;n++)
  {
    //multiply random values
    randombytes(fa.v,32);
    randombytes(fb.v,32);
    fe25519_mul(&fr, &fa, &fb);

    print("(");
    fe25519_print(&fa);
    print("*");
    fe25519_print(&fb);
    print("-");
    fe25519_print(&fr);
    print(") % (2^255-19)\r\n");
  }

  //multiply maximal values
  for(i=0;i<32;i++)
    fa.v[i] = fb.v[i] = 255;
  fe25519_mul(&fr, &fa, &fb);

  print("(");
  fe25519_print(&fa);
  print("*");
  fe25519_print(&fb);
  print("-");
  fe25519_print(&fr);
  print(") % (2^255-19)\r\n");

  //multiply bad case for final carry
  for(i=0;i<32;i++)
    fa.v[i] = fb.v[i] = 255;
  fb.v[0] = 253;

  fe25519_mul(&fr, &fa, &fb);

  print("(");
  fe25519_print(&fa);
  print("*");
  fe25519_print(&fb);
  print("-");
  fe25519_print(&fr);
  print(") % (2^255-19)\r\n");


}
示例#12
0
int
dnsperf_makekey(const unsigned char *hexkey)
{
    encryption = 0;

    if (fromhex(hexkey, &key.server_publickey[0])) {
        //client secret key
        randombytes(&key.server_secretkey[0], 32);
        int rc = crypto_scalarmult_curve25519_base(&key.client_publickey[0], &key.server_secretkey[0]);
        if (rc != 0) {
            fprintf(stderr, "(%s:%s:%i) (crypto_scalarmult_curve25519_base) rc: %i\n", __FILE__, __func__, __LINE__, rc);
            return 0;
        } else {
            key.hash = fDns_hash_fnv64(&key.server_publickey[0], crypto_box_curve25519xsalsa20poly1305_PUBLICKEYBYTES);
/*
            printf("Using hash: '%lu' for public key for host: ", key.hash);
            for (rc = 0; rc < crypto_box_curve25519xsalsa20poly1305_PUBLICKEYBYTES; rc++) {
                printf("%02x", key.server_publickey[rc]);
            }
            printf("\n");
*/
            rc = crypto_box_curve25519xsalsa20poly1305_beforenm((unsigned char *)&key.shared_new_key[0], (const unsigned char *)&key.server_publickey[0], (const unsigned char *)&key.server_secretkey[0]);
            if (rc != 0) {
                fprintf(stderr, "(%s:%s:%i) (crypto_box_curve25519xsalsa20poly1305_beforenm) rc: %i\n", __FILE__, __func__, __LINE__, rc);
                return 0;
            }
            key.shared_key = &key.shared_new_key[0];
/*
            printf("Using shared key: ");
            for (rc = 0; rc < crypto_box_curve25519xsalsa20poly1305_PUBLICKEYBYTES; rc++) {
                printf("%02x", key.shared_key[rc]);
            }
            printf("\n");
*/
        }

        bzero(&key.nonce[12], 12);
        randombytes(&key.nonce[0], 12);
/*
        printf("Using nonce: ");
        for (rc = 0; rc < crypto_box_curve25519xsalsa20poly1305_NONCEBYTES; rc++) {
            printf("%02x", key.nonce[rc]);
        }
        printf("\n");
*/
        encryption = 1;
    }

    return 0;
}
示例#13
0
文件: reop.c 项目: jwilkins/reop
/*
 * generate two key pairs, one for signing and one for encryption.
 */
static void
generate(const char *pubkeyfile, const char *seckeyfile, int rounds,
    const char *ident)
{
	struct pubkey pubkey;
	struct seckey seckey;
	uint8_t symkey[SYMKEYBYTES];
	uint8_t fingerprint[FPLEN];
	kdf_allowstdin allowstdin = { 1 };
	kdf_confirm confirm = { 1 };

	if (!seckeyfile)
		seckeyfile = gethomefile("seckey");

	memset(&pubkey, 0, sizeof(pubkey));
	memset(&seckey, 0, sizeof(seckey));

	crypto_sign_ed25519_keypair(pubkey.sigkey, seckey.sigkey);
	crypto_box_keypair(pubkey.enckey, seckey.enckey);
	randombytes(fingerprint, sizeof(fingerprint));

	memcpy(seckey.fingerprint, fingerprint, FPLEN);
	memcpy(seckey.sigalg, SIGALG, 2);
	memcpy(seckey.encalg, ENCALG, 2);
	memcpy(seckey.symalg, SYMALG, 2);
	memcpy(seckey.kdfalg, KDFALG, 2);
	seckey.kdfrounds = htonl(rounds);
	randombytes(seckey.salt, sizeof(seckey.salt));

	kdf(seckey.salt, sizeof(seckey.salt), rounds, allowstdin, confirm,
	    symkey, sizeof(symkey));
	symencryptmsg(seckey.sigkey, sizeof(seckey.sigkey) + sizeof(seckey.enckey),
	    seckey.box, symkey);
	explicit_bzero(symkey, sizeof(symkey));

	writekeyfile(seckeyfile, "SECRET KEY", &seckey, sizeof(seckey),
	    ident, O_EXCL, 0600);
	explicit_bzero(&seckey, sizeof(seckey));

	memcpy(pubkey.fingerprint, fingerprint, FPLEN);
	memcpy(pubkey.sigalg, SIGALG, 2);
	memcpy(pubkey.encalg, ENCALG, 2);

	if (!pubkeyfile)
		pubkeyfile = gethomefile("pubkey");
	writekeyfile(pubkeyfile, "PUBLIC KEY", &pubkey, sizeof(pubkey),
	    ident, O_EXCL, 0666);
}
示例#14
0
void
http(Ticketreq *tr)
{
	Ticket t;
	char tbuf[TICKETLEN+1];
	char key[DESKEYLEN];
	char *p;
	Biobuf *b;
	int n;

	n = strlen(tr->uid);
	b = Bopen("/sys/lib/httppasswords", OREAD);
	if(b == nil){
		replyerror("no password file", raddr);
		return;
	}

	/* find key */
	for(;;){
		p = Brdline(b, '\n');
		if(p == nil)
			break;
		p[Blinelen(b)-1] = 0;
		if(strncmp(p, tr->uid, n) == 0)
		if(p[n] == ' ' || p[n] == '\t'){
			p += n;
			break;
		}
	}
	Bterm(b);
	if(p == nil) {
		randombytes((uchar*)key, DESKEYLEN);
	} else {
		while(*p == ' ' || *p == '\t')
			p++;
		passtokey(key, p);
	}

	/* send back a ticket encrypted with the key */
	randombytes((uchar*)t.chal, CHALLEN);
	mkkey(t.key);
	tbuf[0] = AuthOK;
	t.num = AuthHr;
	safecpy(t.cuid, tr->uid, sizeof(t.cuid));
	safecpy(t.suid, tr->uid, sizeof(t.suid));
	convT2M(&t, tbuf+1, key);
	write(1, tbuf, sizeof(tbuf));
}
示例#15
0
文件: ctx.cpp 项目: 5igm4/libzmq
zmq::ctx_t::ctx_t () :
    tag (ZMQ_CTX_TAG_VALUE_GOOD),
    starting (true),
    terminating (false),
    reaper (NULL),
    slot_count (0),
    slots (NULL),
    max_sockets (clipped_maxsocket (ZMQ_MAX_SOCKETS_DFLT)),
    max_msgsz (INT_MAX),
    io_thread_count (ZMQ_IO_THREADS_DFLT),
    blocky (true),
    ipv6 (false),
    thread_priority (ZMQ_THREAD_PRIORITY_DFLT),
    thread_sched_policy (ZMQ_THREAD_SCHED_POLICY_DFLT)
{
#ifdef HAVE_FORK
    pid = getpid();
#endif
#ifdef ZMQ_HAVE_VMCI
    vmci_fd = -1;
    vmci_family = -1;
#endif

    crypto_sync.lock ();
#if defined (ZMQ_USE_TWEETNACL)
    // allow opening of /dev/urandom
    unsigned char tmpbytes[4];
    randombytes(tmpbytes, 4);
#elif defined (ZMQ_USE_LIBSODIUM)
    int rc = sodium_init ();
    zmq_assert (rc != -1);
#endif
    crypto_sync.unlock ();
}
示例#16
0
void newhope_sharedb(unsigned char *sharedkey, unsigned char *send, const unsigned char *received)
{
  poly sp, ep, v, a, pka, c, epp, bp;
  unsigned char seed[NEWHOPE_SEEDBYTES];
  unsigned char noiseseed[32];
  
  randombytes(noiseseed, 32);

  decode_a(&pka, seed, received);
  gen_a(&a, seed);

  poly_getnoise(&sp,noiseseed,0);
  poly_ntt(&sp);
  poly_getnoise(&ep,noiseseed,1);
  poly_ntt(&ep);

  poly_pointwise(&bp, &a, &sp);
  poly_add(&bp, &bp, &ep);
  
  poly_pointwise(&v, &pka, &sp);
  poly_bitrev(&v);
  poly_invntt(&v);

  poly_getnoise(&epp,noiseseed,2);
  poly_add(&v, &v, &epp);

  helprec(&c, &v, noiseseed, 3);

  encode_b(send, &bp, &c);
  
  rec(sharedkey, &v, &c);

  sha3256(sharedkey, sharedkey, 32);
}
示例#17
0
uint64_t createTid() {
  uint64_t tid;

  randombytes((unsigned char*)&tid, sizeof tid);

  return tid & ~TID_FLAGS;
}
示例#18
0
zmq::curve_client_t::curve_client_t (const options_t &options_) :
    mechanism_t (options_),
    state (send_hello),
    cn_nonce(1),
    cn_peer_nonce(1),
    sync()
{
    int rc;
    memcpy (public_key, options_.curve_public_key, crypto_box_PUBLICKEYBYTES);
    memcpy (secret_key, options_.curve_secret_key, crypto_box_SECRETKEYBYTES);
    memcpy (server_key, options_.curve_server_key, crypto_box_PUBLICKEYBYTES);
    scoped_lock_t lock (sync);
#if defined(HAVE_TWEETNACL)
    // allow opening of /dev/urandom
    unsigned char tmpbytes[4];
    randombytes(tmpbytes, 4);
#else
    rc = sodium_init ();
    zmq_assert (rc != -1);
#endif

    //  Generate short-term key pair
    rc = crypto_box_keypair (cn_public, cn_secret);
    zmq_assert (rc == 0);
}
示例#19
0
/* Generates a secret symmetric key from the given passphrase. out_key must be at least
 * TOX_PASS_KEY_LENGTH bytes long.
 * Be sure to not compromise the key! Only keep it in memory, do not write to disk.
 * The password is zeroed after key derivation.
 * The key should only be used with the other functions in this module, as it
 * includes a salt.
 * Note that this function is not deterministic; to derive the same key from a
 * password, you also must know the random salt that was used. See below.
 *
 * returns true on success
 */
bool tox_derive_key_from_pass(const uint8_t *passphrase, size_t pplength, TOX_PASS_KEY *out_key,
                              TOX_ERR_KEY_DERIVATION *error)
{
    uint8_t salt[crypto_pwhash_scryptsalsa208sha256_SALTBYTES];
    randombytes(salt, sizeof salt);
    return tox_derive_key_with_salt(passphrase, pplength, salt, out_key, error);
}
示例#20
0
文件: reop.c 项目: jwilkins/reop
/*
 * encrypt a file using symmetric cryptography (a password)
 */
static void
symencrypt(const char *msgfile, const char *encfile, int rounds)
{
	struct symmsg symmsg;
	uint8_t symkey[SYMKEYBYTES];
	uint8_t *msg;
	unsigned long long msglen;
	kdf_allowstdin allowstdin = { strcmp(msgfile, "-") != 0 };
	kdf_confirm confirm = { 1 };

	msg = readall(msgfile, &msglen);

	memcpy(symmsg.kdfalg, KDFALG, 2);
	memcpy(symmsg.symalg, SYMALG, 2);
	symmsg.kdfrounds = htonl(rounds);
	randombytes(symmsg.salt, sizeof(symmsg.salt));
	kdf(symmsg.salt, sizeof(symmsg.salt), rounds,
	    allowstdin, confirm, symkey, sizeof(symkey));

	symencryptmsg(msg, msglen, symmsg.box, symkey);
	explicit_bzero(symkey, sizeof(symkey));

	writeencfile(encfile, &symmsg, sizeof(symmsg), "<symmetric>", msg, msglen);

	xfree(msg, msglen);
}
示例#21
0
lob_t remote_encrypt(remote_t remote, local_t local, lob_t inner)
{
  uint8_t secret[crypto_box_BEFORENMBYTES], nonce[24], shared[24+crypto_box_BEFORENMBYTES], hash[32], csid = 0x3a;
  lob_t outer;
  size_t inner_len;

  outer = lob_new();
  lob_head(outer,&csid,1);
  inner_len = lob_len(inner);
  if(!lob_body(outer,NULL,32+24+inner_len+crypto_secretbox_MACBYTES+16)) return lob_free(outer);

  // copy in the ephemeral public key/nonce
  memcpy(outer->body, remote->ekey, 32);
  randombytes(nonce,24);
  memcpy(outer->body+32, nonce, 24);

  // get the shared secret to create the nonce+key for the open aes
  crypto_box_beforenm(secret, remote->key, remote->esecret);

  // encrypt the inner
  if(crypto_secretbox_easy(outer->body+32+24,
    lob_raw(inner),
    inner_len,
    nonce,
    secret) != 0) return lob_free(outer);

  // generate secret for hmac
  crypto_box_beforenm(secret, remote->key, local->secret);
  memcpy(shared,nonce,24);
  memcpy(shared+24,secret,crypto_box_BEFORENMBYTES);
  e3x_hash(shared,24+crypto_box_BEFORENMBYTES,hash);
  crypto_onetimeauth(outer->body+32+24+inner_len+crypto_secretbox_MACBYTES, outer->body, outer->body_len-16, hash);

  return outer;
}
示例#22
0
zmq::curve_server_t::curve_server_t (session_base_t *session_,
                                     const std::string &peer_address_,
                                     const options_t &options_) :
    mechanism_t (options_),
    session (session_),
    peer_address (peer_address_),
    state (expect_hello),
    expecting_zap_reply (false),
    cn_nonce (1),
    sync()
{
    //  Fetch our secret key from socket options
    memcpy (secret_key, options_.curve_secret_key, crypto_box_SECRETKEYBYTES);
    scoped_lock_t lock (sync);
#if defined(HAVE_TWEETNACL)
    // allow opening of /dev/urandom
    unsigned char tmpbytes[4];
    randombytes(tmpbytes, 4);
#else
    // todo check return code
    sodium_init();
#endif

    //  Generate short-term key pair
    const int rc = crypto_box_keypair (cn_public, cn_secret);
    zmq_assert (rc == 0);
}
示例#23
0
/* Generates a secret symmetric key from the given passphrase. out_key must be at least
 * TOX_PASS_KEY_LENGTH bytes long.
 * Be sure to not compromise the key! Only keep it in memory, do not write to disk.
 * The password is zeroed after key derivation.
 * The key should only be used with the other functions in this module, as it
 * includes a salt.
 * Note that this function is not deterministic; to derive the same key from a
 * password, you also must know the random salt that was used. See below.
 *
 * returns true on success
 */
bool tox_pass_key_derive(Tox_Pass_Key *out_key, const uint8_t *passphrase, size_t pplength,
                         TOX_ERR_KEY_DERIVATION *error)
{
    uint8_t salt[crypto_pwhash_scryptsalsa208sha256_SALTBYTES];
    randombytes(salt, sizeof salt);
    return tox_pass_key_derive_with_salt(out_key, passphrase, pplength, salt, error);
}
示例#24
0
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);
}
示例#25
0
文件: CryptoAuth.c 项目: Ralith/cjdns
/**
 * If we don't know her key, the handshake has to be done backwards.
 * Reverse handshake requests are signaled by sending a non-obfuscated zero nonce.
 */
static uint8_t genReverseHandshake(struct Message* message,
                                   struct Wrapper* wrapper,
                                   union Headers_CryptoAuth* header)
{
    wrapper->nextNonce = 0;
    Message_shift(message, -Headers_CryptoAuth_SIZE);

    // Buffer the packet so it can be sent ASAP
    if (wrapper->bufferedMessage == NULL) {
        Log_debug(wrapper->context->logger, "Buffered a message.\n");
        wrapper->bufferedMessage =
            Message_clone(message, wrapper->externalInterface.allocator);
        assert(wrapper->nextNonce == 0);
    } else {
        Log_debug(wrapper->context->logger,
                  "Expelled a message because a session has not yet been setup.\n");
        Message_copyOver(wrapper->bufferedMessage,
                         message,
                         wrapper->externalInterface.allocator);
        assert(wrapper->nextNonce == 0);
    }
    wrapper->hasBufferedMessage = true;

    Message_shift(message, Headers_CryptoAuth_SIZE);
    header = (union Headers_CryptoAuth*) message->bytes;
    header->nonce = UINT32_MAX;
    message->length = Headers_CryptoAuth_SIZE;

    // sessionState must be 0, auth and 24 byte nonce are garbaged and public key is set
    // now garbage the authenticator and the encrypted key which are not used.
    randombytes((uint8_t*) &header->handshake.authenticator, 48);

    return wrapper->wrappedInterface->sendMessage(message, wrapper->wrappedInterface);
}
示例#26
0
int main(int argc,char **argv)
{
  char *d;

  if (!argv[0]) die_usage();
  if (!argv[1]) die_usage();
  d = argv[1];

  umask(022);
  if (mkdir(d,0755) == -1) die_fatal("unable to create directory",d,0);
  if (chdir(d) == -1) die_fatal("unable to chdir to directory",d,0);
  if (mkdir(".expertsonly",0700) == -1) die_fatal("unable to create directory",d,".expertsonly");

  sodium_init();

  crypto_box_keypair(pk,sk);
  create(d,"publickey",pk,sizeof pk);

  randombytes(noncekey,sizeof noncekey);

  umask(077);
  create(d,".expertsonly/secretkey",sk,sizeof sk);
  create(d,".expertsonly/lock",lock,sizeof lock);
  create(d,".expertsonly/noncekey",noncekey,sizeof noncekey);
  create(d,".expertsonly/noncecounter",noncecounter,sizeof noncecounter);

  return 0;
}
示例#27
0
文件: ecdsa.c 项目: wbl/NISTP
/*Secret keys are 64 bytes. First 32 bytes are an exponent, second 32 are
  hashed with last 32 bytes of h(m) to give k*/
void crypto_sign_keypair_ecdsa256sha512(unsigned char *pk,
                                        unsigned char *sk){
  point p;
  randombytes(sk, 64);
  p256scalarmult_base(&p, sk); //first 32 bytes are used only
  p256pack(pk, &p);
}
示例#28
0
int crypto_box_curve25519xsalsa20poly1305_keypair(
  unsigned char *pk,
  unsigned char *sk
)
{
  randombytes(sk,32);
  return crypto_scalarmult_curve25519_base(pk,sk);
}
示例#29
0
void
chap(Ticketreq *tr)
{
	char *secret, *hkey;
	DigestState *s;
	char sbuf[SECRETLEN], hbuf[DESKEYLEN];
	uchar digest[MD5dlen];
	char chal[CHALLEN];
	OChapreply reply;

	/*
	 *  Create a challenge and send it.
	 */
	randombytes((uchar*)chal, sizeof(chal));
	write(1, chal, sizeof(chal));

	/*
	 *  get chap reply
	 */
	if(readn(0, &reply, sizeof(reply)) < 0)
		exits(0);
	safecpy(tr->uid, reply.uid, sizeof(tr->uid));

	/*
	 * lookup
	 */
	secret = findsecret(KEYDB, tr->uid, sbuf);
	hkey = findkey(KEYDB, tr->hostid, hbuf);
	if(hkey == 0 || secret == 0){
		replyerror("chap-fail bad response %s", raddr);
		logfail(tr->uid);
		exits(0);
	}

	/*
	 *  check for match
	 */
	s = md5(&reply.id, 1, 0, 0);
	md5((uchar*)secret, strlen(secret), 0, s);
	md5((uchar*)chal, sizeof(chal), digest, s);

	if(memcmp(digest, reply.resp, MD5dlen) != 0){
		replyerror("chap-fail bad response %s", raddr);
		logfail(tr->uid);
		exits(0);
	}

	succeed(tr->uid);

	/*
	 *  reply with ticket & authenticator
	 */
	if(tickauthreply(tr, hkey) < 0)
		exits(0);

	if(debug)
		syslog(0, AUTHLOG, "chap-ok %s %s", tr->uid, raddr);
}
示例#30
0
int crypto_dh_curve25519_keypair(
    unsigned char *pk,
    unsigned char *sk
    )
{
  randombytes(sk,crypto_scalarmult_curve25519_SCALARBYTES);
  crypto_scalarmult_curve25519_base(pk,sk);
  return 0;
}