Example #1
0
qint32 CryptoUtils::padAESEncrypt (const char *from, qint32 fromLen, char *to, qint32 size) {
    qint32 paddedSize = (fromLen + 15) & -16;
    Q_UNUSED(size);
    Q_ASSERT(fromLen > 0 && paddedSize <= size);
    if (fromLen < paddedSize) {
        qint32 isRandSupported = RAND_pseudo_bytes ((uchar *) from + fromLen, paddedSize - fromLen);
        Q_UNUSED(isRandSupported);
        Q_ASSERT(isRandSupported >= 0);
    }
    AES_ige_encrypt ((uchar *) from, (uchar *) to, paddedSize, &aes_key, aes_iv, AES_ENCRYPT);
//    delete from;
//    delete to;
    return paddedSize;
}
Example #2
0
void rand_pseudo_bytes(char* buf, int count)
{
  static int init = init_openssl();
  (void)init;

  // RAND_pseudo_bytes is deprecated in favor of RAND_bytes as of OpenSSL 1.1.0
#if OPENSSL_VERSION_NUMBER < 0x10100000L
  int result = RAND_pseudo_bytes((unsigned char*)buf, count);
  if (result == -1)
    FC_THROW("Error calling OpenSSL's RAND_pseudo_bytes(): ${code}", ("code", (uint32_t)ERR_get_error()));
#else
  rand_bytes(buf, count);
#endif
}
int
px_get_pseudo_random_bytes(uint8 *dst, unsigned count)
{
	int			res;

	if (!openssl_random_init)
		init_openssl_rand();

	res = RAND_pseudo_bytes(dst, count);
	if (res == 0 || res == 1)
		return count;

	return PXE_OSSL_RAND_ERROR;
}
Example #4
0
/*
 *  call-seq:
 *     pseudo_bytes(length) -> aString
 *
 */
static VALUE
ossl_rand_pseudo_bytes(VALUE self, SEL sel, VALUE len)
{
    VALUE str;
    int n = NUM2INT(len);

    str = rb_bstr_new();
    rb_bstr_resize(str, n);
    if (!RAND_pseudo_bytes((unsigned char *)rb_bstr_bytes(str), n)) {
	ossl_raise(eRandomError, NULL);
    }

    return str;
}
static int mech_step_accname(sasl_session_t *p, char *message, size_t len, char **out, size_t *out_len)
{
	ecdsa_session_t *s = p->mechdata;
	myuser_t *mu;
	char *end;
	unsigned char pubkey_raw[BUFSIZE];
	const unsigned char *pubkey_raw_p;
	metadata_t *md;
	int ret;

	memset(pubkey_raw, '\0', sizeof pubkey_raw);

	end = memchr(message, '\0', len);
	if (end == NULL)
		p->username = sstrndup(message, len);
	else
	{
		p->username = sstrndup(message, end-message);
		p->authzid = sstrndup(end+1, len-1-(end-message));
	}

	mu = myuser_find_by_nick(p->username);
	if (mu == NULL)
		return ASASL_FAIL;

	md = metadata_find(mu, "pubkey");
	if (md == NULL)
		return ASASL_FAIL;

	ret = base64_decode(md->value, (char *)pubkey_raw, BUFSIZE);
	if (ret == -1)
		return ASASL_FAIL;

	pubkey_raw_p = pubkey_raw;
	o2i_ECPublicKey(&s->pubkey, &pubkey_raw_p, ret);

#ifndef DEBUG_STATIC_CHALLENGE_VECTOR
	RAND_pseudo_bytes(s->challenge, CHALLENGE_LENGTH);
#else
	memset(s->challenge, 'A', CHALLENGE_LENGTH);
#endif

	*out = malloc(400);
	memcpy(*out, s->challenge, CHALLENGE_LENGTH);
	*out_len = CHALLENGE_LENGTH;

	s->step = ECDSA_ST_RESPONSE;
	return ASASL_MORE;
}
Example #6
0
static int packetTestsuiteMsg(const int random_msg) {
	unsigned char plbuf[packetTestsuite_PLBUF_SIZE];
	unsigned char plbufdec[packetTestsuite_PLBUF_SIZE];
	struct s_packet_data testdata = { .pl_buf_size = packetTestsuite_PLBUF_SIZE, .pl_buf = plbuf };
	struct s_packet_data testdatadec = { .pl_buf_size = packetTestsuite_PLBUF_SIZE, .pl_buf = plbufdec };
	unsigned char pkbuf[packetTestsuite_PKBUF_SIZE];
	struct s_crypto ctx[2];
	unsigned char secret[64];
	unsigned char nonce[16];
	struct s_seq_state seqstate;
	char str[4096];
	int len;
	
	memset(secret, 23, 64);
	memset(nonce, 5, 16);
	
	cryptoCreate(ctx, 2);
	
	if(!cryptoSetKeys(&ctx[0], 1, secret, 64, nonce, 16)) return 0;
	if(!cryptoSetKeys(&ctx[1], 1, secret, 64, nonce, 16)) return 0;

	seqInit(&seqstate, 0);
	
	memset(plbuf, 0, packetTestsuite_PLBUF_SIZE);
	if(random_msg) RAND_pseudo_bytes(plbuf, packetTestsuite_PLBUF_SIZE);
	else strcpy((char *)plbuf, "moo");
	len = packetTestsuite_PLBUF_SIZE;
	testdata.pl_length = len;
	testdata.pl_type = 0;
	testdata.pl_options = 0;
	testdata.peerid = plbuf[0];
	testdata.seq = 1;
	utilByteArrayToHexstring(str, 4096, plbuf, len);
	printf("%s (len=%d, peerid=%d) -> ", str, len, testdata.peerid);
	len = packetEncode(pkbuf, packetTestsuite_PKBUF_SIZE, &testdata, &ctx[0]);
	if(!(len > 0)) return 0;
	utilByteArrayToHexstring(str, 4096, pkbuf, len);
	printf("%s (%d) -> ", str, len);
	if(!(packetDecode(&testdatadec, pkbuf, len, &ctx[1], &seqstate))) return 0;
	if(!(testdatadec.pl_length > 0)) return 0;
	if(!(testdatadec.peerid == plbuf[0])) return 0;
	if(!memcmp(testdatadec.pl_buf, testdata.pl_buf, packetTestsuite_PLBUF_SIZE) == 0) return 0;
	utilByteArrayToHexstring(str, 4096, testdatadec.pl_buf, testdatadec.pl_length);
	printf("%s (len=%d, peerid=%d)\n", str, testdatadec.pl_length, testdatadec.peerid);
	
	cryptoDestroy(ctx, 2);

	return 1;
}
Example #7
0
static std::string get_salt(bool mac) {
  unsigned char buf[16];
  int i = RAND_pseudo_bytes(buf, 16);
  if (i < 0) {
    std::cout<<"Something wrong with random generator"<<std::endl;
  }

  if(mac){buf[15] = 0x01;}
  else {buf[15] = 0x02;}

  std::string ret;
  ret = Base64::encode(std::string((const char*)buf, 16));
  //std::cout<<"Generated salt: "<<ret<<std::endl;
  return ret;
}
Example #8
0
/* Generates a new serial number for a certificate. */
long get_serial()
{
	long serial = read_serial();

	if (serial == INVALID_SERIAL) { /* Read failed */
		/* Generate a new serial */
		RAND_pseudo_bytes((unsigned char*)&serial, sizeof(serial));
		serial &= 0x0FFFFFFF; /* Fix sign and allow loads of serials before an overflow occurs */
		RAND_cleanup();
		write_serial(serial);
	} else
		write_serial(++serial); /* Update serial file */

	return serial;
}
Example #9
0
void test_aes()
{
	const int nAESKeyLen = 16;
	unsigned char aesKey[nAESKeyLen + 1] = { 0 };
	RAND_pseudo_bytes((unsigned char*)aesKey, nAESKeyLen);
	std::string strKey((char*)aesKey, 16);
	std::cout << "key:  " << aesKey << std::endl << std::endl;
	std::string strAesKey((char*)aesKey, nAESKeyLen);
	std::string strNaked = "I am cswuyg.....";
	std::cout << "nake:  " << strNaked << std::endl;
	std::string strEncode = Encryption::EncodeAES(strAesKey, strNaked);
	std::cout << "encode:  " << strEncode << std::endl;
	std::string strDecode = Encryption::DecodeAES(strAesKey, strEncode);
	std::cout << "decode  " << strDecode << std::endl << std::endl;
}
Example #10
0
int
__bro_openssl_rand_bytes(u_char *buf, int num)
{
  if (! buf || num <= 0)
    return FALSE;

  /* Make sure PRNG is initialized; has effect only once. */
  prng_init();

  if (RAND_bytes(buf, num) > 0)
    return TRUE;
  
  RAND_pseudo_bytes(buf, num);
  return TRUE;
}
Example #11
0
int get_randomness( unsigned char * buf, int length )
{
    /* Seed OpenSSL PRNG with EGD enthropy pool -kre */
    if (ConfigFileEntry.use_egd &&
        (ConfigFileEntry.egdpool_path != NULL))
    {
      if (RAND_egd(ConfigFileEntry.egdpool_path) == -1)
            return -1;
    }

  if ( RAND_status() )
    return RAND_bytes( buf, length );
  else /* XXX - abort? */
    return RAND_pseudo_bytes( buf, length );
}
int
PKCS5_pbe_set0_algor(X509_ALGOR *algor, int alg, int iter,
    const unsigned char *salt, int saltlen)
{
	PBEPARAM *pbe = NULL;
	ASN1_STRING *pbe_str = NULL;
	unsigned char *sstr;

	pbe = PBEPARAM_new();
	if (!pbe) {
		ASN1err(ASN1_F_PKCS5_PBE_SET0_ALGOR, ERR_R_MALLOC_FAILURE);
		goto err;
	}
	if (iter <= 0)
		iter = PKCS5_DEFAULT_ITER;
	if (!ASN1_INTEGER_set(pbe->iter, iter)) {
		ASN1err(ASN1_F_PKCS5_PBE_SET0_ALGOR, ERR_R_MALLOC_FAILURE);
		goto err;
	}
	if (!saltlen)
		saltlen = PKCS5_SALT_LEN;
	if (!ASN1_STRING_set(pbe->salt, NULL, saltlen)) {
		ASN1err(ASN1_F_PKCS5_PBE_SET0_ALGOR, ERR_R_MALLOC_FAILURE);
		goto err;
	}
	sstr = ASN1_STRING_data(pbe->salt);
	if (salt)
		memcpy(sstr, salt, saltlen);
	else if (RAND_pseudo_bytes(sstr, saltlen) < 0)
		goto err;

	if (!ASN1_item_pack(pbe, ASN1_ITEM_rptr(PBEPARAM), &pbe_str)) {
		ASN1err(ASN1_F_PKCS5_PBE_SET0_ALGOR, ERR_R_MALLOC_FAILURE);
		goto err;
	}

	PBEPARAM_free(pbe);
	pbe = NULL;

	if (X509_ALGOR_set0(algor, OBJ_nid2obj(alg), V_ASN1_SEQUENCE, pbe_str))
		return 1;

err:
	if (pbe != NULL)
		PBEPARAM_free(pbe);
	ASN1_STRING_free(pbe_str);
	return 0;
}
Example #13
0
int encrypt_esp_packet(struct openconnect_info *vpninfo, struct pkt *pkt)
{
	int i, padlen;
	const int blksize = 16;
	unsigned int hmac_len = 20;
	int crypt_len;
	HMAC_CTX hmac_ctx;

	/* This gets much more fun if the IV is variable-length */
	pkt->esp.spi = vpninfo->esp_out.spi;
	pkt->esp.seq = htonl(vpninfo->esp_out.seq++);
	if (!RAND_pseudo_bytes((void *)&pkt->esp.iv, sizeof(pkt->esp.iv))) {
		vpn_progress(vpninfo, PRG_ERR,
			     _("Failed to generate random IV for ESP packet:\n"));
		openconnect_report_ssl_errors(vpninfo);
		return -EIO;
	}

	padlen = blksize - 1 - ((pkt->len + 1) % blksize);
	for (i=0; i<padlen; i++)
		pkt->data[pkt->len + i] = i + 1;
	pkt->data[pkt->len + padlen] = padlen;
	pkt->data[pkt->len + padlen + 1] = 0x04; /* Legacy IP */
	
	if (!EVP_EncryptInit_ex(&vpninfo->esp_out.cipher, NULL, NULL, NULL,
				pkt->esp.iv)) {
		vpn_progress(vpninfo, PRG_ERR,
			     _("Failed to set up encryption context for ESP packet:\n"));
		openconnect_report_ssl_errors(vpninfo);
		return -EINVAL;
	}

	crypt_len = pkt->len + padlen + 2;
	if (!EVP_EncryptUpdate(&vpninfo->esp_out.cipher, pkt->data, &crypt_len,
			       pkt->data, crypt_len)) {
		vpn_progress(vpninfo, PRG_ERR,
			     _("Failed to encrypt ESP packet:\n"));
		openconnect_report_ssl_errors(vpninfo);
		return -EINVAL;
	}

	HMAC_CTX_copy(&hmac_ctx, &vpninfo->esp_out.hmac);
	HMAC_Update(&hmac_ctx, (void *)&pkt->esp, sizeof(pkt->esp) + crypt_len);
	HMAC_Final(&hmac_ctx, pkt->data + crypt_len, &hmac_len);
	HMAC_CTX_cleanup(&hmac_ctx);

	return sizeof(pkt->esp) + crypt_len + 12;
}
Example #14
0
static size_t csf_write_page(CSF_CTX *ctx, int pgno, void *data, size_t data_sz) {
  off_t start_offset = HDR_SZ + (pgno * ctx->page_sz);
  off_t cur_offset =  lseek(*ctx->fh, 0L, SEEK_CUR);
  int to_write = ctx->page_sz;
  size_t write_sz = 0;
  CSF_PAGE_HEADER header;

  assert(data_sz <= ctx->data_sz);

  header.data_sz = data_sz;

  if(cur_offset != start_offset) { /* if not in proper position for page, seek there */
    cur_offset = lseek(*ctx->fh, start_offset, SEEK_SET);
  }
  
  RAND_pseudo_bytes(ctx->page_buffer, ctx->iv_sz);

  memcpy(ctx->scratch_buffer, &header, sizeof(header));
  memcpy(ctx->scratch_buffer + ctx->page_header_sz, data, data_sz);

  /* normally this would encrypt here */
  if(ctx->encrypted) {
    EVP_CIPHER_CTX ectx;
    void *out_ptr =  ctx->page_buffer + ctx->iv_sz;
    int out_sz, cipher_sz = 0;

    EVP_CipherInit(&ectx, CIPHER, NULL, NULL, 1);
    EVP_CIPHER_CTX_set_padding(&ectx, 0);
    EVP_CipherInit(&ectx, NULL, ctx->key_data, ctx->page_buffer, 1);
    EVP_CipherUpdate(&ectx, out_ptr + cipher_sz, &out_sz, ctx->scratch_buffer, ctx->page_header_sz + ctx->data_sz);
    cipher_sz += out_sz;
    EVP_CipherFinal(&ectx, out_ptr + cipher_sz, &out_sz);
    cipher_sz += out_sz;
    EVP_CIPHER_CTX_cleanup(&ectx);
    assert(cipher_sz == (ctx->page_header_sz + ctx->data_sz));
  } else {
    memcpy(ctx->page_buffer + ctx->iv_sz, ctx->scratch_buffer, ctx->page_header_sz + ctx->data_sz);
  }

  for(;write_sz < to_write;) { /* FIXME - error handling */ 
    size_t bytes_write = write(*ctx->fh, ctx->page_buffer + write_sz, to_write - write_sz);
    write_sz += bytes_write;
  }  
  
  TRACE6("csf_write_page(%d,%d,x,%d), cur_offset=%d, write_sz= %d\n", *ctx->fh, pgno, data_sz, cur_offset, write_sz);

  return data_sz;
}
Example #15
0
// create max_files and fill with random data
// return list of {file name, content md5}
static GList *populate_file_list (gint max_files, GList *l_files, gchar *in_dir)
{
    gint i;
    gchar *out_dir;
    GError *error = NULL;
    FileData *fdata;
    gchar *name;
    FILE *f;

    out_dir = g_dir_make_tmp (NULL, &error);
    g_assert (out_dir);


    LOG_debug (POOL_TEST, "In dir: %s   Out dir: %s", in_dir, out_dir);

    for (i = 0; i < max_files; i++) {
        char *bytes;
        size_t bytes_len;

        fdata = g_new0 (FileData, 1);
        fdata->checked = FALSE;
        bytes_len = g_random_int_range (100000, 1000000);
        bytes = g_malloc (bytes_len + 1);
        RAND_pseudo_bytes ((unsigned char *)bytes, bytes_len);
        *(bytes + bytes_len) = '\0';
        
        name = get_random_string (15, TRUE);
        fdata->in_name = g_strdup_printf ("%s/%s", in_dir, name);
        f = fopen (fdata->in_name, "w");
        fwrite (bytes, 1, bytes_len + 1, f);
        fclose (f);

        fdata->out_name = g_strdup_printf ("%s/%s", out_dir, name);
        get_md5_sum (bytes, bytes_len + 1, &fdata->md5, NULL);
        
        fdata->fout = fopen (fdata->out_name, "w");
        g_assert (fdata->fout);

        fdata->url = g_strdup_printf ("http://127.0.0.1:8011/%s", name);
        g_assert (fdata->url);
        
        LOG_debug (POOL_TEST, "%s -> %s, size: %u", fdata->in_name, fdata->md5, bytes_len);
        
        l_files = g_list_append (l_files, fdata);
    }

    return l_files;
}
Example #16
0
static void send_challenge_user(CcnetProcessor *processor, CcnetUser *user)
{
    CcnetKeepaliveProcPriv *priv = GET_PRIV (processor);
    unsigned char *buf;
    int len;

    ccnet_debug ("[Keepalive] Send user challenge to %.8s\n",
                 processor->peer->id);
    RAND_pseudo_bytes (priv->random_buf, 40);
    buf = public_key_encrypt (user->pubkey, priv->random_buf, 40, &len);
    ccnet_processor_send_update (processor, "321", NULL, (char *)buf, len);

    g_free(buf);
    processor->state = WAIT_CHALLENGE_USER;
    reset_timeout (processor);
}
Example #17
0
int winpr_RAND_pseudo(BYTE* output, size_t len)
{
#if defined(WITH_OPENSSL)
	if (RAND_pseudo_bytes(output, len) != 1)
		return -1;
#elif defined(WITH_MBEDTLS) && defined(MBEDTLS_HAVEGE_C)
	mbedtls_havege_state hs;
	mbedtls_havege_init(&hs);

	if (mbedtls_havege_random(&hs, output, len) != 0)
		return -1;

	mbedtls_havege_free(&hs);
#endif
	return 0;
}
Example #18
0
tls_t *tls_init_master(tls_issues_t *ti)
{
  /* Default id in case RAND fails */
  unsigned char sessionId[32] = "sofia/tls";
  tls_t *tls;

#if HAVE_SIGPIPE
  signal(SIGPIPE, SIG_IGN);  /* Ignore spurios SIGPIPE from OpenSSL */
#endif

  tls_set_default(ti);

  if (!(tls = tls_create(tls_master)))
    return NULL;

  if (tls_init_context(tls, ti) < 0) {
    int err = errno;
    tls_free(tls);
    errno = err;
    return NULL;
  }

  RAND_pseudo_bytes(sessionId, sizeof(sessionId));

  SSL_CTX_set_session_id_context(tls->ctx,
                                 (void*) sessionId,
				 sizeof(sessionId));

  if (ti->CAfile != NULL)
    SSL_CTX_set_client_CA_list(tls->ctx,
                               SSL_load_client_CA_file(ti->CAfile));

#if 0
  if (sock != -1) {
    tls->bio_con = BIO_new_socket(sock, BIO_NOCLOSE);

    if (tls->bio_con == NULL) {
      tls_log_errors(1, "tls_init_master", 0);
      tls_free(tls);
      errno = EIO;
      return NULL;
    }
  }
#endif

  return tls;
}
Example #19
0
static int nbiof_write(BIO *b, const char *in, int inl)
	{
	NBIO_TEST *nt;
	int ret=0;
	int num;
	unsigned char n;

	if ((in == NULL) || (inl <= 0)) return(0);
	if (b->next_bio == NULL) return(0);
	nt=(NBIO_TEST *)b->ptr;

	BIO_clear_retry_flags(b);

#if 1
	if (nt->lwn > 0)
		{
		num=nt->lwn;
		nt->lwn=0;
		}
	else
		{
		RAND_pseudo_bytes(&n,1);
		num=(n&7);
		}

	if (inl > num) inl=num;

	if (num == 0)
		{
		ret= -1;
		BIO_set_retry_write(b);
		}
	else
#endif
		{
		ret=BIO_write(b->next_bio,in,inl);
		if (ret < 0)
			{
			BIO_copy_next_retry(b);
			nt->lwn=inl;
			}
		}
	return(ret);
	}
Example #20
0
static void oc_new(char *dst) {
    int have_hash = 0, i;
    unsigned char hash[21];

#ifdef HAVE_TLS
    if (RAND_bytes(hash, 21) || RAND_pseudo_bytes(hash, 21))
	have_hash = 1;
#endif

    if (!have_hash) { /* should only be used if TLS is not available or it fails */
	unsigned char rbuf[64];
	if (!rand_inited) {
#ifdef HAVE_SRANDOMDEV
	    srandomdev();
#else
#ifdef Win32		
		srand(time(NULL) ^ (getpid() << 12));
#else
		/* fall back -- mix of time and pid is the best we can do ... */
	    srandom(time(NULL) ^ (getpid() << 12));
#endif
#endif
	    rand_inited = 1;
	}	
#ifdef Win32
	for (i = 0; i < sizeof(rbuf); i++) rbuf[i] = rand();
#else
	for (i = 0; i < sizeof(rbuf); i++) rbuf[i] = random();
#endif
	/* we use random -> SHA1 .. is it an overkill? */
	sha1hash((const char*)rbuf, sizeof(rbuf) - 1, hash);
	/* the last byte is the hold-out byte -- just because SHA gives only 160 bits */
	hash[20] = rbuf[sizeof(rbuf) - 1];
    }
    if (Rserve_oc_prefix)
      *(dst++) = Rserve_oc_prefix;
    for (i = 0; i < 21; i += 3) {
	*(dst++) = b64map[hash[i] & 63];
	*(dst++) = b64map[((hash[i] >> 6) | (hash[i + 1] << 2)) & 63];
	*(dst++) = b64map[((hash[i + 1] >> 4) | (hash[i + 2] << 4)) & 63];
	*(dst++) = b64map[hash[i + 2] >> 2];
    }
    *dst = 0;
}
Example #21
0
int
tr_cryptoRandInt( int upperBound )
{
    int noise;
    int val;

    assert( upperBound > 0 );

    if( RAND_pseudo_bytes ( (unsigned char *) &noise, sizeof noise ) >= 0 )
    {
        val = abs( noise ) % upperBound;
    }
    else /* fall back to a weaker implementation... */
    {
        val = tr_cryptoWeakRandInt( upperBound );
    }

    return val;
}
static int build_packet(char *buffer, const char *metric)
{
	HMAC_CTX ctx;
	struct timespec now;
	uint64_t timestamp;
	uint32_t nonce;
	unsigned int hmac_len;
	int metric_len = strlen(metric);

	RAND_pseudo_bytes((void *)&nonce, sizeof(nonce));
	clock_gettime(CLOCK_REALTIME, &now);
	timestamp = (uint64_t)now.tv_sec - 2; /* fake delay */

	HMAC_CTX_init(&ctx);
	HMAC_Init_ex(&ctx, HMAC_KEY, strlen(HMAC_KEY), EVP_sha256(), NULL);

	HMAC_Update(&ctx, (void *)&timestamp, sizeof(timestamp));
	HMAC_Update(&ctx, (void *)&nonce, sizeof(nonce));
	HMAC_Update(&ctx, (void *)metric, metric_len);

	HMAC_Final(&ctx, buffer, &hmac_len);

	HMAC_CTX_cleanup(&ctx);

	memcpy(buffer + SHA_SIZE, &timestamp, sizeof(timestamp));
	memcpy(buffer + SHA_SIZE + 8, &nonce, sizeof(nonce));
	memcpy(buffer + SHA_SIZE + 12, metric, metric_len);

#ifdef DEBUG
	{
		int i;

		fprintf(stderr, "HMAC: ");
		for (i = 0; i < SHA_SIZE; ++i)
			fprintf(stderr, "%02x", (unsigned char)buffer[i]);

		fprintf(stderr, "\nTIMESTAMP: %llu\nNONCE: %08x\nMETRIC: %s\n",
			(long long unsigned int)timestamp, nonce, metric);
	}
#endif

	return SHA_SIZE + 12 + metric_len;
}
Example #23
0
static int kek_wrap_key(unsigned char *out, size_t *outlen,
		const unsigned char *in, size_t inlen, EVP_CIPHER_CTX *ctx)
	{
	size_t blocklen = EVP_CIPHER_CTX_block_size(ctx);
	size_t olen;
	int dummy;
	/* First decide length of output buffer: need header and round up to
	 * multiple of block length.
	 */
	olen = (inlen + 4 + blocklen - 1)/blocklen;
	olen *= blocklen;
	if (olen < 2 * blocklen)
		{
		/* Key too small */
		return 0;
		}
	if (inlen > 0xFF)
		{
		/* Key too large */
		return 0;
		}
	if (out)
		{
		/* Set header */
		out[0] = (unsigned char)inlen;
		out[1] = in[0] ^ 0xFF;
		out[2] = in[1] ^ 0xFF;
		out[3] = in[2] ^ 0xFF;
		memcpy(out + 4, in, inlen);
		/* Add random padding to end */
		if (olen > inlen + 4)
			RAND_pseudo_bytes(out + 4 + inlen, olen - 4 - inlen);
		/* Encrypt twice */
		if (!EVP_EncryptUpdate(ctx, out, &dummy, out, olen)
		    || !EVP_EncryptUpdate(ctx, out, &dummy, out, olen))
			return 0;
		}

	*outlen = olen;

	return 1;
	}
Example #24
0
/* Set up a mac structure */
int PKCS12_setup_mac (PKCS12 * p12, int iter, unsigned char *salt, int saltlen, const EVP_MD * md_type)
{
    if (!(p12->mac = PKCS12_MAC_DATA_new ()))
        return PKCS12_ERROR;
    if (iter > 1)
    {
        if (!(p12->mac->iter = M_ASN1_INTEGER_new ()))
        {
            PKCS12err (PKCS12_F_PKCS12_SETUP_MAC, ERR_R_MALLOC_FAILURE);
            return 0;
        }
        if (!ASN1_INTEGER_set (p12->mac->iter, iter))
        {
            PKCS12err (PKCS12_F_PKCS12_SETUP_MAC, ERR_R_MALLOC_FAILURE);
            return 0;
        }
    }
    if (!saltlen)
        saltlen = PKCS12_SALT_LEN;
    p12->mac->salt->length = saltlen;
    if (!(p12->mac->salt->data = OPENSSL_malloc (saltlen)))
    {
        PKCS12err (PKCS12_F_PKCS12_SETUP_MAC, ERR_R_MALLOC_FAILURE);
        return 0;
    }
    if (!salt)
    {
        if (RAND_pseudo_bytes (p12->mac->salt->data, saltlen) < 0)
            return 0;
    }
    else
        memcpy (p12->mac->salt->data, salt, saltlen);
    p12->mac->dinfo->algor->algorithm = OBJ_nid2obj (EVP_MD_type (md_type));
    if (!(p12->mac->dinfo->algor->parameter = ASN1_TYPE_new ()))
    {
        PKCS12err (PKCS12_F_PKCS12_SETUP_MAC, ERR_R_MALLOC_FAILURE);
        return 0;
    }
    p12->mac->dinfo->algor->parameter->type = V_ASN1_NULL;

    return 1;
}
Session::Session(DC *dc, Settings *settings, CryptoUtils *crypto, QObject *parent) :
    Connection(dc->host(), dc->port(), parent),
    mSettings(settings),
    mCrypto(crypto),
    m_sessionId(0),
    m_serverSalt(0),
    mTimeDifference(0),
    m_seqNo(0),
    m_dc(dc),
    m_initConnectionNeeded(true) {
    // ensure dc has, at least, the shared key created
    Q_ASSERT(dc->state() >= DC::authKeyCreated);
    // copy calculated values for timeDifference and serverSalt when created shared key.
    // This copy is needed because we could have several sessions against same dc with different values
    mTimeDifference = m_dc->timeDifference();
    m_serverSalt = m_dc->serverSalt();
    // create session id
    RAND_pseudo_bytes((uchar *) &m_sessionId, 8);
    qCDebug(TG_CORE_SESSION) << "created session with id" << QString::number(m_sessionId, 16);
}
Example #26
0
File: dh.c Project: mwgoldsmith/ssh
int ssh_get_random(void *where, int len, int strong){

#ifdef HAVE_LIBGCRYPT
  /* variable not used in gcrypt */
  (void) strong;
  /* not using GCRY_VERY_STRONG_RANDOM which is a bit overkill */
  gcry_randomize(where,len,GCRY_STRONG_RANDOM);

  return 1;
#elif defined HAVE_LIBCRYPTO
  if (strong) {
    return RAND_bytes(where,len);
  } else {
    return RAND_pseudo_bytes(where,len);
  }
#endif

  /* never reached */
  return 1;
}
Example #27
0
static LUA_FUNCTION(openssl_random_bytes)
{
  long length = luaL_checkint(L, 1);
  int strong = lua_isnil(L, 2) ? 0 : lua_toboolean(L, 2);

  char *buffer = NULL;
  int ret = 0;

  if (length <= 0)
  {
    luaL_argerror(L, 1, "must greater than 0");
  }

  buffer = malloc(length + 1);
  if (strong)
  {
    ret = RAND_bytes((byte*)buffer, length);
    if (ret == 1)
    {
      lua_pushlstring(L, buffer, length);
    }
    else
    {
      lua_pushboolean(L, 0);
    }
  }
  else
  {
    ret = RAND_pseudo_bytes((byte*)buffer, length);
    if (ret == 1)
    {
      lua_pushlstring(L, buffer, length);
    }
    else
    {
      lua_pushboolean(L, 0);
    }
  }
  free(buffer);
  return 1;
}
Example #28
0
gchar *get_random_string (size_t len, gboolean readable)
{
    gchar *out;

    out = g_malloc (len + 1);

    if (readable) {
        gchar readable_chars[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        size_t i;

        for (i = 0; i < len; i++)
            out[i] = readable_chars[rand() % strlen (readable_chars)];
    } else {
        if (!RAND_pseudo_bytes ((unsigned char *)out, len))
            return out;
    }

    *(out + len) = '\0';

    return out;
}
Example #29
0
ClientSide::ClientSide()
{
    //ctor

    //salt len 20
    //get the random value

    m_rand_a = BN_new();
    unsigned char *tmp;
    if (m_rand_a != NULL && (tmp = (unsigned char *)malloc(2500*sizeof(char))) !=NULL)
    {
        RAND_pseudo_bytes(tmp, 20);
        m_rand_a = BN_bin2bn(tmp, 20, NULL);
        free(tmp);
//        print_bn(m_rand_b);
    }
    //get the default g and n
    m_base_g = &bn_generator_2;
    m_base_N = &bn_group_1024;
//    print_bn(m_base_g);
//    print_bn(m_base_N);
}
// Generate a random number between low and high.
int CyberUtil::randInt(int low, int high)
{
    // This produces great results on Mac/Linux but is awful on Windows.
//    return rand() % ((high + 1) - low) + low;

    // Use OpenSSL to generate random numbers
    // based on example found at:
    // http://www.mitchr.me/SS/exampleCode/random/opensslPRandEx.c.html
    int randInt = 0;
    int randInts[1];
    if (!(RAND_pseudo_bytes((unsigned char*) randInts, sizeof(randInts)))) {
        randInt = rand();
    } else {
        randInt = abs(randInts[0]);
    }

    return randInt % ((high + 1) - low) + low;

    //
    // Here are some other cool ways to use OpenSSL:
    // http://www.madboa.com/geek/openssl
}