示例#1
0
文件: prf.c 项目: meshlink/meshlink
static bool hmac_sha512(const char *key, size_t keylen, const char *msg, size_t msglen, char *out) {
	char tmp[2 * mdlen];
	sha512_context md;

	if(keylen <= mdlen) {
		memcpy(tmp, key, keylen);
		memset(tmp + keylen, 0, mdlen - keylen);
	} else {
		if(sha512(key, keylen, tmp) != 0)
			return false;
	}

	if(sha512_init(&md) != 0)
		return false;

	// ipad
	memxor(tmp, 0x36, mdlen);
	if(sha512_update(&md, tmp, mdlen) != 0)
		return false;

	// message
	if(sha512_update(&md, msg, msglen) != 0)
		return false;

	if(sha512_final(&md, tmp + mdlen) != 0)
		return false;

	// opad
	memxor(tmp, 0x36 ^ 0x5c, mdlen);
	if(sha512(tmp, sizeof tmp, out) != 0)
		return false;

	return true;
}
示例#2
0
文件: sha.c 项目: abrauchli/allnet
/* the result array must have size SHA512_SIZE */
void sha512hmac (const char * data, int dsize, const char * key, int ksize,
                 char * result)
{
  char key_copy [SHA512_BLOCK_SIZE];
  bzero (key_copy, sizeof (key_copy));
  if (ksize <= SHA512_BLOCK_SIZE) {
    memcpy (key_copy, key, ksize);
  } else {
    sha512 (key, ksize, key_copy);  /* only fills half of key_copy */
  }

  char ipad [SHA512_BLOCK_SIZE];
  char opad [SHA512_BLOCK_SIZE];

  int i;
  for (i = 0; i < SHA512_BLOCK_SIZE; i++) {
    ipad [i] = 0x36 ^ key_copy [i];
    opad [i] = 0x5c ^ key_copy [i];
  }

  char * data1 = malloc_concat (ipad, SHA512_BLOCK_SIZE, data, dsize);
  char hash1 [SHA512_SIZE];
  sha512 (data1, SHA512_BLOCK_SIZE + dsize, hash1);
  free (data1);

  char * data2 = malloc_concat (opad, SHA512_BLOCK_SIZE, hash1, SHA512_SIZE);
  sha512 (data2, SHA512_BLOCK_SIZE + SHA512_SIZE, result);
  free (data2);
}
示例#3
0
void attacker_send_hash(havege_state *havege_state, void* socket)
  //@ requires attacker_invariant(?pub, ?pred, ?kc, havege_state, socket, ?attacker);
  //@ ensures  attacker_invariant(pub, pred, kc, havege_state, socket, attacker);
{
  int temp;
  int size;
  char buffer[MAX_MESSAGE_SIZE];

  //@ open attacker_invariant(pub, pred, kc, havege_state, socket, attacker);

  size = net_recv(socket, buffer, MAX_MESSAGE_SIZE);
  if (size < MINIMAL_STRING_SIZE)
  {
    //@ close attacker_invariant(pub, pred, kc, havege_state, socket, attacker);
    return;
  }
  //@ assert chars(buffer, size, ?pay);

  char hash[64];
  //@ chars_to_crypto_chars(buffer, size);
  //@ HASH_PUB_PAYLOAD(pay)
  sha512(buffer, (unsigned int) size, hash, 0);
  //@ assert cryptogram(hash, 64, ?h_ccs, ?h_cg);
  //@ assert h_cg == cg_hash(cs_to_ccs(pay));
  //@ assert is_hash_is_public(?proof, pub, pred);
  //@ crypto_chars_to_chars(buffer, size);
  //@ public_chars(buffer, size);
  //@ proof(h_cg);
  //@ public_cryptogram(hash, h_cg);
  net_send(socket, hash, 64);

  //@ close attacker_invariant(pub, pred, kc, havege_state, socket, attacker);
}
示例#4
0
文件: main.c 项目: drgoebbels/sabot
int main(int arc, char *argv[])
{
    aes_digest_s *tmp;
    
    compile_regex("^(a|bc)*(hello(bob|(a|b)))?[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$");
    
    return 0;
    print_aesdigest(tmp = aes_encrypt(clear, sizeof(clear)-1, key));
    puts("\n");
    print_aesdigest(aes_decrypt(tmp->data, tmp->size, key));
    
    return 0;
    
    
    
    
    puts("Welcome to SA Bot");
    sha512_s digest;
    
    sha512(argv[1], strlen(argv[1]), &digest);

    print_sha512digest(&digest);
    //store_account();
    //authenticate();
    /*for(i = 0; i < N_TESTS; i++) {
        time = clock();
        sha512(argv[1], strlen(argv[1]), &digest);
        accum += (clock() - time);
    }
    
    print_digest(&digest);*/
   // printf("\naverage time: %f ticks\n", accum/(double)N_TESTS);
    
    exit(EXIT_SUCCESS);
}
示例#5
0
/*
 * Entropy accumulator update
 */
static int entropy_update( entropy_context *ctx, unsigned char source_id,
                           const unsigned char *data, size_t len )
{
    unsigned char header[2];
    unsigned char tmp[ENTROPY_BLOCK_SIZE];
    size_t use_len = len;
    const unsigned char *p = data;

    if( use_len > ENTROPY_BLOCK_SIZE )
    {
#if defined(POLARSSL_ENTROPY_SHA512_ACCUMULATOR)
        sha512( data, len, tmp, 0 );
#else
        sha256( data, len, tmp, 0 );
#endif
        p = tmp;
        use_len = ENTROPY_BLOCK_SIZE;
    }

    header[0] = source_id;
    header[1] = use_len & 0xFF;

#if defined(POLARSSL_ENTROPY_SHA512_ACCUMULATOR)
    sha512_update( &ctx->accumulator, header, 2 );
    sha512_update( &ctx->accumulator, p, use_len );
#else
    sha256_update( &ctx->accumulator, header, 2 );
    sha256_update( &ctx->accumulator, p, use_len );
#endif

    return( 0 );
}
示例#6
0
void PCH_ChartManager::LoadMidiFile(std::string filePath)
{
    fs::path boostPath = filePath;
    PCH_CString strPath = filePath.c_str();//(PCH_CString)boostPath.c_str();
    printf("Loading %s...\n",strPath);
    std::ifstream in(strPath, std::ios::in | std::ios::binary);
    std::string contents;
    if (in)
    {
        in.seekg(0, std::ios::end);
        contents.resize(in.tellg());
        in.seekg(0, std::ios::beg);
        in.read(&contents[0], contents.size());
        in.close();
    }
    else
    {

        printf("Error while reading the file directly!\n");
        return;
    }

    std::string strHash = sha512(contents);
    PCH_CString sHash = strHash.c_str();

    bool needInsert = false;
    bool needUpdate = false;

    if(_db->ChartExists(strPath))
    {
        printf("File found on database. Checking hash...\n");
        if(_db->ChartHashChanged(strPath,sHash))
        {
            printf("Hash code changed. Update is required.\n");
            needInsert = true;
            needUpdate = true;
        }
        else
        {
            printf("File OK. No update required.\n");
        }
    }
    else
    {
        printf("File not found on database. Adding...\n");
        needInsert = true;
    }

    if(needInsert)
    {
        printf("Adding/updating...\n");
        LoadMidiToDB(strPath,sHash, needUpdate);
        printf("Load COMPLETE\n");
    }
    int chartID = _db->GetChartID(strPath);
    std::string sss = boostPath.filename().string();
    std::pair<PCH_Number, std::string> v(chartID,sss);
    _chartList.push_back(v);
}
示例#7
0
文件: digest.c 项目: PHPDOTSQL/fwknop
/* Compute SHA512 hash on in and store the hex string result in out.
*/
void
sha512_hex(char *out, size_t size_out, unsigned char *in, size_t size_in)
{
    uint8_t       md[SHA512_DIGEST_LEN];

    sha512(md, in, size_in);
    digest_to_hex(out, size_out, md, SHA512_DIGEST_LEN);
}
示例#8
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);
}
示例#9
0
文件: digest.c 项目: PHPDOTSQL/fwknop
/* Compute SHA512 hash on in and store the base64 string result in out.
*/
void
sha512_base64(char *out, unsigned char *in, size_t size)
{
    uint8_t       md[SHA512_DIGEST_LEN];

    sha512(md, in, size);
    b64_encode(md, out, SHA512_DIGEST_LEN);

    strip_b64_eq(out);
}
示例#10
0
int
CWin32Platform::genUserPW(const char * salt, char * retbuf, int maxlen)
{
	char buf[1024];
	time_t tm;
	int rnd = rand();
	time(&tm);
	sprintf(buf, "%d.%ld.%s", rnd, (u32)tm, salt);
	return sha512(buf, retbuf, maxlen);
}
示例#11
0
文件: sha.c 项目: abrauchli/allnet
/* the result array must have size rsize, only the first rsize bytes
 * of the hash are saved (or the hash is padded with zeros) */
void sha1_bytes (const char * data, int dsize, char * result, int rsize)
{
  char sha [SHA1_SIZE];
  sha512 (data, dsize, sha);
  if (rsize <= SHA1_SIZE) {
    memcpy (result, sha, rsize);
  } else {
    memcpy (result, sha, SHA1_SIZE);
    bzero (result + SHA1_SIZE, rsize - SHA1_SIZE);
  }
}
示例#12
0
文件: sha.c 项目: abrauchli/allnet
static void run_test (char * text, int tlen, char * expected)
{
  char result [SHA512_SIZE];
  sha512 (text, tlen, result);
  if (memcmp (result, expected, sizeof (result)) != 0) {
    printf ("error (sha512 of %s): expected\n", text);
    print_data ((unsigned char *) expected, sizeof (result));
  }
  printf ("sha of %s (%d chars) is:\n", text, tlen);
  print_data ((unsigned char *) result, sizeof (result));
}
示例#13
0
void ed25519_create_keypair(unsigned char *public_key, unsigned char *private_key, const unsigned char *seed) {
    ge_p3 A;

    sha512(seed, 32, private_key);
    private_key[0] &= 248;
    private_key[31] &= 63;
    private_key[31] |= 64;

    ge_scalarmult_base(&A, private_key);
    ge_p3_tobytes(public_key, &A);
}
示例#14
0
struct item *create_hash(struct item *payload)
  /*@ requires [?f0]world(?pub, ?key_clsfy) &*&
               [?f1]item(payload, ?pay, pub); @*/
  /*@ ensures  [f0]world(pub, key_clsfy) &*&
               [f1]item(payload, pay, pub) &*& item(result, ?hash, pub) &*& 
               col || hash == hash_item(some(pay)); @*/
{
  //@ open [f1]item(payload, pay, pub);
  //@ open [_]item_constraints(pay, ?pay_cs, pub);
  //@ assert [f1]payload->content |-> ?p_cont &*& [f1]payload->size |-> ?p_size;
  struct item* hash = malloc(sizeof(struct item));
  if (hash == 0){abort_crypto_lib("malloc of item failed");}
  
  hash->size = TAG_LENGTH + HASH_SIZE;
  hash->content = malloc_wrapper(hash->size);
  write_tag(hash->content, TAG_HASH);
  
  if (payload->size < MINIMAL_STRING_SIZE)
    {abort_crypto_lib("Payload of hash was to small");}
  sha512(payload->content, (unsigned int) payload->size, hash->content + TAG_LENGTH, 0);
  
  //@ open [f0]world(pub, key_clsfy);  
  //@ assert hash->content |-> ?cont &*& hash->size |-> ?size;
  //@ public_chars(cont, TAG_LENGTH);
  //@ assert chars(cont, TAG_LENGTH, ?cs_tag);
  //@ assert cs_tag == full_tag(TAG_HASH);
  //@ open cryptogram(cont + TAG_LENGTH, HASH_SIZE, ?cs_cont, ?h_cg);
  //@ assert h_cg == cg_hash(pay_cs);
  //@ item h = hash_item(some(pay));
  //@ close ic_cg(h)(cs_cont, h_cg);
  //@ list<char> cs = append(cs_tag, cs_cont);
  //@ if (col) public_chars(cont + TAG_LENGTH, HASH_SIZE);
  //@ if (col) public_generated_join(polarssl_pub(pub), cs_tag, cs_cont);  
  //@ if (col) chars_to_secret_crypto_chars(cont + TAG_LENGTH, HASH_SIZE);
  //@ chars_to_secret_crypto_chars(cont, TAG_LENGTH);
  //@ crypto_chars_join(cont);
  //@ close [f0]world(pub, key_clsfy);
  //@ close ic_parts(h)(cs_tag, cs_cont);
  //@ WELL_FORMED(cs_tag, cs_cont, TAG_HASH)
  //@ close well_formed_item_chars(h)(pay_cs);
  //@ leak well_formed_item_chars(h)(pay_cs);
  //@ close item_constraints(h, cs, pub);
  //@ leak item_constraints(h, cs, pub);
  //@ close item(hash, h, pub);
  
  return hash;
  //@ close [f1]item(payload, pay, pub);
}
示例#15
0
int passcheck_cb(void *flag, int argc, char **argv, char **colnames){

	if (argc < 3)
		return 0;

	int showflag = *((int*)flag);

	char *label = argv[0];
	char *salt = argv[1];
	char *hash = argv[2];

	char *pass;
	char passhash[SHA512_OUTPUT] = {0};
	int correct = 0;

	struct termios term;
	tcgetattr(STDIN_FILENO, &term);
	term.c_lflag &= ~ECHO;

	while (correct != 1){

		if (!showflag) tcsetattr(STDIN_FILENO, TCSANOW, &term);
		int skip = stdin_prompt(label, &pass);
		if (!showflag) { term.c_lflag &= ~ECHO; tcsetattr(STDIN_FILENO, TCSANOW, &term);}

		if (skip != 0){
			fprintf(stdout, "\x1B[1;34;49mSkipping.\x1B[0;0;0m\n");
			break;
		}

		sha512(pass, salt, passhash);

		if (strcmp(hash, passhash) != 0){
			fprintf(stdout, "\x1B[1;31;49mWrong!\x1B[0;0;0m\n");
		}
		else {
			fprintf(stdout, "\x1B[1;32;49mCorrect!\x1B[0;0;0m\n");
			correct = 1;
		}

		free(pass);

	}

	return 0;

}
示例#16
0
void hmac_sha512_init(hmac_sha512_ctx *ctx, unsigned char *key,
                      unsigned int key_size)
{
    unsigned int fill;
    unsigned int num;

    unsigned char *key_used;
    unsigned char key_temp[SHA512_DIGEST_SIZE];
    int i;

    if (key_size == SHA512_BLOCK_SIZE) {
        key_used = key;
        num = SHA512_BLOCK_SIZE;
    } else {
        if (key_size > SHA512_BLOCK_SIZE){
            key_used = key_temp;
            num = SHA512_DIGEST_SIZE;
            sha512(key, key_size, key_used);
        } else { /* key_size > SHA512_BLOCK_SIZE */
            key_used = key;
            num = key_size;
        }
        fill = SHA512_BLOCK_SIZE - num;

        memset(ctx->block_ipad + num, 0x36, fill);
        memset(ctx->block_opad + num, 0x5c, fill);
    }

    for (i = 0; i < num; i++) {
        ctx->block_ipad[i] = key_used[i] ^ 0x36;
        ctx->block_opad[i] = key_used[i] ^ 0x5c;
    }

    sha512_init(&ctx->ctx_inside);
    sha512_update(&ctx->ctx_inside, ctx->block_ipad, SHA512_BLOCK_SIZE);

    sha512_init(&ctx->ctx_outside);
    sha512_update(&ctx->ctx_outside, ctx->block_opad,
                  SHA512_BLOCK_SIZE);

    /* for hmac_reinit */
    memcpy(&ctx->ctx_inside_reinit, &ctx->ctx_inside,
           sizeof(sha512_ctx));
    memcpy(&ctx->ctx_outside_reinit, &ctx->ctx_outside,
           sizeof(sha512_ctx));
}
示例#17
0
文件: tests.c 项目: zdone/libhash
void test_sha512() {
	const char * tests[4] = {
		"", "A", "0123456789", "abcdefghijklmnopqrstuvwxyz"
	};
	const char * oks[4] = {
		"cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e",
		"21b4f4bd9e64ed355c3eb676a28ebedaf6d8f17bdc365995b319097153044080516bd083bfcce66121a3072646994c8430cc382b8dc543e84880183bf856cff5",
		"bb96c2fc40d2d54617d6f276febe571f623a8dadf0b734855299b0e107fda32cf6b69f2da32b36445d73690b93cbd0f7bfc20e0f7f28553d2a4428f23b716e90",
		"4dbff86cc2ca1bae1e16468a05cb9881c97f1753bce3619034898faa1aabe429955a1bf8ec483d7421fe3c1646613a59ed5441fb0f321389f77f48a879c7b1f1"
	};
	uint8_t hash[SHA512_HASH_SIZE];
	char string[SHA512_STRING_HASH_SIZE];
	int i;
	puts("\n\nTesting SHA512...\n");
	for (i = 0; i < 4; i++) {
		sha512(tests[i], strlen(tests[i]), hash);
		sha512_hash_to_string(hash, string);
		printf("%s\n%s\n--> %s\n\n", tests[i], string, strcmp(string, oks[i]) == 0 ? "OK" : "FAIL");
	}
	puts("\nTest done.\n");
}
示例#18
0
static bool do_test(const struct test *t)
{
	struct sha512 h;
	char got[128 + 1];
	bool passed;
	size_t i, vector_len = strlen(t->vector) / 2;
	void *vector = xmalloc(vector_len);

	hex_decode(t->vector, vector_len * 2, vector, vector_len);

	for (i = 0; i < t->repetitions; i++) {
		sha512(&h, vector, vector_len);
		if (t->repetitions > 1)
			memcpy(vector, &h, sizeof(h));
	}

	hex_encode(&h, sizeof(h), got, sizeof(got));

	passed = strcmp(t->expected, got) == 0;
	free(vector);
	return passed;
}
示例#19
0
文件: sha2_test.c 项目: ValkaTR/nncms
int
main( int argc, char *argv[] )
{
    unsigned char digest[SHA512_DIGEST_SIZE]; int i;
    unsigned char output[2 * SHA512_DIGEST_SIZE + 1];

    if( argc != 2 )
    {
        fprintf( stderr, "Usage: %s <string>\n", argv[0] );
        exit( 1 );
    }

    sha512( argv[1], strlen( (char *) argv[1] ), digest );

    output[2 * SHA512_DIGEST_SIZE] = '\0';
    for( i = 0; i < (int) SHA512_DIGEST_SIZE ; i++ )
    {
       sprintf( (char *) output + 2 * i, "%02x", digest[i] );
    }

    printf( "String: %s\n", argv[1] );
    printf( "Hash: %s\n", output );
}
示例#20
0
	void HashFunctions::sha512(const DataBuffer &data, unsigned char out_hash[64])
	{
		sha512(data.get_data(), data.get_size(), out_hash);
	}
示例#21
0
	void HashFunctions::sha512(const std::string &data, unsigned char out_hash[64])
	{
		sha512(data.data(), data.length(), out_hash);
	}
示例#22
0
	std::string HashFunctions::sha512(const std::string &data, bool uppercase)
	{
		return sha512(data.data(), data.length(), uppercase);
	}
示例#23
0
	std::string HashFunctions::sha512(const DataBuffer &data, bool uppercase)
	{
		return sha512(data.get_data(), data.get_size(), uppercase);
	}
示例#24
0
int main(int argc, char **argv){

	int err;
	char *err_msg;
	sqlite3 *db;
	char dbpath[PATH_MAX] = {0};

	char *dellabel = NULL;
	int addflag = 0;
	int showflag = 0;
	int delflag = 0;
	int listflag = 0;
	int initdb = 0;
	int c;

	while ((c = getopt (argc, argv, "asd:lh")) != -1){
		switch (c){
			case 'a':
				addflag = 1;
				break;
			case 's':
				showflag = 1;
				break;
			case 'd':
				delflag = 1;
				dellabel = optarg;
				break;
			case 'l':
				listflag = 1;
				break;
			case 'h':
			default:
				fprintf(stdout, usage);
				exit(0);
		}
	}

	if (addflag & delflag){
		fprintf(stderr, "Specify either -a or -d, not both\n");
		exit(1);
	}

	if (fs_datadir_init(DATA_DIR)){
		perror("Failed to open config directory");
		exit(1);
	}

	if (fs_exists_relative(DB_NAME) != 0){
		puts("First run, initializing db...");
		initdb = 1;
	}

	strcat(dbpath, fs_datadir_getpath());
	strcat(dbpath, "/");
	strcat(dbpath, DB_NAME);


	if ((err = sqlite3_open(dbpath, &db)) != SQLITE_OK){
		fprintf(stderr, "sqlite3_open failure: %s\n", sqlite3_errmsg(db));
		sqlite3_close(db);
		exit(1);
	}

	if (initdb){
		char *sql = "CREATE TABLE passwords (label TEXT, salt TEXT, hash TEXT, created DATETIME, last_success DATETIME);";
		err = sqlite3_exec(db, sql, 0, 0, &err_msg);
		if (err != SQLITE_OK){
			fprintf(stderr, "SQL error: %s\n", err_msg);
			sqlite3_free(err_msg);
			sqlite3_close(db);
			exit(1);
		}
	}

	if (listflag){

		int err;
		char *err_msg;

		err = sqlite3_exec(db, "SELECT created, label FROM passwords ORDER BY label ASC", passlist_cb, NULL, &err_msg);

		if (err != SQLITE_OK){
			fprintf(stderr, "SQL SELECT error: %s\n", err_msg);
			sqlite3_free(err_msg);
			sqlite3_close(db);
			exit(1);
		}

		exit(0);
	}

	if (delflag){

		int err;
		char *yn;

		if (sql_label_exists(db, dellabel) == 0){
			fprintf(stderr, "A password with that label does not exist\n");
			sqlite3_close(db);
			exit(1);
		}

		fprintf(stdout, "You are about to delete the entry labeled ``%s''\n", dellabel);

		err = stdin_prompt("Continue [yn]", &yn);
		if (err != 0){
			exit(0);
		}

		if (strcmp("y", yn) == 0){

			sql_label_delete(db, dellabel);

			puts("Entry deleted.");

		}

		exit(0);

	}

	if (addflag){

		char *label, *pass;
		time_t rawtime;
		struct tm *timeinfo;
		char timestr[24] = {0};
		char *sql_p = "INSERT INTO passwords (label, salt, hash, created, last_success) VALUES (?, ?, ?, ?, ?);";
		sqlite3_stmt *res;
		char hash[SHA512_OUTPUT];

		puts("Adding new password");

		if (stdin_prompt("label", &label)){
			sqlite3_close(db);
			fprintf(stderr, "entry canceled\n");
			exit(1);
		}

		if (sql_label_exists(db, label) != 0){
			fprintf(stderr, "A password with that label already exists.\n");
			exit(1);
		}

		if (stdin_prompt("pass", &pass)){
			sqlite3_close(db);
			fprintf(stderr, "entry canceled\n");
			exit(1);
		}

		time(&rawtime);
		timeinfo = localtime(&rawtime);
		strftime(timestr, sizeof(timestr), "%Y-%m-%d %H:%M:%S", timeinfo);

		err = sqlite3_prepare_v2(db, sql_p, -1, &res, 0);

		if (err == SQLITE_OK){
			char salt[SALT_LEN+1];
			gensalt(salt, SALT_LEN);
			sha512(pass, salt, hash);
			sqlite3_bind_text(res, 1, label, strlen(label), NULL);
			sqlite3_bind_text(res, 2, salt, SALT_LEN, NULL);
			sqlite3_bind_text(res, 3, hash, strlen(hash), NULL);
			sqlite3_bind_text(res, 4, timestr, strlen(timestr), NULL);
			sqlite3_bind_text(res, 5, timestr, strlen(timestr), NULL);
		}
		else {
			fprintf(stderr, "Failed to prepare insert statement: %s\n", sqlite3_errmsg(db));
			sqlite3_close(db);
			exit(1);
		}


		err = sqlite3_step(res);

		free(label);
		free(pass);

		if (err != SQLITE_OK && err != SQLITE_DONE){
			fprintf(stderr, "Failed to execute prepared insert: %s\n", sqlite3_errmsg(db));
			sqlite3_close(db);
			exit(1);
		}

		sqlite3_finalize(res);

		puts("Entry added successfully.");

	}
	else {

		int entries = 0;
		sqlite3_stmt *res;

		err = sqlite3_prepare_v2(db, "SELECT count(*) from passwords", -1, &res, 0);
		if (err != SQLITE_OK){
			fprintf(stderr, "SQL prepare failure: %s\n",  sqlite3_errmsg(db));
			sqlite3_close(db);
			exit(1);
		}

		err = sqlite3_step(res);

		if (err == SQLITE_ROW){
			entries = sqlite3_column_int(res, 0);
		}

		sqlite3_finalize(res);

		if (entries == 0){
			fprintf(stderr, "No passwords in db\n");
			exit(0);
		}

		fprintf(stdout, "%d passwords in db.\n", entries);

		err = sqlite3_exec(db, "SELECT label, salt, hash FROM passwords ORDER BY RANDOM()", passcheck_cb, &showflag, &err_msg);

		if (err != SQLITE_OK){
			fprintf(stderr, "SQL SELECT error: %s\n", err_msg);
			sqlite3_free(err_msg);
			sqlite3_close(db);
			exit(1);
		}

		puts("Finished.");

	}

	sqlite3_close(db);

	return 0;
}
示例#25
0
/**
 * @Brief Compute the certificate fingerprint(hash of DER formated certificate)
 * hash function to use shall be the same used by certificate signature(this is a way to ensure that the hash function is available at both ends as they already agreed on certificate)
 * However, peer may provide a fingerprint generated with another hash function(indicated at the fingerprint header).
 * In case certificate and fingerprint hash function differs, issue a warning and use the fingerprint one
 *
 * @param[in]	certificate		Certificate we shall compute the fingerprint
 * @param[in]	peer_fingerprint	Fingerprint received from peer, check its header to get the hash function used to generate it
 *
 * @return 0 if the fingerprint doesn't match, 1 is they do.
 */
static uint8_t ms_dtls_srtp_check_certificate_fingerprint(const x509_crt *certificate, const char *peer_fingerprint) {
	unsigned char fingerprint[256]; /* maximum length of the fingerprint for sha-512: 8+3*64+1 so we're good with 256 bytes buffer */
	unsigned char buffer[64]; /* buffer is max length of returned hash, which is 64 in case we use sha-512 */
	size_t hash_length = 0;
	char hash_alg_string[8]; /* buffer to store the string description of the algo, longest is SHA-512(7 chars + null termination) */
	md_type_t hash_function = POLARSSL_MD_NONE;

	/* get Hash algorithm used from peer fingerprint */
	if (strncasecmp(peer_fingerprint, "sha-1 ", 6) ==0 ) {
		sha1(certificate->raw.p, certificate->raw.len, buffer);
		hash_length = 20;
		memcpy(hash_alg_string, "sha-1", 6);
		hash_function = POLARSSL_MD_SHA1;
	} else if (strncasecmp(peer_fingerprint, "sha-224 ", 8) ==0 ){
		sha256(certificate->raw.p, certificate->raw.len, buffer, 1); /* last argument is a boolean, indicate to output sha-224 and not sha-256 */
		hash_length = 28;
		memcpy(hash_alg_string, "sha-224", 8);
		hash_function = POLARSSL_MD_SHA224;
	} else if (strncasecmp(peer_fingerprint, "sha-256 ", 8) ==0 ){
		sha256(certificate->raw.p, certificate->raw.len, buffer, 0);
		hash_length = 32;
		memcpy(hash_alg_string, "sha-256", 8);
		hash_function = POLARSSL_MD_SHA256;
	} else if (strncasecmp(peer_fingerprint, "sha-384 ", 8) ==0 ){
		sha512(certificate->raw.p, certificate->raw.len, buffer, 1); /* last argument is a boolean, indicate to output sha-384 and not sha-512 */
		hash_length = 48;
		memcpy(hash_alg_string, "sha-384", 8);
		hash_function = POLARSSL_MD_SHA384;
	} else if (strncasecmp(peer_fingerprint, "sha-512 ", 8) ==0 ){
		sha512(certificate->raw.p, certificate->raw.len, buffer, 1); /* last argument is a boolean, indicate to output sha-384 and not sha-512 */
		hash_length = 64;
		memcpy(hash_alg_string, "sha-512", 8);
		hash_function = POLARSSL_MD_SHA512;
	} else { /* we have an unknown hash function: return null */
		ms_error("DTLS-SRTP received invalid peer fingerprint, hash function unknown");
		return 0;
	}

	/* check that hash function used match the one used for certificate signature */
	if (hash_function != certificate->sig_md) {
		ms_warning("DTLS-SRTP peer fingerprint generated using a different hash function that the one used for certificate signature, peer is nasty but lucky we have the hash function required anyway");
	}

	if (hash_length>0) {
		int i;
		int fingerprint_index = strlen(hash_alg_string);
		char prefix=' ';
		sprintf((char *)fingerprint, "%s", hash_alg_string);
		for (i=0; i<hash_length; i++, fingerprint_index+=3) {
			sprintf((char *)(fingerprint+fingerprint_index),"%c%02X", prefix,buffer[i]);
			prefix=':';
		}
		*(fingerprint+fingerprint_index) = '\0';
	}

	/* compare fingerprints */
	if (strncasecmp((const char *)fingerprint, peer_fingerprint, strlen((const char *)fingerprint)) == 0) {
		return 1;
	} else {
		ms_error("DTLS Handshake successful but fingerprints differ received : %s computed %s", peer_fingerprint, fingerprint);
		return 0;
	}
}
示例#26
0
文件: invitation.c 项目: xentec/tinc
int cmd_join(int argc, char *argv[]) {
	free(data);
	data = NULL;
	datalen = 0;

	if(argc > 2) {
		fprintf(stderr, "Too many arguments!\n");
		return 1;
	}

	// Make sure confbase exists and is accessible.
	if(!confbase_given && mkdir(confdir, 0755) && errno != EEXIST) {
		fprintf(stderr, "Could not create directory %s: %s\n", confdir, strerror(errno));
		return 1;
	}

	if(mkdir(confbase, 0777) && errno != EEXIST) {
		fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
		return 1;
	}

	if(access(confbase, R_OK | W_OK | X_OK)) {
		fprintf(stderr, "No permission to write in directory %s: %s\n", confbase, strerror(errno));
		return 1;
	}

	// If a netname or explicit configuration directory is specified, check for an existing tinc.conf.
	if((netname || confbasegiven) && !access(tinc_conf, F_OK)) {
		fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
		return 1;
	}

	// Either read the invitation from the command line or from stdin.
	char *invitation;

	if(argc > 1) {
		invitation = argv[1];
	} else {
		if(tty)
			fprintf(stderr, "Enter invitation URL: ");
		errno = EPIPE;
		if(!fgets(line, sizeof line, stdin)) {
			fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
			return false;
		}
		invitation = line;
	}

	// Parse the invitation URL.
	rstrip(line);

	char *slash = strchr(invitation, '/');
	if(!slash)
		goto invalid;

	*slash++ = 0;

	if(strlen(slash) != 48)
		goto invalid;

	char *address = invitation;
	char *port = NULL;
	if(*address == '[') {
		address++;
		char *bracket = strchr(address, ']');
		if(!bracket)
			goto invalid;
		*bracket = 0;
		if(bracket[1] == ':')
			port = bracket + 2;
	} else {
		port = strchr(address, ':');
		if(port)
			*port++ = 0;
	}

	if(!port || !*port)
		port = "655";

	if(!b64decode(slash, hash, 24) || !b64decode(slash + 24, cookie, 24))
		goto invalid;

	// Generate a throw-away key for the invitation.
	ecdsa_t *key = ecdsa_generate();
	if(!key)
		return 1;

	char *b64key = ecdsa_get_base64_public_key(key);

	// Connect to the tinc daemon mentioned in the URL.
	struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
	if(!ai)
		return 1;

	struct addrinfo *aip = NULL;

next:
	if(!aip)
		aip = ai;
	else {
		aip = aip->ai_next;
		if(!aip)
			return 1;
	}

	sock = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
	if(sock <= 0) {
		fprintf(stderr, "Could not open socket: %s\n", strerror(errno));
		goto next;
	}

	if(connect(sock, aip->ai_addr, aip->ai_addrlen)) {
		char *addrstr, *portstr;
		sockaddr2str((sockaddr_t *)aip->ai_addr, &addrstr, &portstr);
		fprintf(stderr, "Could not connect to %s port %s: %s\n", addrstr, portstr, strerror(errno));
		free(addrstr);
		free(portstr);
		closesocket(sock);
		goto next;
	}

	fprintf(stderr, "Connected to %s port %s...\n", address, port);

	// Tell him we have an invitation, and give him our throw-away key.
	int len = snprintf(line, sizeof line, "0 ?%s %d.%d\n", b64key, PROT_MAJOR, PROT_MINOR);
	if(len <= 0 || len >= sizeof line)
		abort();

	if(!sendline(sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
		fprintf(stderr, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
		closesocket(sock);
		goto next;
	}

	char hisname[4096] = "";
	int code, hismajor, hisminor = 0;

	if(!recvline(sock, line, sizeof line) || sscanf(line, "%d %s %d.%d", &code, hisname, &hismajor, &hisminor) < 3 || code != 0 || hismajor != PROT_MAJOR || !check_id(hisname) || !recvline(sock, line, sizeof line) || !rstrip(line) || sscanf(line, "%d ", &code) != 1 || code != ACK || strlen(line) < 3) {
		fprintf(stderr, "Cannot read greeting from peer\n");
		closesocket(sock);
		goto next;
	}

	// Check if the hash of the key he gave us matches the hash in the URL.
	char *fingerprint = line + 2;
	char hishash[64];
	if(sha512(fingerprint, strlen(fingerprint), hishash)) {
		fprintf(stderr, "Could not create digest\n%s\n", line + 2);
		return 1;
	}
	if(memcmp(hishash, hash, 18)) {
		fprintf(stderr, "Peer has an invalid key!\n%s\n", line + 2);
		return 1;

	}
	
	ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
	if(!hiskey)
		return 1;

	// Start an SPTPS session
	if(!sptps_start(&sptps, NULL, true, false, key, hiskey, "tinc invitation", 15, invitation_send, invitation_receive))
		return 1;

	// Feed rest of input buffer to SPTPS
	if(!sptps_receive_data(&sptps, buffer, blen))
		return 1;

	while((len = recv(sock, line, sizeof line, 0))) {
		if(len < 0) {
			if(errno == EINTR)
				continue;
			fprintf(stderr, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
			return 1;
		}

		char *p = line;
		while(len) {
			int done = sptps_receive_data(&sptps, p, len);
			if(!done)
				return 1;
			len -= done;
			p += done;
		}
	}
	
	sptps_stop(&sptps);
	ecdsa_free(hiskey);
	ecdsa_free(key);
	closesocket(sock);

	if(!success) {
		fprintf(stderr, "Connection closed by peer, invitation cancelled.\n");
		return 1;
	}

	return 0;

invalid:
	fprintf(stderr, "Invalid invitation URL.\n");
	return 1;
}
示例#27
0
int entropy_func( void *data, unsigned char *output, size_t len )
{
    int ret, count = 0, i, reached;
    entropy_context *ctx = (entropy_context *) data;
    unsigned char buf[ENTROPY_BLOCK_SIZE];

    if( len > ENTROPY_BLOCK_SIZE )
        return( POLARSSL_ERR_ENTROPY_SOURCE_FAILED );

#if defined(POLARSSL_THREADING_C)
    if( ( ret = polarssl_mutex_lock( &ctx->mutex ) ) != 0 )
        return( ret );
#endif

    /*
     * Always gather extra entropy before a call
     */
    do
    {
        if( count++ > ENTROPY_MAX_LOOP )
        {
            ret = POLARSSL_ERR_ENTROPY_SOURCE_FAILED;
            goto exit;
        }

        if( ( ret = entropy_gather_internal( ctx ) ) != 0 )
            goto exit;

        reached = 0;

        for( i = 0; i < ctx->source_count; i++ )
            if( ctx->source[i].size >= ctx->source[i].threshold )
                reached++;
    }
    while( reached != ctx->source_count );

    memset( buf, 0, ENTROPY_BLOCK_SIZE );

#if defined(POLARSSL_ENTROPY_SHA512_ACCUMULATOR)
    sha512_finish( &ctx->accumulator, buf );

    /*
     * Reset accumulator and counters and recycle existing entropy
     */
    memset( &ctx->accumulator, 0, sizeof( sha512_context ) );
    sha512_starts( &ctx->accumulator, 0 );
    sha512_update( &ctx->accumulator, buf, ENTROPY_BLOCK_SIZE );

    /*
     * Perform second SHA-512 on entropy
     */
    sha512( buf, ENTROPY_BLOCK_SIZE, buf, 0 );
#else /* POLARSSL_ENTROPY_SHA512_ACCUMULATOR */
    sha256_finish( &ctx->accumulator, buf );

    /*
     * Reset accumulator and counters and recycle existing entropy
     */
    memset( &ctx->accumulator, 0, sizeof( sha256_context ) );
    sha256_starts( &ctx->accumulator, 0 );
    sha256_update( &ctx->accumulator, buf, ENTROPY_BLOCK_SIZE );

    /*
     * Perform second SHA-256 on entropy
     */
    sha256( buf, ENTROPY_BLOCK_SIZE, buf, 0 );
#endif /* POLARSSL_ENTROPY_SHA512_ACCUMULATOR */

    for( i = 0; i < ctx->source_count; i++ )
        ctx->source[i].size = 0;

    memcpy( output, buf, len );

    ret = 0;

exit:
#if defined(POLARSSL_THREADING_C)
    if( polarssl_mutex_unlock( &ctx->mutex ) != 0 )
        return( POLARSSL_ERR_THREADING_MUTEX_ERROR );
#endif

    return( ret );
}
示例#28
0
int main()
{
    static const unsigned char *vectors[4][3] =
    {   /* SHA-224 */
        {
        "23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7",
        "75388b16512776cc5dba5da1fd890150b0c6455cb4f58b1952522525",
        "20794655980c91d8bbb4c1ea97618a4bf03f42581948b2ee4ee7ad67",
        },
        /* SHA-256 */
        {
        "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
        "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1",
        "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0",
        },
        /* SHA-384 */
        {
        "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed"
        "8086072ba1e7cc2358baeca134c825a7",
        "09330c33f71147e83d192fc782cd1b4753111b173b3b05d22fa08086e3b0f712"
        "fcc7c71a557e2db966c3e9fa91746039",
        "9d0e1809716474cb086e834e310a4a1ced149e9c00f248527972cec5704c2a5b"
        "07b8b3dc38ecc4ebae97ddd87f3d8985",
        },
        /* SHA-512 */
        {
        "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a"
        "2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f",
        "8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018"
        "501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909",
        "e718483d0ce769644e2e42c7bc15b4638e1f98b13b2044285632a803afa973eb"
        "de0ff244877ea60a4cb0432ce577c31beb009c5c2c49aa2e4eadb217ad8cc09b"
        }
    };

    static const unsigned char message1[] = "abc";
    static const unsigned char message2a[] = "abcdbcdecdefdefgefghfghighijhi"
                                             "jkijkljklmklmnlmnomnopnopq";
    static const unsigned char message2b[] =
                                      "abcdefghbcdefghicdefghijdefghijkefghij"
                                      "klfghijklmghijklmnhijklmnoijklmnopjklm"
                                      "nopqklmnopqrlmnopqrsmnopqrstnopqrstu";
    unsigned char *message3;
    unsigned int message3_len  = 1000000;
    unsigned char digest[SHA512_DIGEST_SIZE];

    message3 = malloc(message3_len);
    if (message3 == NULL) {
        fprintf(stderr, "Can't allocate memory\n");
        return -1;
    }
    memset(message3, 'a', message3_len);

    printf("SHA-2 FIPS 180-2 Validation tests\n\n");
    printf("SHA-224 Test vectors\n");

    sha224(message1, strlen((char *) message1), digest);
    test(vectors[0][0], digest, SHA224_DIGEST_SIZE);
    sha224(message2a, strlen((char *) message2a), digest);
    test(vectors[0][1], digest, SHA224_DIGEST_SIZE);
    sha224(message3, message3_len, digest);
    test(vectors[0][2], digest, SHA224_DIGEST_SIZE);
    printf("\n");

    printf("SHA-256 Test vectors\n");

    sha256(message1, strlen((char *) message1), digest);
    test(vectors[1][0], digest, SHA256_DIGEST_SIZE);
    sha256(message2a, strlen((char *) message2a), digest);
    test(vectors[1][1], digest, SHA256_DIGEST_SIZE);
    sha256(message3, message3_len, digest);
    test(vectors[1][2], digest, SHA256_DIGEST_SIZE);
    printf("\n");

    printf("SHA-384 Test vectors\n");

    sha384(message1, strlen((char *) message1), digest);
    test(vectors[2][0], digest, SHA384_DIGEST_SIZE);
    sha384(message2b, strlen((char *) message2b), digest);
    test(vectors[2][1], digest, SHA384_DIGEST_SIZE);
    sha384(message3, message3_len, digest);
    test(vectors[2][2], digest, SHA384_DIGEST_SIZE);
    printf("\n");

    printf("SHA-512 Test vectors\n");

    sha512(message1, strlen((char *) message1), digest);
    test(vectors[3][0], digest, SHA512_DIGEST_SIZE);
    sha512(message2b, strlen((char *) message2b), digest);
    test(vectors[3][1], digest, SHA512_DIGEST_SIZE);
    sha512(message3, message3_len, digest);
    test(vectors[3][2], digest, SHA512_DIGEST_SIZE);
    printf("\n");

    printf("All tests passed.\n");

    return 0;
}
示例#29
0
static void sha512_wrap( const unsigned char *input, size_t ilen,
                    unsigned char *output )
{
    sha512( input, ilen, output, 0 );
}
示例#30
0
int main( int argc, char *argv[] )
{
    int keysize, i;
    unsigned char tmp[200];
    char title[TITLE_LEN];
    todo_list todo;

    if( argc == 1 )
        memset( &todo, 1, sizeof( todo ) );
    else
    {
        memset( &todo, 0, sizeof( todo ) );

        for( i = 1; i < argc; i++ )
        {
            if( strcmp( argv[i], "md4" ) == 0 )
                todo.md4 = 1;
            else if( strcmp( argv[i], "md5" ) == 0 )
                todo.md5 = 1;
            else if( strcmp( argv[i], "ripemd160" ) == 0 )
                todo.ripemd160 = 1;
            else if( strcmp( argv[i], "sha1" ) == 0 )
                todo.sha1 = 1;
            else if( strcmp( argv[i], "sha256" ) == 0 )
                todo.sha256 = 1;
            else if( strcmp( argv[i], "sha512" ) == 0 )
                todo.sha512 = 1;
            else if( strcmp( argv[i], "arc4" ) == 0 )
                todo.arc4 = 1;
            else if( strcmp( argv[i], "des3" ) == 0 )
                todo.des3 = 1;
            else if( strcmp( argv[i], "des" ) == 0 )
                todo.des = 1;
            else if( strcmp( argv[i], "aes_cbc" ) == 0 )
                todo.aes_cbc = 1;
            else if( strcmp( argv[i], "aes_gcm" ) == 0 )
                todo.aes_gcm = 1;
            else if( strcmp( argv[i], "camellia" ) == 0 )
                todo.camellia = 1;
            else if( strcmp( argv[i], "blowfish" ) == 0 )
                todo.blowfish = 1;
            else if( strcmp( argv[i], "havege" ) == 0 )
                todo.havege = 1;
            else if( strcmp( argv[i], "ctr_drbg" ) == 0 )
                todo.ctr_drbg = 1;
            else if( strcmp( argv[i], "hmac_drbg" ) == 0 )
                todo.hmac_drbg = 1;
            else if( strcmp( argv[i], "rsa" ) == 0 )
                todo.rsa = 1;
            else if( strcmp( argv[i], "dhm" ) == 0 )
                todo.dhm = 1;
            else if( strcmp( argv[i], "ecdsa" ) == 0 )
                todo.ecdsa = 1;
            else if( strcmp( argv[i], "ecdh" ) == 0 )
                todo.ecdh = 1;
            else
            {
                printf( "Unrecognized option: %s\n", argv[i] );
                printf( "Available options:" OPTIONS );
            }
        }
    }

    printf( "\n" );

    memset( buf, 0xAA, sizeof( buf ) );

#if defined(POLARSSL_MD4_C)
    if( todo.md4 )
        TIME_AND_TSC( "MD4", md4( buf, BUFSIZE, tmp ) );
#endif

#if defined(POLARSSL_MD5_C)
    if( todo.md5 )
        TIME_AND_TSC( "MD5", md5( buf, BUFSIZE, tmp ) );
#endif

#if defined(POLARSSL_RIPEMD160_C)
    if( todo.ripemd160 )
        TIME_AND_TSC( "RIPEMD160", ripemd160( buf, BUFSIZE, tmp ) );
#endif

#if defined(POLARSSL_SHA1_C)
    if( todo.sha1 )
        TIME_AND_TSC( "SHA-1", sha1( buf, BUFSIZE, tmp ) );
#endif

#if defined(POLARSSL_SHA256_C)
    if( todo.sha256 )
        TIME_AND_TSC( "SHA-256", sha256( buf, BUFSIZE, tmp, 0 ) );
#endif

#if defined(POLARSSL_SHA512_C)
    if( todo.sha512 )
        TIME_AND_TSC( "SHA-512", sha512( buf, BUFSIZE, tmp, 0 ) );
#endif

#if defined(POLARSSL_ARC4_C)
    if( todo.arc4 )
    {
        arc4_context arc4;
        arc4_setup( &arc4, tmp, 32 );
        TIME_AND_TSC( "ARC4", arc4_crypt( &arc4, BUFSIZE, buf, buf ) );
    }
#endif

#if defined(POLARSSL_DES_C) && defined(POLARSSL_CIPHER_MODE_CBC)
    if( todo.des3 )
    {
        des3_context des3;
        des3_set3key_enc( &des3, tmp );
        TIME_AND_TSC( "3DES",
                des3_crypt_cbc( &des3, DES_ENCRYPT, BUFSIZE, tmp, buf, buf ) );
    }

    if( todo.des )
    {
        des_context des;
        des_setkey_enc( &des, tmp );
        TIME_AND_TSC( "DES",
                des_crypt_cbc( &des, DES_ENCRYPT, BUFSIZE, tmp, buf, buf ) );
    }
#endif

#if defined(POLARSSL_AES_C)
#if defined(POLARSSL_CIPHER_MODE_CBC)
    if( todo.aes_cbc )
    {
        aes_context aes;
        for( keysize = 128; keysize <= 256; keysize += 64 )
        {
            snprintf( title, sizeof( title ), "AES-CBC-%d", keysize );

            memset( buf, 0, sizeof( buf ) );
            memset( tmp, 0, sizeof( tmp ) );
            aes_setkey_enc( &aes, tmp, keysize );

            TIME_AND_TSC( title,
                aes_crypt_cbc( &aes, AES_ENCRYPT, BUFSIZE, tmp, buf, buf ) );
        }
    }
#endif
#if defined(POLARSSL_GCM_C)
    if( todo.aes_gcm )
    {
        gcm_context gcm;
        for( keysize = 128; keysize <= 256; keysize += 64 )
        {
            snprintf( title, sizeof( title ), "AES-GCM-%d", keysize );

            memset( buf, 0, sizeof( buf ) );
            memset( tmp, 0, sizeof( tmp ) );
            gcm_init( &gcm, POLARSSL_CIPHER_ID_AES, tmp, keysize );

            TIME_AND_TSC( title,
                    gcm_crypt_and_tag( &gcm, GCM_ENCRYPT, BUFSIZE, tmp,
                        12, NULL, 0, buf, buf, 16, tmp ) );

            gcm_free( &gcm );
        }
    }
#endif
#endif

#if defined(POLARSSL_CAMELLIA_C) && defined(POLARSSL_CIPHER_MODE_CBC)
    if( todo.camellia )
    {
        camellia_context camellia;
        for( keysize = 128; keysize <= 256; keysize += 64 )
        {
            snprintf( title, sizeof( title ), "CAMELLIA-CBC-%d", keysize );

            memset( buf, 0, sizeof( buf ) );
            memset( tmp, 0, sizeof( tmp ) );
            camellia_setkey_enc( &camellia, tmp, keysize );

            TIME_AND_TSC( title,
                    camellia_crypt_cbc( &camellia, CAMELLIA_ENCRYPT,
                        BUFSIZE, tmp, buf, buf ) );
        }
    }
#endif

#if defined(POLARSSL_BLOWFISH_C) && defined(POLARSSL_CIPHER_MODE_CBC)
    if( todo.blowfish )
    {
        blowfish_context blowfish;
        for( keysize = 128; keysize <= 256; keysize += 64 )
        {
            snprintf( title, sizeof( title ), "BLOWFISH-CBC-%d", keysize );

            memset( buf, 0, sizeof( buf ) );
            memset( tmp, 0, sizeof( tmp ) );
            blowfish_setkey( &blowfish, tmp, keysize );

            TIME_AND_TSC( title,
                    blowfish_crypt_cbc( &blowfish, BLOWFISH_ENCRYPT, BUFSIZE,
                        tmp, buf, buf ) );
        }
    }
#endif

#if defined(POLARSSL_HAVEGE_C)
    if( todo.havege )
    {
        havege_state hs;
        havege_init( &hs );
        TIME_AND_TSC( "HAVEGE", havege_random( &hs, buf, BUFSIZE ) );
    }
#endif

#if defined(POLARSSL_CTR_DRBG_C)
    if( todo.ctr_drbg )
    {
        ctr_drbg_context ctr_drbg;

        if( ctr_drbg_init( &ctr_drbg, myrand, NULL, NULL, 0 ) != 0 )
            exit(1);
        TIME_AND_TSC( "CTR_DRBG (NOPR)",
                if( ctr_drbg_random( &ctr_drbg, buf, BUFSIZE ) != 0 )
                exit(1) );

        if( ctr_drbg_init( &ctr_drbg, myrand, NULL, NULL, 0 ) != 0 )
            exit(1);
        ctr_drbg_set_prediction_resistance( &ctr_drbg, CTR_DRBG_PR_ON );
        TIME_AND_TSC( "CTR_DRBG (PR)",
                if( ctr_drbg_random( &ctr_drbg, buf, BUFSIZE ) != 0 )
                exit(1) );
    }