Esempio n. 1
0
File: main.cpp Progetto: Sopamo/m2p
int main(int argc, const char * argv[]) {
    
    // Init sodium (currently not in use)
    sodium_init();
    if(sodium_init()) {
        std::cout << "Starting to encode ...\n";
        encode(argv[1], argv[2]);
        std::cout << "Starting to decode ...\n";
        decode(argv[2]);
    }
    
    return 0;
}
Esempio n. 2
0
int
main(void)
{
    sodium_set_misuse_handler(NULL);
    sodium_set_misuse_handler(misuse_handler);
    sodium_set_misuse_handler(NULL);

    assert(sodium_init() == 1);

    (void) sodium_runtime_has_neon();
    (void) sodium_runtime_has_sse2();
    (void) sodium_runtime_has_sse3();
    (void) sodium_runtime_has_ssse3();
    (void) sodium_runtime_has_sse41();
    (void) sodium_runtime_has_pclmul();
    (void) sodium_runtime_has_aesni();

    sodium_set_misuse_handler(misuse_handler);
#ifndef __EMSCRIPTEN__
    sodium_misuse();
    printf("Misuse handler returned\n");
#else
    printf("misuse_handler()\n");
#endif

    return 0;
}
Esempio n. 3
0
//02 002
void config_encryption(const char *password, const char *method) {
    SSLeay_add_all_algorithms();
    sodium_init();
    _method = encryption_method_from_string(method);
    if (_method == ENCRYPTION_TABLE) {
        get_table((unsigned char *) password);
        cipher = CIPHER_TABLE;
    } else if (_method == ENCRYPTION_SALSA20 || _method == ENCRYPTION_CHACHA20) {
        cipher = CIPHER_SODIUM;
        _key_len = 32;
        unsigned char tmp[EVP_MAX_IV_LENGTH];;
        EVP_BytesToKey(EVP_aes_256_cfb(), EVP_md5(), NULL, (unsigned char *)password,
                                strlen(password), 1, _key, tmp);
        shadowsocks_key = _key;
    } else {
        cipher = CIPHER_OPENSSL;
        const char *name = shadowsocks_encryption_names[_method];
        if (_method == ENCRYPTION_RC4_MD5) {
            name = "RC4";
        }
        _cipher = EVP_get_cipherbyname(name);
        if (_cipher == NULL) {
//            assert(0);
            // TODO
            printf("_cipher is nil! \r\nThe %s doesn't supported!\r\n please chose anthor!",name);
        } else {
            unsigned char tmp[EVP_MAX_IV_LENGTH];
            _key_len = EVP_BytesToKey(_cipher, EVP_md5(), NULL, (unsigned char *)password,
                                      strlen(password), 1, _key, tmp);
            shadowsocks_key = _key;
        }

//        printf("%d\n", _key_len);
    }
}
Esempio n. 4
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;
}
Esempio n. 5
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);
}
Esempio n. 6
0
int crypto_init() {
  if (-1 == sodium_init())
    return 1;
  randombytes_set_implementation(&randombytes_salsa20_implementation);
  randombytes_stir();
  return 0;
}
Esempio n. 7
0
int main() {
  char *pw =ucmalloc(8);
  char *pw2 =ucmalloc(8);
  char *o = ucmalloc(8);
  char *m = ucmalloc(8);
  strcpy(pw, "xxxx");
  strcpy(pw2, "xxxx");
  strcpy(o, "xxxx");
  strcpy(m, "xxxx");

  if(sodium_init() == -1) return 1;
  PCPCTX *ptx = ptx_new();
  pcp_key_t *k = pcpkey_new ();

  memcpy(k->owner, o, 8);
  memcpy(k->mail, m, 8);

  pcp_key_t *key = pcpkey_encrypt(ptx, k, pw);

  int i;
  for(i=0; i<3; i++)
    mkinvalid_secret(ptx, key, i);

  for(i=0; i<4; i++)
    mkinvalid_public(ptx, key, i);

  mkinvv(ptx, "testvault-invalidheader",  0);
  mkinvv(ptx, "testvault-invalidversion",  1);
  mkinvv(ptx, "testvault-invaliditemsize", 2);
  mkinvv(ptx, "testvault-invaliditemtype",  3);
  mkinvv(ptx, "testvault-invalidkeytype", 4);

  return 0;
}
Esempio n. 8
0
static char * createGUID()
{
  sodium_init();

  unsigned char out[crypto_hash_sha512_BYTES];
  unsigned char sk[crypto_sign_SECRETKEYBYTES];
  int valid_pow = 0;
  while (valid_pow == 0){

    //Generate a key pair
    unsigned char pk[crypto_sign_PUBLICKEYBYTES];
    unsigned char sk[crypto_sign_SECRETKEYBYTES];
    crypto_sign_keypair(pk, sk);

    //Sign the public key
    const unsigned char * message = pk;
    int message_len = crypto_sign_PUBLICKEYBYTES;

    unsigned char signed_message[crypto_sign_BYTES + message_len];
    unsigned long long signed_message_len;

    crypto_sign(signed_message, &signed_message_len,
            message, message_len, sk);

    //Hash the signed key with sha512
    crypto_hash_sha512(out, signed_message, signed_message_len);
    char proof_of_work[32];
    memcpy(proof_of_work, &out[32], 32);
    char * pow = to_hex(proof_of_work, 3);
    valid_pow = test_pow(pow);
  }
  to_hex(sk, 32);
  return to_hex(sk, 32);
}
Esempio n. 9
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);
}
int main(void) {
	sodium_init();

	//create random chain key
	unsigned char chain_key[crypto_auth_BYTES];
	randombytes_buf(chain_key, crypto_auth_BYTES);

	//print first chain key
	printf("Chain key (%i Bytes):\n", crypto_auth_BYTES);
	print_hex(chain_key, crypto_auth_BYTES, 30);
	putchar('\n');

	int status;


	//derive message key from chain key
	unsigned char message_key[crypto_auth_BYTES];
	status = derive_message_key(message_key, chain_key);
	sodium_memzero(chain_key, crypto_auth_BYTES);
	if (status != 0) {
		fprintf(stderr, "ERROR: Failed to derive message key. (%i)\n", status);
		sodium_memzero(message_key, crypto_auth_BYTES);
		return status;
	}

	//print message key
	printf("Message key (%i Bytes):\n", crypto_auth_BYTES);
	print_hex(message_key, crypto_auth_BYTES, 30);
	putchar('\n');

	sodium_memzero(message_key, crypto_auth_BYTES);
	return EXIT_SUCCESS;
}
Esempio n. 11
0
File: ctx.cpp Progetto: 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 ();
}
Esempio n. 12
0
void c_the_program::init_library_sodium() {
	_fact(mo_file_reader::gettext("L_starting_lib_libsodium"));

	if (sodium_init() == -1) {
		_throw_error( std::runtime_error(mo_file_reader::gettext("L_lisodium_init_err")) );
	}
	_info(mo_file_reader::gettext("L_libsodium_ready"));
}
Esempio n. 13
0
int main(void) {
	if (sodium_init() == -1) {
		return -1;
	}

	return_status status = return_status_init();

	//create buffers
	buffer_t *master_key = buffer_create_on_heap(50, 50);
	buffer_t *subkey1 = buffer_create_on_heap(60, 60);
	buffer_t *subkey2 = buffer_create_on_heap(60, 60);
	buffer_t *subkey1_copy = buffer_create_on_heap(60, 60);

	int status_int = 0;
	status_int = buffer_fill_random(master_key, master_key->buffer_length);
	if (status_int != 0) {
		throw(KEYDERIVATION_FAILED, "Failed to generate master key.");
	}
	printf("Master key:\n");
	print_hex(master_key);
	putchar('\n');

	status = derive_key(subkey1, subkey1->buffer_length, master_key, 0);
	throw_on_error(KEYDERIVATION_FAILED, "Failed to derive first subkey.");
	printf("First subkey:\n");
	print_hex(subkey1);
	putchar('\n');

	status = derive_key(subkey2, subkey2->buffer_length, master_key, 1);
	throw_on_error(KEYDERIVATION_FAILED, "Failed to derive the second subkey.");
	printf("Second subkey:\n");
	print_hex(subkey2);
	putchar('\n');

	if (buffer_compare(subkey1, subkey2) == 0) {
		throw(KEYGENERATION_FAILED, "Both subkeys are the same.");
	}

	status = derive_key(subkey1_copy, subkey1_copy->buffer_length, master_key, 0);
	throw_on_error(KEYDERIVATION_FAILED, "Failed to derive copy of the first subkey.");

	if (buffer_compare(subkey1, subkey1_copy) != 0) {
		throw(INCORRECT_DATA, "Failed to reproduce subkey.");
	}

cleanup:
	buffer_destroy_from_heap_and_null_if_valid(master_key);
	buffer_destroy_from_heap_and_null_if_valid(subkey1);
	buffer_destroy_from_heap_and_null_if_valid(subkey2);
	buffer_destroy_from_heap_and_null_if_valid(subkey1_copy);

	on_error {
		print_errors(&status);
	}
	return_status_destroy_errors(&status);

	return status.status;
}
Esempio n. 14
0
int main () {
   unsigned char hash[crypto_generichash_BYTES + 1] = {0};
   unsigned char minhash[crypto_generichash_BYTES_MIN + 1] = {0};
   unsigned char maxhash[crypto_generichash_BYTES_MAX + 1] = {0};
   unsigned char key[crypto_generichash_KEYBYTES] = "123456789 123456789 123456789 12";

   if (sodium_init() != 0) {
      return -1;
   }

   size_t min_hex_maxlen = crypto_generichash_BYTES_MIN * 2 + 1;
   size_t std_hex_maxlen = crypto_generichash_BYTES * 2 + 1;
   size_t max_hex_maxlen = crypto_generichash_BYTES_MAX * 2 + 1;
   unsigned char min_hex[min_hex_maxlen];
   unsigned char std_hex[std_hex_maxlen];
   unsigned char max_hex[max_hex_maxlen];

   printf ("text: %s\n", MESSAGE);
   crypto_generichash(minhash, crypto_generichash_BYTES_MIN,
                      MESSAGE, MESSAGE_LEN,
                      NULL, 0);
   sodium_bin2hex (min_hex, min_hex_maxlen, minhash, crypto_generichash_BYTES_MIN);
   printf ("min hash: %s\n", min_hex);
   printf ("hash length is %d\n", strlen (minhash));

   crypto_generichash(hash, crypto_generichash_BYTES,
                      MESSAGE, MESSAGE_LEN,
                      NULL, 0);
   sodium_bin2hex (std_hex, std_hex_maxlen, hash, crypto_generichash_BYTES);
   printf ("\nstd hash: %s\n", std_hex);
   printf ("hash length is %d\n", strlen (hash));

   crypto_generichash(maxhash, crypto_generichash_BYTES_MAX,
                      MESSAGE, MESSAGE_LEN,
                      NULL, 0);
   sodium_bin2hex (max_hex, max_hex_maxlen, maxhash, crypto_generichash_BYTES_MAX);
   printf ("\nmax hash: %s\n", max_hex);
   printf ("hash length is %d\n", strlen (maxhash));

   crypto_generichash(minhash, crypto_generichash_BYTES_MIN,
                      MESSAGE, MESSAGE_LEN,
                      key, sizeof key);
   sodium_bin2hex (min_hex, min_hex_maxlen, minhash, crypto_generichash_BYTES_MIN);
   printf ("\nkeyed min hash: %s\n", min_hex);

   crypto_generichash(hash, crypto_generichash_BYTES,
                      MESSAGE, MESSAGE_LEN,
                      key, sizeof key);
   sodium_bin2hex (std_hex, std_hex_maxlen, hash, crypto_generichash_BYTES);
   printf ("keyed std hash: %s\n", std_hex);

   crypto_generichash(maxhash, crypto_generichash_BYTES_MAX,
                      MESSAGE, MESSAGE_LEN,
                      key, sizeof key);
   sodium_bin2hex (max_hex, max_hex_maxlen, maxhash, crypto_generichash_BYTES_MAX);
   printf ("keyed max hash: %s\n", max_hex);
   return 0;
}
int main(void) {
	sodium_init();

	//create random key
	unsigned char key[crypto_secretbox_KEYBYTES];
	randombytes_buf(key, crypto_secretbox_KEYBYTES);

	//print key
	printf("Key (%i Bytes):\n", crypto_secretbox_KEYBYTES);
	print_hex(key, crypto_secretbox_KEYBYTES, 30);
	putchar('\n');


	//encrypted message
	unsigned char ciphertext[500]; //TODO don't use fixed size buffer here

	size_t ciphertext_length = 0;
	int status;
	status = encrypt(ciphertext, &ciphertext_length, key);
	if (status != 0) {
		fprintf(stderr, "ERROR: Failed to encrypt message. (%i)\n", status);
		return status;
	}

	//print the ciphertext
	printf("Ciphertext (packet, %zu Bytes):\n", ciphertext_length);
	print_hex(ciphertext, ciphertext_length, 30);
	putchar('\n');

	puts("NOW DECRYPT -------------------------------------------------------------------\n");

	unsigned char header[ciphertext_length];

	size_t header_length = 0;

	status = extract_header_without_verifying(
			header,
			&header_length,
			ciphertext,
			ciphertext_length);
	if (status != 0) {
		fprintf(stderr, "ERROR: Failed to extract header from packet. (%i)\n", status);
		return status;
	}

	//print header
	printf("Received header (%zu Bytes):\n%s\n\n", header_length, header);

	//check header
	if (sodium_memcmp(header, HEADER, sizeof(HEADER)) != 0) {
		fprintf(stderr, "ERROR: Headers aren't the same!\n");
		return -1;
	}

	return EXIT_SUCCESS;
}
Esempio n. 16
0
LUALIB_API int luaopen_sodium (lua_State *L) {
	if (sodium_init() != 0) {
		lua_pushstring(L, "Failed to initialize libsodium.");
		return lua_error(L);
	}

	lua_newtable(L);
	luaL_setfuncs(L, sodiumlib, 0);
	return 1;
}
Esempio n. 17
0
int
crypto_init(const char *password) {
    if (sodium_init() == -1) {
        return 1;
    }

    randombytes_set_implementation(&randombytes_salsa20_implementation);
    randombytes_stir();

    return crypto_generichash(secret_key, sizeof secret_key, (uint8_t*)password, strlen(password), NULL, 0);
}
Esempio n. 18
0
proto_functions_s* __stdcall handshake( host_functions_s *hf )
{
    if (ASSERT(lan_engine::get(false) == nullptr))
    {
        if (sodium_init() == -1)
        {
        }

        lan_engine::create( hf );
    }

    return &funcs;
}
Esempio n. 19
0
int main(void) {
	sodium_init();

	//create a user_store
	user_store *store = user_store_create();

	//check the content
	buffer_t *list = user_store_list(store);
	if (list->content_length != 0) {
		fprintf(stderr, "ERROR: List of users is not empty.\n");
		user_store_destroy(store);
		buffer_destroy_from_heap(list);

		return EXIT_FAILURE;
	}
	buffer_destroy_from_heap(list);

	int status;
	//create three users with prekeys and identity keys
	//first alice
	//alice identity key
	buffer_t *alice_private_identity = buffer_create(crypto_box_SECRETKEYBYTES, crypto_box_SECRETKEYBYTES);
	buffer_t *alice_public_identity = buffer_create(crypto_box_PUBLICKEYBYTES, crypto_box_PUBLICKEYBYTES);
	status = generate_and_print_keypair(
			alice_public_identity->content,
			alice_private_identity->content,
			"Alice",
			"identity");
	if (status != 0) {
		fprintf(stderr, "ERROR: Failed to generate Alice's identity keypair.\n");
		buffer_clear(alice_private_identity);
		return status;
	}

	//alice prekeys
	buffer_t *alice_private_prekeys = buffer_create(PREKEY_AMOUNT * crypto_box_SECRETKEYBYTES, PREKEY_AMOUNT * crypto_box_SECRETKEYBYTES);
	buffer_t *alice_public_prekeys = buffer_create(PREKEY_AMOUNT * crypto_box_PUBLICKEYBYTES, PREKEY_AMOUNT * crypto_box_PUBLICKEYBYTES);
	status = generate_prekeys(alice_private_prekeys, alice_public_prekeys);
	if (status != 0) {
		fprintf(stderr, "ERROR: Failed to generate Alice's prekeys.\n");
		buffer_clear(alice_private_identity);
		buffer_clear(alice_private_prekeys);
		return status;
	}

	//make illegal access to the user store
	printf("User store length: %zi\n", store->length); //The program should crash here!

	user_store_destroy(store);
	return EXIT_SUCCESS;
}
Esempio n. 20
0
bool InitializeYojimbo()
{
    g_defaultAllocator = new yojimbo::DefaultAllocator();

    assert( yojimbo::NonceBytes == crypto_aead_chacha20poly1305_NPUBBYTES );
    assert( yojimbo::KeyBytes == crypto_aead_chacha20poly1305_KEYBYTES );
    assert( yojimbo::AuthBytes == crypto_aead_chacha20poly1305_ABYTES );
    assert( yojimbo::KeyBytes == crypto_secretbox_KEYBYTES );
    assert( yojimbo::MacBytes == crypto_secretbox_MACBYTES );

    if ( !yojimbo::InitializeNetwork() )
        return false;

    return sodium_init() != -1;
}
Esempio n. 21
0
cipher_t *
aead_key_init(int method, const char *pass, const char *key)
{
    if (method < AES128GCM || method >= AEAD_CIPHER_NUM) {
        LOGE("aead_key_init(): Illegal method");
        return NULL;
    }

    cipher_t *cipher = (cipher_t *)ss_malloc(sizeof(cipher_t));
    memset(cipher, 0, sizeof(cipher_t));

    // Initialize sodium for random generator
    if (sodium_init() == -1) {
        FATAL("Failed to initialize sodium");
    }

    if (method >= CHACHA20POLY1305IETF) {
        cipher_kt_t *cipher_info = (cipher_kt_t *)ss_malloc(sizeof(cipher_kt_t));
        cipher->info             = cipher_info;
        cipher->info->base       = NULL;
        cipher->info->key_bitlen = supported_aead_ciphers_key_size[method] * 8;
        cipher->info->iv_size    = supported_aead_ciphers_nonce_size[method];
    } else {
        cipher->info = (cipher_kt_t *)aead_get_cipher_type(method);
    }

    if (cipher->info == NULL && cipher->key_len == 0) {
        LOGE("Cipher %s not found in crypto library", supported_aead_ciphers[method]);
        FATAL("Cannot initialize cipher");
    }

    if (key != NULL)
        cipher->key_len = crypto_parse_key(key, cipher->key,
                supported_aead_ciphers_key_size[method]);
    else
        cipher->key_len = crypto_derive_key(pass, cipher->key,
                supported_aead_ciphers_key_size[method]);

    if (cipher->key_len == 0) {
        FATAL("Cannot generate key and nonce");
    }

    cipher->nonce_len = supported_aead_ciphers_nonce_size[method];
    cipher->tag_len   = supported_aead_ciphers_tag_size[method];
    cipher->method    = method;

    return cipher;
}
Esempio n. 22
0
void HttpServer::start(int numOfWorkers, quint16 port)
{
    if(sodium_init()!=0)
    {
        qDebug() << "sodium problem";
    }

    SettingsManager::getSingleton().init();

    if(SettingsManager::getSingleton().has("reCAPTCHA/secret"))
    {
        qDebug() << "has reCAPTCHA settings";
        QString secret = SettingsManager::getSingleton().get("reCAPTCHA/secret").toString();
        ReCAPTCHAVerifier::getSingleton().init(secret);
    }

    QString adminPassHash;
    QString consolePath;

    if (SettingsManager::getSingleton().has("admin/pass") && SettingsManager::getSingleton().has("admin/path"))
    {
        qDebug() << "request admin console";
        adminPassHash = QCryptographicHash::hash(SettingsManager::getSingleton().get("admin/pass").toString().toUtf8(), QCryptographicHash::Sha512).toHex();
        consolePath = SettingsManager::getSingleton().get("admin/path").toString();
    }

    qDebug()<<"Need to create"<<numOfWorkers<<"workers";

    if(numOfWorkers<1)
    {
        numOfWorkers=1;
    }

    for(int i=0;i<numOfWorkers;++i)
    {
        Worker *aWorker=new Worker(QString("worker %1").arg(i), m_incomingConnectionQueue, consolePath, adminPassHash);
        aWorker->moveToThread(aWorker);
        aWorker->registerWebApps(m_webAppSet);
        aWorker->start();
        aWorker->setPriority(QThread::HighPriority);
        connect(aWorker, SIGNAL(shutdown()), this, SLOT(shutdown()));
        m_workerPool.push_back(aWorker);
    }

    listen(QHostAddress::Any, port);

    qDebug()<<"Start listening! main ThreadId"<<thread()->currentThreadId();
}
Esempio n. 23
0
int32_t psAesInitGCM(psAesGcm_t *ctx,
    const unsigned char key[AES_MAXKEYLEN], uint8_t keylen)
{
    /* Check that structure is 16bytes aligned: */
    if (((uintptr_t) (const void *) (&(ctx->libSodiumCtx))) % 16 != 0)
    {
        psTraceCrypto("\nFAIL: libsodium structure not 16bytes aligned");
        printf("FAIL: libsodium structure not 16bytes aligned %p", &(ctx->libSodiumCtx));
        psAssert(0);
        return PS_FAIL;
    }

    /* libsodium only supports aes256, not aes128 */
    if (keylen != crypto_aead_aes256gcm_KEYBYTES)
    {
        psTraceCrypto("FAIL: libsodium-aes doesn't support this key length");
        psAssert(keylen == crypto_aead_aes256gcm_KEYBYTES);
        return PS_FAIL;
    }

    if (sodium_init() != 0)
    {
        /* libsodium is already initialized, no problem */
    }

    if (crypto_aead_aes256gcm_is_available() == 0)
    {
        psTraceCrypto("FAIL: libsodium-aes not supported");
        psAssert(0);
        return PS_FAIL;
    }

    memset(ctx, 0x00, sizeof(psAesGcm_t));

    if (crypto_aead_aes256gcm_beforenm(&(ctx->libSodiumCtx), key) != 0)
    {
        psTraceCrypto("FAIL: libsodium-aes init");
        psAssert(0);
        return PS_FAIL;
    }
    return PS_SUCCESS;
}
Esempio n. 24
0
int main(void) {
	sodium_init();

	printf("HKDF as described in RFC 5869 based on HMAC-SHA512256!\n\n");

	unsigned char output_key[200];
	size_t output_key_length = sizeof(output_key);

	//create random salt
	unsigned char salt[crypto_auth_KEYBYTES];
	randombytes_buf(salt, crypto_auth_KEYBYTES);
	printf("Salt (%i Bytes):\n", crypto_auth_KEYBYTES);
	print_hex(salt, crypto_auth_KEYBYTES, 30);
	putchar('\n');

	//create key to derive from
	unsigned char input_key[100];
	size_t input_key_length = sizeof(input_key);
	randombytes_buf(input_key, input_key_length);
	printf("Input key (%zu Bytes):\n", input_key_length);
	print_hex(input_key, input_key_length, 30);
	putchar('\n');

	//info
	unsigned char* info = (unsigned char*) "This is some info!";
	size_t info_length = sizeof(info);
	printf("Info (%zu Bytes):\n", info_length); //this could also be binary data
	printf("%s\n\n", info);

	int status;
	status = hkdf(output_key, output_key_length, salt, input_key, input_key_length, info, info_length);
	if (status != 0) {
		fprintf(stderr, "ERROR: Failed to derive key. %i\n", status);
		return EXIT_FAILURE;
	}

	printf("Derived key (%zu Bytes):\n", output_key_length);
	print_hex(output_key, output_key_length, 30);
	putchar('\n');
	return EXIT_SUCCESS;
}
Esempio n. 25
0
int
main(int argc, char *argv[])
{
    struct stat st;
    int         fd;
    int         ret = -1;

    if (argc != 3) {
        usage();
    }
    if ((fd = open(argv[2], O_RDONLY)) == -1) {
        perror("open");
        return 1;
    }
    if (fstat(fd, &st) != 0) {
        perror("fdstat");
        (void) close(fd);
        return 1;
    }
    if (!S_ISREG(st.st_mode)) {
        fprintf(stderr, "[%s] is not a regular file\n", argv[2]);
        (void) close(fd);
        return 1;
    }
    sodium_init();
    if (strcmp(argv[1], "-e") == 0) {
        ret = file_encrypt(fd, st.st_size);
    } else if (strcmp(argv[1], "-d") == 0) {
        ret = file_decrypt(fd);
    } else {
        usage();
    }
    close(fd);

    if (ret != 0) {
        fprintf(stderr, "Aborted.\n");
    }

    return -ret;
}
Esempio n. 26
0
int main() {
  int i, t, p;
  char *pass = ucmalloc(4);
  unsigned char *h;
  char tmp[65];
  pw *item;
  pw *list = NULL;
  pw *have = NULL;
  unsigned char nonce[32] = {1};

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

  for(i=97; i<126; ++i) {
    pass[0] = i;
    pass[1] = 0;
    h = pcp_derivekey(pass, nonce);

    p =0;
    for(t=0; t<32; ++t) {
      sprintf(&tmp[p], "%02x", h[t]);
      p += 2;
    }

    have = NULL;
    HASH_FIND_STR(list, tmp, have);
    if(have == NULL) {
      item = ucmalloc(sizeof(pw));
      memcpy(item->hash, tmp, 65);
      HASH_ADD_STR( list, hash, item ); 
    }
    else {
      fprintf(stderr, "Error: collision found: %s!\n", have->hash);
      return 1;
    }
  }

  fprintf(stderr, "ok\n");
  return 0;
}
Esempio n. 27
0
/*
 * Init kickpass with a working directory and its corresponding master password.
 */
kp_error_t
kp_init(struct kp_ctx *ctx)
{
	const char *home;
	char **password;

	password = (char **)&ctx->password;

	home = getenv("HOME");
	if (!home) {
		return KP_NO_HOME;
	}

	if (strlcpy(ctx->ws_path, home, PATH_MAX) >= PATH_MAX) {
		errno = ENOMEM;
		return KP_ERRNO;
	}

	if (strlcat(ctx->ws_path, "/" KP_PATH, PATH_MAX) >= PATH_MAX) {
		errno = ENOMEM;
		return KP_ERRNO;
	}

	if (sodium_init() != 0) {
		return KP_EINTERNAL;
	}

	*password = sodium_malloc(KP_PASSWORD_MAX_LEN);
	if (!ctx->password) {
		errno = ENOMEM;
		return KP_ERRNO;
	}

	ctx->cfg.memlimit = crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_SENSITIVE/5;
	ctx->cfg.opslimit = crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_SENSITIVE/5;

	return KP_SUCCESS;
}
Esempio n. 28
0
bool _cdecl app_preinit( const wchar_t *cmdl )
{
#if defined _DEBUG || defined _CRASH_HANDLER
    ts::exception_operator_c::set_unhandled_exception_filter();
#endif

    sodium_init();

    if (!parsecmdl(cmdl))
        return false;

    if (!check_autoupdate())
        return false;

#ifdef _FINAL
    if (g_commandline.checkinstance)
        if (!check_instance()) return false;
#endif // _FINAL


#if defined _DEBUG || defined _CRASH_HANDLER
    ts::exception_operator_c::dump_filename = ts::fn_change_name_ext(ts::get_exe_full_name(), ts::wstr_c(CONSTWSTR(APPNAME)).append_char('.').append(ts::to_wstr(application_c::appver())).as_sptr(), CONSTWSTR("dmp"));
#endif

	ts::tsfileop_c::setup<fileop_c>();

	ts::CHARz_copy( g_sysconf.name, CONSTWSTR(APPNAME) .s );
    
#ifndef _FINAL
    debug_name();
    dotests0();
#endif

	TSNEW(application_c, cmdl); // not a memory leak! see SEV_EXIT handler

	return true;
}
int main(void) {
	sodium_init();

	int status;
	//create random chain key
	buffer_t *chain_key = buffer_create(crypto_auth_BYTES, crypto_auth_BYTES);
	status = buffer_fill_random(chain_key, chain_key->buffer_length);
	if (status != 0) {
		fprintf(stderr, "ERROR: Failed to create chain key. (%i)\n", status);
		buffer_clear(chain_key);
		return status;
	}

	//print first chain key
	printf("Chain key (%zi Bytes):\n", chain_key->content_length);
	print_hex(chain_key);
	putchar('\n');

	//derive message key from chain key
	buffer_t *message_key = buffer_create(crypto_auth_BYTES, crypto_auth_BYTES);
	status = derive_message_key(message_key, chain_key);
	buffer_clear(chain_key);
	if (status != 0) {
		fprintf(stderr, "ERROR: Failed to derive message key. (%i)\n", status);
		buffer_clear(message_key);
		return status;
	}

	//print message key
	printf("Message key (%zi Bytes):\n", message_key->content_length);
	print_hex(message_key);
	putchar('\n');

	buffer_clear(message_key);
	return EXIT_SUCCESS;
}
Esempio n. 30
0
void enc_key_init(int method, const char *pass)
{
    if (method <= TABLE || method >= CIPHER_NUM) {
        LOGE("enc_key_init(): Illegal method");
        return;
    }

    // Inilitialize cache
    cache_create(&iv_cache, 256, NULL);

#if defined(USE_CRYPTO_OPENSSL)
    OpenSSL_add_all_algorithms();
#endif

    uint8_t iv[MAX_IV_LENGTH];

    cipher_kt_t *cipher;
    cipher_kt_t cipher_info;

    if (method == SALSA20 || method == CHACHA20 || method == CHACHA20IETF) {
        if (sodium_init() == -1) {
            FATAL("Failed to initialize sodium");
        }
        // Fake cipher
        cipher = (cipher_kt_t *)&cipher_info;
#if defined(USE_CRYPTO_OPENSSL)
        cipher->key_len = supported_ciphers_key_size[method];
        cipher->iv_len  = supported_ciphers_iv_size[method];
#endif
#if defined(USE_CRYPTO_POLARSSL)
        cipher->base       = NULL;
        cipher->key_length = supported_ciphers_key_size[method] * 8;
        cipher->iv_size    = supported_ciphers_iv_size[method];
#endif
#if defined(USE_CRYPTO_MBEDTLS)
        // XXX: key_length changed to key_bitlen in mbed TLS 2.0.0
        cipher->base       = NULL;
        cipher->key_bitlen = supported_ciphers_key_size[method] * 8;
        cipher->iv_size    = supported_ciphers_iv_size[method];
#endif
    } else {
        cipher = (cipher_kt_t *)get_cipher_type(method);
    }

    if (cipher == NULL) {
        do {
#if defined(USE_CRYPTO_POLARSSL) && defined(USE_CRYPTO_APPLECC)
            if (supported_ciphers_applecc[method] != kCCAlgorithmInvalid) {
                cipher_info.base       = NULL;
                cipher_info.key_length = supported_ciphers_key_size[method] * 8;
                cipher_info.iv_size    = supported_ciphers_iv_size[method];
                cipher                 = (cipher_kt_t *)&cipher_info;
                break;
            }
#endif
#if defined(USE_CRYPTO_MBEDTLS) && defined(USE_CRYPTO_APPLECC)
            // XXX: key_length changed to key_bitlen in mbed TLS 2.0.0
            if (supported_ciphers_applecc[method] != kCCAlgorithmInvalid) {
                cipher_info.base       = NULL;
                cipher_info.key_bitlen = supported_ciphers_key_size[method] * 8;
                cipher_info.iv_size    = supported_ciphers_iv_size[method];
                cipher                 = (cipher_kt_t *)&cipher_info;
                break;
            }
#endif
            LOGE("Cipher %s not found in crypto library",
                 supported_ciphers[method]);
            FATAL("Cannot initialize cipher");
        } while (0);
    }

    const digest_type_t *md = get_digest_type("MD5");
    if (md == NULL) {
        FATAL("MD5 Digest not found in crypto library");
    }

    enc_key_len = bytes_to_key(cipher, md, (const uint8_t *)pass, enc_key, iv);
    if (enc_key_len == 0) {
        FATAL("Cannot generate key and IV");
    }
    if (method == RC4_MD5) {
        enc_iv_len = 16;
    } else {
        enc_iv_len = cipher_iv_size(cipher);
    }
    enc_method = method;
}