Ejemplo n.º 1
0
/** Test base32 decoding. */
static void
test_crypto_base32_decode(void)
{
  char plain[60], encoded[96 + 1], decoded[60];
  int res;
  crypto_rand(plain, 60);
  /* Encode and decode a random string. */
  base32_encode(encoded, 96 + 1, plain, 60);
  res = base32_decode(decoded, 60, encoded, 96);
  test_eq(res, 0);
  test_memeq(plain, decoded, 60);
  /* Encode, uppercase, and decode a random string. */
  base32_encode(encoded, 96 + 1, plain, 60);
  tor_strupper(encoded);
  res = base32_decode(decoded, 60, encoded, 96);
  test_eq(res, 0);
  test_memeq(plain, decoded, 60);
  /* Change encoded string and decode. */
  if (encoded[0] == 'A' || encoded[0] == 'a')
    encoded[0] = 'B';
  else
    encoded[0] = 'A';
  res = base32_decode(decoded, 60, encoded, 96);
  test_eq(res, 0);
  test_memneq(plain, decoded, 60);
  /* Bad encodings. */
  encoded[0] = '!';
  res = base32_decode(decoded, 60, encoded, 96);
  test_assert(res < 0);

 done:
  ;
}
Ejemplo n.º 2
0
Archivo: vars.c Proyecto: srijan/ncdc
static char *i_cid_pid() {
  if(db_vars_get(0, "cid") && db_vars_get(0, "pid"))
    return NULL;

  guint64 r = rand_64();

  struct tiger_ctx t;
  char pid[24];
  tiger_init(&t);
  tiger_update(&t, (char *)&r, 8);
  tiger_final(&t, pid);

  // now hash the PID so we have our CID
  char cid[24];
  tiger_init(&t);
  tiger_update(&t, pid, 24);
  tiger_final(&t, cid);

  // encode and save
  char enc[40] = {};
  base32_encode(pid, enc);
  db_vars_set(0, "pid", enc);
  base32_encode(cid, enc);
  db_vars_set(0, "cid", enc);

  return NULL;
}
Ejemplo n.º 3
0
enum nssync_error
nssync_crypto_synckey_encode(const uint8_t *key, char **key_out)
{
	char *genkey;
	char key32[BASE32_SYNCKEY_LENGTH + 1];
	int key32idx = 0;
	size_t buflen = sizeof(key32);
	int keyidx = 0;
	int idx;

	base32_encode((uint8_t*)key32, &buflen, key, SYNCKEY_LENGTH);

	genkey = malloc(ENCODED_SYNCKEY_LENGTH + 1); /* allow for zero pad */
	if (genkey == NULL) {
		return NSSYNC_ERROR_NOMEM;
	}

	genkey[keyidx++] = tofriendly(key32[key32idx++]);
	while (keyidx < ENCODED_SYNCKEY_LENGTH) {
		genkey[keyidx++] = '-';
		for (idx=0; idx < 5; idx++) {
			genkey[keyidx++] = tofriendly(key32[key32idx++]);
		}
	}
	genkey[keyidx++] = 0;

	*key_out = genkey;

	return NSSYNC_ERROR_OK;
}
Ejemplo n.º 4
0
int
main(int argc, char **argv) {
  uint8_t a[128];
  unsigned alen = sizeof(a);

  if (!base32_encode(a, &alen, (unsigned char *) argv[1], strlen(argv[1]))) {
    perror("encode");
    return 1;
  }

  write(1, a, alen);
  write(1, "\n", 1);

  uint8_t b[128];
  unsigned blen = sizeof(b);

  if (!base32_decode(b, &blen, a, alen, 0)) {
    perror("decode");
    return 1;
  }

  write(1, b, blen);
  write(1, "\n", 1);

  return 0;
}
Ejemplo n.º 5
0
static chunk_t *
b32_enc(const chunk_t *inp)
{
  chunk_t *ch = chunk_new(base32_encoded_size(inp->len));
  base32_encode((char *)ch->buf, ch->len, (char*)inp->buf, inp->len);
  ch->len = strlen((char *) ch->buf);
  return ch;
}
Ejemplo n.º 6
0
/** Return a filename with a random suffix, relative to our testing temporary
 * directory. If name is NULL, return the name of the testing temporary
 * directory, without any suffix. */
const char *
get_fname_rnd(const char *name)
{
  char rnd[256], rnd32[256];
  crypto_rand(rnd, RAND_PATH_BYTES);
  base32_encode(rnd32, sizeof(rnd32), rnd, RAND_PATH_BYTES);
  return get_fname_suffix(name, rnd32);
}
Ejemplo n.º 7
0
// these all create a new hashname
hashname_t hashname_str(char *str)
{
  hashname_t hn;
  if(!hashname_valid(str)) return NULL;
  hn = hashname_new(NULL);
  base32_decode(str,52,hn->bin,32);
  base32_encode(hn->bin,32,hn->hashname,53);
  return hn;
}
Ejemplo n.º 8
0
static void test_base32_encode(void)
{
	static const char *input[] = {
		"toedeledokie!!",
		"bye bye world",
		"hoeveel onzin kun je testen?????",
		"c'est pas vrai! ",
		"dit is het einde van deze test"
	};
	static const char *output[] = {
		"ORXWKZDFNRSWI33LNFSSCII=",
		"MJ4WKIDCPFSSA53POJWGI===",
		"NBXWK5TFMVWCA33OPJUW4IDLOVXCA2TFEB2GK43UMVXD6PZ7H47Q====",
		"MMTWK43UEBYGC4ZAOZZGC2JBEA======",
		"MRUXIIDJOMQGQZLUEBSWS3TEMUQHMYLOEBSGK6TFEB2GK43U"
	};
	string_t *str;
	unsigned int i;

	test_begin("base32_encode() with padding");
	str = t_str_new(256);
	for (i = 0; i < N_ELEMENTS(input); i++) {
		str_truncate(str, 0);
		base32_encode(TRUE, input[i], strlen(input[i]), str);
		test_assert(strcmp(output[i], str_c(str)) == 0);
	}
	test_end();

	test_begin("base32_encode() no padding");
	str = t_str_new(256);
	for (i = 0; i < N_ELEMENTS(input); i++) {
		const char *p = strchr(output[i], '=');
		size_t len;

		if (p == NULL)
			len = strlen(output[i]);
		else
			len = (size_t)(p - output[i]);
		str_truncate(str, 0);
		base32_encode(FALSE, input[i], strlen(input[i]), str);
		test_assert(strncmp(output[i], str_c(str), len) == 0);
	}
	test_end();
}
Ejemplo n.º 9
0
static void
test_util_format_base32_encode(void *arg)
{
  (void) arg;
  size_t real_dstlen = 32;
  char *dst = tor_malloc_zero(real_dstlen);

  /* Basic use case that doesn't require a source length correction. */
  {
    /* Length of 10 bytes. */
    const char *src = "blahbleh12";
    size_t srclen = strlen(src);
    /* Expected result encoded base32. This was created using python as
     * such (and same goes for all test case.):
     *
     *  b = bytes("blahbleh12", 'utf-8')
     *  base64.b32encode(b)
     *  (result in lower case)
     */
    const char *expected = "mjwgc2dcnrswqmjs";

    base32_encode(dst, base32_encoded_size(srclen), src, srclen);
    tt_mem_op(expected, OP_EQ, dst, strlen(expected));
    /* Encode but to a larger size destination. */
    memset(dst, 0, real_dstlen);
    base32_encode(dst, real_dstlen, src, srclen);
    tt_mem_op(expected, OP_EQ, dst, strlen(expected));
  }

  /* Non multiple of 5 for the source buffer length. */
  {
    /* Length of 8 bytes. */
    const char *expected = "mjwgc2dcnrswq";
    const char *src = "blahbleh";
    size_t srclen = strlen(src);

    memset(dst, 0, real_dstlen);
    base32_encode(dst, base32_encoded_size(srclen), src, srclen);
    tt_mem_op(expected, OP_EQ, dst, strlen(expected));
  }

 done:
  tor_free(dst);
}
Ejemplo n.º 10
0
Archivo: ext.c Proyecto: Windol/tuns
/*
 * call-seq:
 *   Base32.encode(string) -> encoded_string
 *
 * Encodes a string in base32.
 */
static VALUE
b32_encode (VALUE self, VALUE value)
{
  value = StringValue(value);

  VALUE result = rb_str_new (0, base32_encoder_buffer_size (RSTRING (value)->len));
  base32_encode ((uint8_t *) RSTRING (result)->ptr, RSTRING (result)->len,
                 (uint8_t *) RSTRING (value)->ptr, RSTRING (value)->len);

  return result;
}
Ejemplo n.º 11
0
// bin must be 32 bytes
hashname_t hashname_new(uint8_t *bin)
{
  hashname_t hn;
  if(!(hn = malloc(sizeof (struct hashname_struct)))) return NULL;
  memset(hn,0,sizeof (struct hashname_struct));
  if(bin)
  {
    memcpy(hn->bin, bin, 32);
    base32_encode(hn->bin,32,hn->hashname,53);
  }
  return hn;
}
Ejemplo n.º 12
0
Archivo: auth.c Proyecto: Nyogtha/uhub
/*
 * This will generate the same challenge to the same user, always.
 * The challenge is made up of the time of the user connected
 * seconds since the unix epoch (modulus 1 million)
 * and the SID of the user (0-1 million).
 */
const char* acl_password_generate_challenge(struct hub_info* hub, struct hub_user* user)
{
	char buf[64];
	uint64_t tiger_res[3];
	static char tiger_buf[MAX_CID_LEN+1];

	// FIXME: Generate a better nonce scheme.
	snprintf(buf, 64, "%p%d%d", user, (int) user->id.sid, (int) net_con_get_sd(user->connection));

	tiger((uint64_t*) buf, strlen(buf), (uint64_t*) tiger_res);
	base32_encode((unsigned char*) tiger_res, TIGERSIZE, tiger_buf);
	tiger_buf[MAX_CID_LEN] = 0;
	return (const char*) tiger_buf;
}
Ejemplo n.º 13
0
static void adc_cid_pid(struct ADC_client* client)
{
	ADC_TRACE;
	char seed[64];
	char pid[64];
	char cid[64];
	uint64_t tiger_res1[3];
	uint64_t tiger_res2[3];

	/* create cid+pid pair */
	memset(seed, 0, 64);
	snprintf(seed, 64, VERSION "%p", client);

	tiger((uint64_t*) seed, strlen(seed), tiger_res1);
	base32_encode((unsigned char*) tiger_res1, TIGERSIZE, pid);
	tiger((uint64_t*) tiger_res1, TIGERSIZE, tiger_res2);
	base32_encode((unsigned char*) tiger_res2, TIGERSIZE, cid);
	cid[ADC_CID_SIZE] = 0;
	pid[ADC_CID_SIZE] = 0;

	adc_msg_add_named_argument(client->info, ADC_INF_FLAG_PRIVATE_ID, pid);
	adc_msg_add_named_argument(client->info, ADC_INF_FLAG_CLIENT_ID, cid);
}
Ejemplo n.º 14
0
int module_hash_encode (MAYBE_UNUSED const hashconfig_t *hashconfig, MAYBE_UNUSED const void *digest_buf, MAYBE_UNUSED const salt_t *salt, MAYBE_UNUSED const void *esalt_buf, MAYBE_UNUSED const void *hook_salt_buf, MAYBE_UNUSED const hashinfo_t *hash_info, char *line_buf, MAYBE_UNUSED const int line_size)
{
  const u32 *digest = (const u32 *) digest_buf;

  u32 tmp[5];

  tmp[0] = byte_swap_32 (digest[0]);
  tmp[1] = byte_swap_32 (digest[1]);
  tmp[2] = byte_swap_32 (digest[2]);
  tmp[3] = byte_swap_32 (digest[3]);
  tmp[4] = byte_swap_32 (digest[4]);

  char digest_buf_c[34];

  base32_encode (int_to_itoa32, (const u8 *) tmp, 20, (u8 *) digest_buf_c);

  digest_buf_c[32] = 0;

  // domain

  const u32 salt_pc_len = salt->salt_len_pc;

  char domain_buf_c[33] = { 0 };

  memcpy (domain_buf_c, (char *) salt->salt_buf_pc, salt_pc_len);

  for (u32 i = 0; i < salt_pc_len; i++)
  {
    const char next = domain_buf_c[i];

    domain_buf_c[i] = '.';

    i += next;
  }

  domain_buf_c[salt_pc_len] = 0;

  // final

  char tmp_salt[SALT_MAX * 2];

  const int salt_len = generic_salt_encode (hashconfig, (const u8 *) salt->salt_buf, (const int) salt->salt_len, (u8 *) tmp_salt);

  tmp_salt[salt_len] = 0;

  const int line_len = snprintf (line_buf, line_size, "%s:%s:%s:%u", digest_buf_c, domain_buf_c, tmp_salt, salt->salt_iter);

  return line_len;
}
Ejemplo n.º 15
0
/** Select and create the temporary directory we'll use to run our unit tests.
 * Store it in <b>temp_dir</b>.  Exit immediately if we can't create it.
 * idempotent. */
static void
setup_directory(void)
{
  static int is_setup = 0;
  int r;
  char rnd[256], rnd32[256];
  if (is_setup) return;

/* Due to base32 limitation needs to be a multiple of 5. */
#define RAND_PATH_BYTES 5
  crypto_rand(rnd, RAND_PATH_BYTES);
  base32_encode(rnd32, sizeof(rnd32), rnd, RAND_PATH_BYTES);

#ifdef _WIN32
  {
    char buf[MAX_PATH];
    const char *tmp = buf;
    const char *extra_backslash = "";
    /* If this fails, we're probably screwed anyway */
    if (!GetTempPathA(sizeof(buf),buf))
      tmp = "c:\\windows\\temp\\";
    if (strcmpend(tmp, "\\")) {
      /* According to MSDN, it should be impossible for GetTempPath to give us
       * an answer that doesn't end with \.  But let's make sure. */
      extra_backslash = "\\";
    }
    tor_snprintf(temp_dir, sizeof(temp_dir),
                 "%s%stor_test_%d_%s", tmp, extra_backslash,
                 (int)getpid(), rnd32);
    r = mkdir(temp_dir);
  }
#else
  tor_snprintf(temp_dir, sizeof(temp_dir), "/tmp/tor_test_%d_%s",
               (int) getpid(), rnd32);
  r = mkdir(temp_dir, 0700);
  if (!r) {
    /* undo sticky bit so tests don't get confused. */
    r = chown(temp_dir, getuid(), getgid());
  }
#endif
  if (r) {
    fprintf(stderr, "Can't create directory %s:", temp_dir);
    perror("");
    exit(1);
  }
  is_setup = 1;
  temp_dir_setup_in_pid = getpid();
}
Ejemplo n.º 16
0
static void
test_rend_cache_lookup_entry(void *data)
{
  int ret;
  rend_data_t *mock_rend_query = NULL;
  char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
  rend_cache_entry_t *entry = NULL;
  rend_encoded_v2_service_descriptor_t *desc_holder = NULL;
  char *service_id = NULL;
  (void)data;

  rend_cache_init();

  generate_desc(RECENT_TIME, &desc_holder, &service_id, 3);

  ret = rend_cache_lookup_entry("abababababababab", 0, NULL);
  tt_int_op(ret, OP_EQ, -ENOENT);

  ret = rend_cache_lookup_entry("invalid query", 2, NULL);
  tt_int_op(ret, OP_EQ, -EINVAL);

  ret = rend_cache_lookup_entry("abababababababab", 2, NULL);
  tt_int_op(ret, OP_EQ, -ENOENT);

  ret = rend_cache_lookup_entry("abababababababab", 4224, NULL);
  tt_int_op(ret, OP_EQ, -ENOENT);

  mock_rend_query = mock_rend_data(service_id);
  base32_encode(desc_id_base32, sizeof(desc_id_base32), desc_holder->desc_id,
                DIGEST_LEN);
  rend_cache_store_v2_desc_as_client(desc_holder->desc_str, desc_id_base32,
                                     mock_rend_query, NULL);

  ret = rend_cache_lookup_entry(service_id, 2, NULL);
  tt_int_op(ret, OP_EQ, 0);

  ret = rend_cache_lookup_entry(service_id, 2, &entry);
  tt_int_op(ret, OP_EQ, 0);
  tt_assert(entry);
  tt_int_op(entry->len, OP_EQ, strlen(desc_holder->desc_str));
  tt_str_op(entry->desc, OP_EQ, desc_holder->desc_str);

 done:
  rend_encoded_v2_service_descriptor_free(desc_holder);
  tor_free(service_id);
  rend_cache_free_all();
  rend_data_free(mock_rend_query);
}
Ejemplo n.º 17
0
Archivo: inf.c Proyecto: leejb521/uhub
static int check_hash_tiger(const char* cid, const char* pid)
{
	char x_pid[64];
	char raw_pid[64];
	uint64_t tiger_res[3];

	memset(x_pid, 0, MAX_CID_LEN+1);

	base32_decode(pid, (unsigned char*) raw_pid, MAX_CID_LEN);
	tiger((uint64_t*) raw_pid, TIGERSIZE, (uint64_t*) tiger_res);
	base32_encode((unsigned char*) tiger_res, TIGERSIZE, x_pid);
	x_pid[MAX_CID_LEN] = 0;
	if (strncasecmp(x_pid, cid, MAX_CID_LEN) == 0)
		return 1;
	return 0;
}
Ejemplo n.º 18
0
char* tth(const char* filename, char **tthl, size_t *tthl_len)
{
    char *tth = NULL;
    size_t numbytes;
    unsigned char root[24];
    unsigned char *cur;
    TT_CONTEXT tt;
    unsigned char buf[1 + 256 * BLOCKSIZE];
    struct stat sb;
    unsigned level;
    size_t leaf_blocksize;

    int fd = open(filename, O_RDONLY);
    if ((fd == -1) || ( fstat(fd, &sb) == -1)) {
        return NULL;
    }

    level = calc_block_level(sb.st_size, max_block_count);
    leaf_blocksize = 1 << (level+10);

    *tthl_len = 0;
    *tthl = NULL;

    tt_init(&tt, *tthl, level);
    tt.leaf = buf;
    buf[0] = '\0';

    while ( (numbytes = read(fd, &buf[1], sizeof(buf) - 1) ) > 0) {
        tt.index = BLOCKSIZE;
        for (cur = &buf[1]; cur + BLOCKSIZE <= &buf[numbytes + 1]; cur += BLOCKSIZE) {
            tt.leaf = cur - 1;
            tt.leaf[0] = '\0';
            tt_block(&tt);
        }
        tt.index = numbytes - (cur - &buf[1]);
        tt.leaf = cur - 1;
        tt.leaf[0] = '\0';
    }

    close(fd);

    tt_digest(&tt, root);

    tth = base32_encode(root, sizeof(root));

    return tth;
}
Ejemplo n.º 19
0
static void 
handle_ggep_h(const char *data, size_t size)
{
  static const struct {
    const char * const prefix;
    const uint8_t base;
  } hashes[] = {
    { NULL, 0 },
    { "urn:sha1:", 32 },
    { "urn:bitprint:", 32 },
    { "urn:md5:", 64 },
    { "urn:uuid:", 16 },
    { "urn:md4:", 64 },
  };
  unsigned char h;
  const char *prefix;
  uint8_t base;

  if (size < 1) {
    printf(" <No payload>");
    return;
  }
  
  h = data[0];
  if (h < ARRAY_LEN(hashes)) {
    prefix = hashes[h].prefix;
    base = hashes[h].base;
  } else {
    prefix = NULL;
    base = 0;
  }

  if (prefix && base) {
    printf(": %s", prefix);

    if (32 == base) {
      char base32[256];
      size_t base32_len;

      base32_len = base32_encode(base32, sizeof base32, &data[1], size - 1);
      base32[base32_len] = '\0';
      printf("%s", base32);
    }
  } else {
    printf(": <%u> \"%s\"", h, escape_buffer(&data[1], size - 1));
  }
}
Ejemplo n.º 20
0
static void
test_rend_cache_lookup_v2_desc_as_dir(void *data)
{
  int ret;
  char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
  rend_encoded_v2_service_descriptor_t *desc_holder = NULL;
  char *service_id = NULL;
  const char *ret_desc = NULL;

  (void)data;

  NS_MOCK(router_get_my_routerinfo);
  NS_MOCK(hid_serv_responsible_for_desc_id);

  rend_cache_init();

  // Test invalid base32
  ret = rend_cache_lookup_v2_desc_as_dir("!bababababababab", NULL);
  tt_int_op(ret, OP_EQ, -1);

  // Test non-existent descriptor but well formed
  ret = rend_cache_lookup_v2_desc_as_dir("3xqunszqnaolrrfmtzgaki7mxelgvkje",
                                         NULL);
  tt_int_op(ret, OP_EQ, 0);

  // Test existing descriptor
  hid_serv_responsible_for_desc_id_response = 1;
  generate_desc(RECENT_TIME, &desc_holder, &service_id, 3);
  rend_cache_store_v2_desc_as_dir(desc_holder->desc_str);
  base32_encode(desc_id_base32, sizeof(desc_id_base32), desc_holder->desc_id,
                DIGEST_LEN);
  ret = rend_cache_lookup_v2_desc_as_dir(desc_id_base32, &ret_desc);
  tt_int_op(ret, OP_EQ, 1);
  tt_assert(ret_desc);

 done:
  NS_UNMOCK(router_get_my_routerinfo);
  NS_UNMOCK(hid_serv_responsible_for_desc_id);
  tor_free(mock_routerinfo);
  rend_cache_free_all();
  rend_encoded_v2_service_descriptor_free(desc_holder);
  tor_free(service_id);
}
Ejemplo n.º 21
0
static G_GNUC_COLD void
tt_check_digest(const char * const expected, const void *data, size_t size)
{
	char digest[TTH_BASE32_SIZE + 1];
	struct tth hash;
	TTH_CONTEXT ctx;

	tt_init(&ctx, size);
	tt_update(&ctx, data, size);
	tt_digest(&ctx, &hash);

	ZERO(&digest);
	base32_encode(digest, sizeof digest, hash.data, sizeof hash.data);
	digest[G_N_ELEMENTS(digest) - 1] = '\0';

	if (0 != strcmp(expected, digest)) {
		g_warning("tt_check_digest:\nExpected: \"%s\"\nGot:      \"%s\"",
			expected, digest);
		g_error("Tigertree implementation is defective.");
	}
}
Ejemplo n.º 22
0
Archivo: auth.c Proyecto: Nyogtha/uhub
int acl_password_verify(struct hub_info* hub, struct hub_user* user, const char* password)
{
	char buf[1024];
	struct auth_info* access;
	const char* challenge;
	char raw_challenge[64];
	char password_calc[64];
	uint64_t tiger_res[3];
	size_t password_len;

	if (!password || !user || strlen(password) != MAX_CID_LEN)
		return 0;

	access = acl_get_access_info(hub, user->id.nick);
	if (!access)
		return 0;

	challenge = acl_password_generate_challenge(hub, user);

	base32_decode(challenge, (unsigned char*) raw_challenge, MAX_CID_LEN);

	password_len = strlen(access->password);
	
	memcpy(&buf[0], access->password, password_len);
	memcpy(&buf[password_len], raw_challenge, TIGERSIZE);
	
	tiger((uint64_t*) buf, TIGERSIZE+password_len, (uint64_t*) tiger_res);
	base32_encode((unsigned char*) tiger_res, TIGERSIZE, password_calc);
	password_calc[MAX_CID_LEN] = 0;

#ifdef PLUGIN_SUPPORT
	hub_free(access);
#endif

	if (strcasecmp(password, password_calc) == 0)
	{
		return 1;
	}
	return 0;
}
Ejemplo n.º 23
0
static void test_base32_random(void)
{
	string_t *str, *dest;
	char buf[10];
	unsigned int i, j, max;

	str = t_str_new(256);
	dest = t_str_new(256);

	test_begin("padded base32 encode/decode with random input");
	for (i = 0; i < 1000; i++) {
		max = rand() % sizeof(buf);
		for (j = 0; j < max; j++)
			buf[j] = rand();

		str_truncate(str, 0);
		str_truncate(dest, 0);
		base32_encode(TRUE, buf, max, str);
		test_assert(base32_decode(str_data(str), str_len(str), NULL, dest) >= 0);
		test_assert(str_len(dest) == max &&
			    memcmp(buf, str_data(dest), max) == 0);
	}
	test_end();

	test_begin("padded base32hex encode/decode with random input");
	for (i = 0; i < 1000; i++) {
		max = rand() % sizeof(buf);
		for (j = 0; j < max; j++)
			buf[j] = rand();

		str_truncate(str, 0);
		str_truncate(dest, 0);
		base32hex_encode(TRUE, buf, max, str);
		test_assert(base32hex_decode(str_data(str), str_len(str), NULL, dest) >= 0);
		test_assert(str_len(dest) == max &&
			    memcmp(buf, str_data(dest), max) == 0);
	}
	test_end();
}
Ejemplo n.º 24
0
/** create a username from an account name
 *
 * The requirements for username are not explained anywhere except
 * except in the source code at
 * https://hg.mozilla.org/mozilla-central/file/2cfff9240e9a/services/sync/modules/identity.js#l422
 *
 */
static char *moz_sync_username_from_accountname(const char *accountname)
{
	char *username;
	SHA_CTX context;
	uint8_t digest[20];
	size_t bufflen = 80;

	if (isvalidusername(accountname)) {
		return strduptolower(accountname);
	}

	SHA1_Init(&context);
	SHA1_Update(&context, accountname, strlen(accountname));
	SHA1_Final(digest, &context);

	username = calloc(1, bufflen);
	if (username != NULL) {
		base32_encode((uint8_t*)username, &bufflen, digest, sizeof(digest));
	}

	return username;
}
Ejemplo n.º 25
0
void calculateAddress(const uint8_t* data, size_t size, char* nemAddress)
{
	unsigned char sha3result[32];

	Keccak_HashInstance _hctx, *hctx = &_hctx;
	Keccak_HashInitialize_SHA3_256(hctx);
	Keccak_HashUpdate(hctx, data, size * 8);
	Keccak_HashSqueeze(hctx, sha3result, 256);

	unsigned char r160result[25];
	computeRIPEMD160(sha3result, 32, r160result + 1);
	r160result[0] = 0x68;

	Keccak_HashInitialize_SHA3_256(hctx);
	Keccak_HashUpdate(hctx, r160result, 21 * 8);
	Keccak_HashSqueeze(hctx, sha3result, 256);

	*(uint32_t*)(r160result + 21) = *(uint32_t*)(sha3result);

	base32_encode(r160result, 25, (unsigned char*)nemAddress);
	nemAddress[40] = 0;
}
Ejemplo n.º 26
0
static void
print_key(FILE *fp, const unsigned char *key, u_int len, int base32)
{
    unsigned char *buf;
    u_int buflen;
    int i;

    if (base32) {
        buflen = ((len + 4) / 5) * 8;
        if ((buf = malloc(buflen + 1)) == NULL)
            err(1, "malloc");
        buf[buflen] = 0;
        base32_encode(key, len, buf);
        assert(buf[buflen] == 0 && (buflen == 0 || buf[buflen - 1] != 0));
        for (i = 0; i < buflen; i++)
            fputc(buf[i], fp);
        free(buf);
    } else {
        for (i = 0; i < len; i++)
            fprintf(fp, "%02x", key[i] & 0xff);
    }
}
Ejemplo n.º 27
0
static void build_base32_hostname(char *buf, size_t buf_size, char *file_name) {
    unsigned int plain_size, label_count;
    char *local_buf = malloc(buf_size); char *tmp = local_buf;

    assert(local_buf);

    dprintf("Buf_size = %d\n", (int) buf_size);

    //buffer can take buf_size hostname. how much filename fits in there after base32 conversion?
    plain_size = ceil( ((double)buf_size - 1) / 8) * 5 ;
    dprintf("base32 should take %d bytes\n", plain_size);

    //include space for DNS label separators '.'
    plain_size -= plain_size / MAX_LABEL_LEN; 
    dprintf("Number of dots: %d\n", plain_size / MAX_LABEL_LEN);

    //shrink the filename until it fits into the free space
    while (strlen(file_name) > plain_size)
        file_name++;

    base32_encode(local_buf, &buf_size, file_name, strlen(file_name));
    dprintf("Expected %d bytes from base32 and dot insertion. Filename length is %d back\n", plain_size, (int) strlen(file_name));

    label_count = 0;
    while (tmp < local_buf + strlen(local_buf) && buf < buf+buf_size){
        *buf = *tmp;
        if (++label_count > MAX_LABEL_LEN) {
           buf++;
           *buf = '.';
           label_count = 0;
        }
        buf++;
        tmp++;
    }

    free(local_buf);
}
Ejemplo n.º 28
0
Archivo: test.c Proyecto: evoskuil/tor
/** Select and create the temporary directory we'll use to run our unit tests.
 * Store it in <b>temp_dir</b>.  Exit immediately if we can't create it.
 * idempotent. */
static void
setup_directory(void)
{
  static int is_setup = 0;
  int r;
  char rnd[256], rnd32[256];
  if (is_setup) return;

/* Due to base32 limitation needs to be a multiple of 5. */
#define RAND_PATH_BYTES 5
  crypto_rand(rnd, RAND_PATH_BYTES);
  base32_encode(rnd32, sizeof(rnd32), rnd, RAND_PATH_BYTES);

#ifdef _WIN32
  {
    char buf[MAX_PATH];
    const char *tmp = buf;
    /* If this fails, we're probably screwed anyway */
    if (!GetTempPathA(sizeof(buf),buf))
      tmp = "c:\\windows\\temp";
    tor_snprintf(temp_dir, sizeof(temp_dir),
                 "%s\\tor_test_%d_%s", tmp, (int)getpid(), rnd32);
    r = mkdir(temp_dir);
  }
#else
  tor_snprintf(temp_dir, sizeof(temp_dir), "/tmp/tor_test_%d_%s",
               (int) getpid(), rnd32);
  r = mkdir(temp_dir, 0700);
#endif
  if (r) {
    fprintf(stderr, "Can't create directory %s:", temp_dir);
    perror("");
    exit(1);
  }
  is_setup = 1;
  temp_dir_setup_in_pid = getpid();
}
Ejemplo n.º 29
0
int main(int argc, char **argv)
{
    const char *str = " *"
                      "* Copyright 2005 Martin Hedenfalk <*****@*****.**>"
                      "*"
                      "* This file is part of ShakesPeer."
                      "*"
                      "* ShakesPeer is free software; you can redistribute it and/or modify"
                      "* it under the terms of the GNU General Public License as published by"
                      "* the Free Software Foundation; either version 2 of the License, or"
                      "* (at your option) any later version."
                      "*"
                      "* ShakesPeer is distributed in the hope that it will be useful,"
                      "* but WITHOUT ANY WARRANTY; without even the implied warranty of"
                      "* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the"
                      "* GNU General Public License for more details."
                      "*"
                      "* You should have received a copy of the GNU General Public License"
                      "* along with ShakesPeer; if not, wite to the Free Software"
                      "* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA"
                      "*/";
    char *tmp = base32_encode(str, strlen(str));

    char *data = base32_decode(tmp, NULL);

    fail_unless(memcmp(data, str, base32_decode_length(strlen(tmp))) == 0);

    const char *b = "RF354FEUIXRYFO4O372SXJLKJDIQ2XKIO3XU37OPKEOUEQ7OACWYRFLWDZU5E2QEMESWOS56BIL65HRBFQJHPF4HGWFD6F4E5EJWSA5NZYSHJJP6UZXPUTA5DGOIRIBJILKE65QPP6WBB3I54JRPHUG3XH6NRQTCTLHWAL73NAQ2BCBPKBL3FCZPCAWYNZ7ZN3OHFX2FOZ277IPPLBEZCP6SHDTKJ3CP6SUF2Q6PGZOBFDRFKOX6ERXQADLK6RH4BCOAVRBRQ3S4BTZWLQJI4JKTV7REN4AA22XUJ7AITQFMIMMG4XAA";
    unsigned outlen = 0;
    void *data2 = base32_decode(b, &outlen);
    fail_unless(data2);
    fail_unless(outlen % 24 == 0);
    fail_unless(outlen == 192);

    return 0;
}
Ejemplo n.º 30
0
/**
 * Runs some test cases to check whether the implementation of the tiger
 * hash algorithm is alright.
 */
G_GNUC_COLD void
tiger_check(void)
{
	static const char zeros[1025];
    static const struct {
		const char *r;
		const char *s;
		size_t len;
	} tests[] = {
		{ "QMLU34VTTAIWJQM5RVN4RIQKRM2JWIFZQFDYY3Y", "\0" "1", 2 },
		{ "LWPNACQDBZRYXW3VHJVCJ64QBZNGHOHHHZWCLNQ", zeros, 1 },
		{ "VK54ZIEEVTWNAUI5D5RDFIL37LX2IQNSTAXFKSA", zeros, 2 },
		{ "KIU5YUNESS4RH6HAJRGHFHETZOFSMDFE52HKTVY", zeros, 8 },
		{ "Z5PUAX6MEZB6EWYXFCSLMMUMZEFIQPOEWX3BA6Q", zeros, 255 },
		{ "D6UXHPOSAGHITCD4VVRHJQ4PCKIWY2WEHPJOUWY", zeros, 1024 },
		{ "CMKDYROZKSC6VTM4I7LSMMHPAE4UG3FXPXZGGKY", zeros, sizeof zeros },
	};
	guint i;

	for (i = 0; i < G_N_ELEMENTS(tests); i++) {
		char hash[24];
		char buf[40];
		gboolean ok;

		ZERO(&buf);
		tiger(tests[i].s, tests[i].len, hash);
		base32_encode(buf, sizeof buf, hash, sizeof hash);
		buf[G_N_ELEMENTS(buf) - 1] = '\0';

		ok = 0 == strcmp(tests[i].r, buf);
		if (!ok) {
			g_warning("i=%u, buf=\"%s\"", i, buf);
			g_assert_not_reached();
		}
	}
}