Esempio n. 1
0
File: app.c Progetto: symma/xmlsec
/**
 * xmlSecOpenSSLAppInit:
 * @config:             the path to certs.
 *
 * General crypto engine initialization. This function is used
 * by XMLSec command line utility and called before
 * @xmlSecInit function.
 *
 * Returns: 0 on success or a negative value otherwise.
 */
int
xmlSecOpenSSLAppInit(const char* config) {
    ERR_load_crypto_strings();

#ifndef XMLSEC_OPENSSL_110
    OPENSSL_config(NULL);
#endif

    OpenSSL_add_all_algorithms();

    if((RAND_status() != 1) && (xmlSecOpenSSLAppLoadRANDFile(NULL) != 1)) {
        xmlSecError(XMLSEC_ERRORS_HERE,
                    NULL,
                    "xmlSecOpenSSLAppLoadRANDFile",
                    XMLSEC_ERRORS_R_XMLSEC_FAILED,
                    XMLSEC_ERRORS_NO_MESSAGE);
        return(-1);
    }

    if((config != NULL) && (xmlSecOpenSSLSetDefaultTrustedCertsFolder(BAD_CAST config) < 0)) {
        xmlSecError(XMLSEC_ERRORS_HERE,
                    NULL,
                    "xmlSecOpenSSLSetDefaultTrustedCertsFolder",
                    XMLSEC_ERRORS_R_XMLSEC_FAILED,
                    XMLSEC_ERRORS_NO_MESSAGE);
        return(-1);
    }

    return(0);
}
Esempio n. 2
0
/*
  Initializes SSL and allocate global
  context SSL_context

  SYNOPSIS
    my_ssl_start
      mysql        connection handle

  RETURN VALUES
    0  success
    1  error
*/
int my_ssl_start(MYSQL *mysql)
{
    int rc= 0;
    DBUG_ENTER("my_ssl_start");
    /* lock mutex to prevent multiple initialization */
    pthread_mutex_lock(&LOCK_ssl_config);
    if (!my_ssl_initialized)
    {
        if (ssl_crypto_init())
            goto end;
        SSL_library_init();

#if SSLEAY_VERSION_NUMBER >= 0x00907000L
        OPENSSL_config(NULL);
#endif
        /* load errors */
        SSL_load_error_strings();
        /* digests and ciphers */
        OpenSSL_add_all_algorithms();

        if (!(SSL_context= SSL_CTX_new(TLSv1_client_method())))
        {
            my_SSL_error(mysql);
            rc= 1;
            goto end;
        }
        my_ssl_initialized= TRUE;
    }
end:
    pthread_mutex_unlock(&LOCK_ssl_config);
    DBUG_RETURN(rc);
}
Esempio n. 3
0
void OpenSSLInitializer::initialize()
{
	Poco::FastMutex::ScopedLock lock(_mutex);
	
	if (++_rc == 1)
	{
#if OPENSSL_VERSION_NUMBER >= 0x0907000L
		OPENSSL_config(NULL);
#endif
		SSL_library_init();
		SSL_load_error_strings();
		OpenSSL_add_all_algorithms();
		
		char seed[SEEDSIZE];
		RandomInputStream rnd;
		rnd.read(seed, sizeof(seed));
		RAND_seed(seed, SEEDSIZE);
		
		int nMutexes = CRYPTO_num_locks();
		_mutexes = new Poco::FastMutex[nMutexes];
		CRYPTO_set_locking_callback(&OpenSSLInitializer::lock);
#ifndef POCO_OS_FAMILY_WINDOWS // SF# 1828231: random unhandled exceptions when linking with ssl
		CRYPTO_set_id_callback(&OpenSSLInitializer::id);
#endif
		CRYPTO_set_dynlock_create_callback(&OpenSSLInitializer::dynlockCreate);
		CRYPTO_set_dynlock_lock_callback(&OpenSSLInitializer::dynlock);
		CRYPTO_set_dynlock_destroy_callback(&OpenSSLInitializer::dynlockDestroy);
	}
}
Esempio n. 4
0
gboolean signature_init(GError **error)
{
#if (OPENSSL_VERSION_NUMBER < 0x10100000L)
	OPENSSL_config(NULL);
	OpenSSL_add_all_algorithms();
	ERR_load_crypto_strings();
#else
	int ret;

	g_return_val_if_fail(error == FALSE || *error == NULL, FALSE);

	ret = OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG | OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL);
	if (!ret) {
		unsigned long err;
		const gchar *data;
		int flags;

		err = ERR_get_error_line_data(NULL, NULL, &data, &flags);
		g_set_error(
				error,
				R_SIGNATURE_ERROR,
				R_SIGNATURE_ERROR_CRYPTOINIT_FAILED,
				"Failed to initalize OpenSSL crypto: %s",
				(flags & ERR_TXT_STRING) ? data : ERR_error_string(err, NULL));
		return FALSE;
	}
#endif

	return TRUE;
}
Esempio n. 5
0
/*
  Initializes SSL and allocate global
  context SSL_context

  SYNOPSIS
    my_ssl_start
      mysql        connection handle

  RETURN VALUES
    0  success
    1  error
*/
int ma_ssl_start(char *errmsg, size_t errmsg_len)
{
  int rc= 1;
  /* lock mutex to prevent multiple initialization */
  pthread_mutex_init(&LOCK_openssl_config,MY_MUTEX_INIT_FAST);
  pthread_mutex_lock(&LOCK_openssl_config);
  if (!ma_ssl_initialized)
  {
    if (ssl_thread_init())
    {
      strncpy(errmsg, "Not enough memory", errmsg_len);
      goto end;
    }
    SSL_library_init();

#if SSLEAY_VERSION_NUMBER >= 0x00907000L
    OPENSSL_config(NULL);
#endif
    /* load errors */
    SSL_load_error_strings();
    /* digests and ciphers */
    OpenSSL_add_all_algorithms();

    if (!(SSL_context= SSL_CTX_new(TLSv1_client_method())))
    {
      ma_ssl_get_error(errmsg, errmsg_len);
      goto end;
    }
    rc= 0;
    ma_ssl_initialized= TRUE;
  }
end:
  pthread_mutex_unlock(&LOCK_openssl_config);
  return rc;
}
Esempio n. 6
0
void initialize()
{
    Mutex::ScopedLock lock(_mutex);
    
    if (++_refCount == 1)
    {
#if OPENSSL_VERSION_NUMBER >= 0x0907000L
        OPENSSL_config(NULL);
#endif
        SSL_library_init();
        SSL_load_error_strings();
        OpenSSL_add_all_algorithms();
        
        char seed[SEEDSIZE];
        Random::getSeed(seed, sizeof(seed));
        RAND_seed(seed, SEEDSIZE);
        
        int nMutexes = CRYPTO_num_locks();
        _mutexes = new Mutex[nMutexes];
        CRYPTO_set_locking_callback(&internal::lock);
// #ifndef WIN32 // SF# 1828231: random unhandled exceptions when linking with ssl
//         CRYPTO_set_id_callback(&internal::id);
// #endif
        CRYPTO_set_dynlock_create_callback(&internal::dynlockCreate);
        CRYPTO_set_dynlock_lock_callback(&internal::dynlock);
        CRYPTO_set_dynlock_destroy_callback(&internal::dynlockDestroy);
    }
}
Esempio n. 7
0
int aesdecrypt(unsigned char* ciphertext,int len,unsigned char* key,unsigned char* decryptedtext){
	
	int decryptedtext_len;
	//LOGD("LIB encrypttext:%s:len=%d\n",plaintext, strlen((char *)plaintext));
	//LOGD("LIB key:%s\n",key);
	
	unsigned char iv[32]={0};
	//memset(iv,0x00,sizeof(iv));
	//unsigned char *iv = (unsigned char*)"01234567890123456";
	
	/* Initialise the library */
  ERR_load_crypto_strings();
  OpenSSL_add_all_algorithms();
  OPENSSL_config(NULL);

  /* Decrypt the ciphertext */
  decryptedtext_len = decrypt(ciphertext, len, key, iv,
    decryptedtext);

  /* Add a NULL terminator. We are expecting printable text */
  decryptedtext[decryptedtext_len] = '\0';

  /* Show the decrypted text */
  //printf("Decrypted text is:\n");
  //printf("%s\n", decryptedtext);
  //LOGD("Decrypted text is:\n%s\n",decryptedtext);

  /* Clean up */
  EVP_cleanup();
  ERR_free_strings();
  
  return decryptedtext_len;
}
Esempio n. 8
0
void uwsgi_ssl_init(void) {
        OPENSSL_config(NULL);
        SSL_library_init();
        SSL_load_error_strings();
        OpenSSL_add_all_algorithms();
        uwsgi.ssl_initialized = 1;
}
Esempio n. 9
0
void crypto_init()
{
    /* Initialise the library */
    ERR_load_crypto_strings();
    OpenSSL_add_all_algorithms();
    OPENSSL_config(NULL);
}
Esempio n. 10
0
int aesencrypt(unsigned char* plaintext,unsigned char* key,unsigned char* ciphertext){
	
	int ciphertext_len;
	
	//LOGD("LIB plaintext:%s:len=%d\n",plaintext, strlen((char *)plaintext));
	//LOGD("LIB key:%s[0x%x,0x%x,0x%x,0x%x]\n",key,key[0],key[1],key[2],key[3]);
	
	unsigned char iv[32]={0};
	//unsigned char *iv = (unsigned char*)"01234567890123456";
	
	/* Initialise the library */
  ERR_load_crypto_strings();
  OpenSSL_add_all_algorithms();
  OPENSSL_config(NULL);

  /* Encrypt the plaintext */
  ciphertext_len = encrypt(plaintext, strlen((char *)plaintext), key, iv,
    ciphertext);
   
	/* Do something useful with the ciphertext here */
  //printf("Ciphertext is:\n");  
  //BIO_dump_fp(stdout, (char *)ciphertext, ciphertext_len);
  //LOGD("#### %x%x%x%x",ciphertext[0],ciphertext[1],ciphertext[2],ciphertext[3]);

  /* Clean up */
  EVP_cleanup();
  ERR_free_strings();
  
  return ciphertext_len;
}
Esempio n. 11
0
int main(int arc, char *argv[])
{ 
	DH *dh = DH_new();

	BN_GENCB *(*cb)(BN_GENCB *, int, int);	
	cb = &callback;

	char buf[400];
	char *bufPtr = &buf[0];

	/* Load the human readable error strings for libcrypto */
	ERR_load_crypto_strings();
	/* Load all digest and cipher algorithms */
	OpenSSL_add_all_algorithms();
	/* Load config file, and other important initialisation */
	OPENSSL_config(NULL);

	/*
		use special PRNG if possible:
			* /dev/random
			* /dev/hwrng
			* ...
	*/

	/*
 		----------------------------	PARAMATER GEN	------------------------
	*/

	printf("start generation\n");
	DH_generate_parameters_ex(dh, 256, 2, NULL);
	printf("paramters DONE\n");

	if(dh->pub_key == NULL)
		printf("pubkey init to NULL\n");

	DH_generate_key(dh);
	printf("key DONE\n");
	bufPtr = BN_bn2hex(dh->p);
	printf ("prime    : %s\n", bufPtr);
	bufPtr = BN_bn2hex(dh->g);
	printf ("generator: %s\n", bufPtr);
	bufPtr = BN_bn2hex(dh->pub_key);
	printf ("pubkey   : %s\n", bufPtr);
	bufPtr = BN_bn2hex(dh->priv_key);
	printf ("privkey  : %s\n", bufPtr);

  /* Clean up */

  /* Removes all digests and ciphers */
  EVP_cleanup();

  /* if you omit the next, a small leak may be left when you make use of the BIO (low level API) for e.g. base64 transformations */
  CRYPTO_cleanup_all_ex_data();

  /* Remove error strings */
  ERR_free_strings();

  return 0;
}
Esempio n. 12
0
		// init
		bool CryptographyEngine::init( void )
		{
			/* Initialise the library */
			ERR_load_CRYPTO_strings();
			OpenSSL_add_all_algorithms();
			OPENSSL_config( NULL );

			return true;
		}
Esempio n. 13
0
/* INFO: Setting it up
   
         The code below sets up the program. In this example we are going to
         take a simple message("The quick brown fox jumps over the lazy dog"),
         and then encrypt it using a predefined key and IV. In this example the
         key and IV have been hard coded in - in a real situation you would
         never do this! Following encryption we will then decrypt the resulting
         ciphertext, and(hopefully!) end up with the message we first started
         with. This program expects two functions to be defined: "encrypt" and
         "decrypt". We will define those further down the page. */
int aes_main(void) {
	/* INFO: Set up the key and iv. Do I need to say to not hard code these
	         in a real application? :-) */

	/* INFO: A 256 bit key */
	unsigned char * key =
		(unsigned char *)"01234567890123456789012345678901";

	/* INFO: A 128 bit IV */
	unsigned char * iv =(unsigned char *)"01234567890123456";

	/* INFO: Message to be encrypted */
	unsigned char *plaintext =
		(unsigned char *)"The quick brown fox jumps over the lazy dog";

	/* INFO: Buffer for ciphertext. Ensure the buffer is long enough for
	         the ciphertext which may be longer than the plaintext,
	         dependant on the algorithm and mode */
	unsigned char ciphertext[128];

	/* INFO: Buffer for the decrypted text */
	unsigned char decryptedtext[128];

	int decryptedtext_len, ciphertext_len;

	/* INFO: Initialise the library */
	ERR_load_crypto_strings();
	OpenSSL_add_all_algorithms();
	/* TODO: deprecated. Ude OPENSSL_init_crypto instead of it. */
	OPENSSL_config(NULL);

	/* INFO: Encrypt the plaintext */
	ciphertext_len = encrypt(plaintext, strlen((char *)plaintext), key,
		iv, ciphertext);

	/* INFO: Do something useful with the ciphertext here */
	printf("Ciphertext is:\n");
	BIO_dump_fp(stdout,(const char *)ciphertext, ciphertext_len);

	/* INFO: Decrypt the ciphertext */
	decryptedtext_len = decrypt(ciphertext, ciphertext_len, key, iv,
		decryptedtext);

	/* INFO: Add a NULL terminator. We are expecting printable text */
	decryptedtext[decryptedtext_len] = '\0';

	/* INFO: Show the decrypted text */
	printf("Decrypted text is:\n");
	printf("%s\n", decryptedtext);

	/* INFO: Clean up */
	EVP_cleanup();
	ERR_free_strings();

	return 0;
}
Esempio n. 14
0
static void openssl_init(void){
    static int init = 0;

    if(!init){
	OPENSSL_config(NULL);
        OpenSSL_add_all_algorithms();
        ERR_load_crypto_strings();
        init = 1;
    }
}
Esempio n. 15
0
void
ssh_OpenSSL_add_all_algorithms(void)
{
	OpenSSL_add_all_algorithms();

	/* Enable use of crypto hardware */
	ENGINE_load_builtin_engines();
	ENGINE_register_all_complete();
	OPENSSL_config(NULL);
}
Esempio n. 16
0
const char *dbapi_lookup(const char *key) {
	long res = 1;
	SSL_CTX* ctx = NULL;
	BIO *web = NULL, *out = NULL;
	SSL *ssl = NULL;
	const SSL_METHOD* method;
	char *token, *tmpout, *buf;
	int hlen=0, len=0, maxlen=2048;
	(void)SSL_library_init();
	SSL_load_error_strings();
	OPENSSL_config(NULL);
	method = SSLv23_method(); if(method==NULL) return NULL;
	ctx = SSL_CTX_new(method); if(ctx==NULL) return NULL;
	SSL_CTX_set_verify_depth(ctx, 4);
	SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3|SSL_OP_NO_TLSv1|
		SSL_OP_NO_COMPRESSION);
	web = BIO_new_ssl_connect(ctx); if(web==NULL) return NULL;
	res = BIO_set_conn_hostname(web, DB_API_SERVER); if(res!=1) return NULL;
	BIO_get_ssl(web, &ssl); if(ssl==NULL) return NULL;
	res = SSL_set_cipher_list(ssl, SECURE_CIPHER_LIST); if(res!=1) return NULL;
	res = SSL_set_tlsext_host_name(ssl, DB_API_HOST); if(res!=1) return NULL;
	out = BIO_new_fp(stdout, BIO_NOCLOSE); if(NULL==out) return NULL;
	res = BIO_do_connect(web); if(res!=1) return NULL;
	res = BIO_do_handshake(web); if(res!=1) return NULL;
	len=(60+strlen(key)+strlen(DB_API_HOST)+strlen(DB_API_AUTH));
	char *request=malloc(sizeof(char)*(len+1));
	snprintf(request,len,
		"GET %s HTTP/1.1\nHost: %s\nx-api-key: %s\nConnection: close\n\n",
		key, DB_API_HOST, DB_API_AUTH);
	request[len]='\0';
	BIO_puts(web, request);
	BIO_puts(out, "\n");
	buf = malloc(sizeof(char)*maxlen);
	do {
		char buff[1536] = {};
		len=BIO_read(web, buff, sizeof(buff));
		hlen+=len;
		if(hlen<maxlen&&len>0) strncat(buf,buff,len);
	} while (len>0 || BIO_should_retry(web));
	buf[maxlen]='\0';
	tmpout = malloc(sizeof(char)*(HASH_MAXLENGTH+1));
	token = strtok(buf, "\n");
	while (token) {
		snprintf(tmpout,HASH_MAXLENGTH,"%s",token);
		token = strtok(NULL, "\n");
	}
	tmpout[strlen(tmpout)]='\0';
	free(buf);
	free(request);
	if(out) BIO_free(out);
	if(web != NULL) BIO_free_all(web);
	if(NULL != ctx) SSL_CTX_free(ctx);
	return tmpout;
}
Esempio n. 17
0
/*
  Initializes SSL and allocate global
  context SSL_context

  SYNOPSIS
    my_ssl_start
      mysql        connection handle

  RETURN VALUES
    0  success
    1  error
*/
int ma_tls_start(char *errmsg, size_t errmsg_len)
{
  int rc= 1;
  if (ma_tls_initialized)
    return 0;

  /* lock mutex to prevent multiple initialization */
  pthread_mutex_init(&LOCK_openssl_config,MY_MUTEX_INIT_FAST);
  pthread_mutex_lock(&LOCK_openssl_config);
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
  OPENSSL_init_ssl(OPENSSL_INIT_LOAD_CONFIG, NULL);
#else
  if (ssl_thread_init())
  {
    strncpy(errmsg, "Not enough memory", errmsg_len);
    goto end;
  }
  SSL_library_init();

#if SSLEAY_VERSION_NUMBER >= 0x00907000L
  OPENSSL_config(NULL);
#endif
#endif
  /* load errors */
  SSL_load_error_strings();
  /* digests and ciphers */
  OpenSSL_add_all_algorithms();
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
  if (!(SSL_context= SSL_CTX_new(TLS_client_method())))
#else
  if (!(SSL_context= SSL_CTX_new(SSLv23_client_method())))
#endif
  {
    ma_tls_get_error(errmsg, errmsg_len);
    goto end;
  }
#ifdef HAVE_TLS_SESSION_CACHE
  SSL_CTX_set_session_cache_mode(SSL_context, SSL_SESS_CACHE_CLIENT);
  ma_tls_sessions= (MA_SSL_SESSION *)calloc(1, sizeof(struct st_ma_tls_session) * ma_tls_session_cache_size);
  SSL_CTX_sess_set_new_cb(SSL_context, ma_tls_session_cb);
  SSL_CTX_sess_set_remove_cb(SSL_context, ma_tls_remove_session_cb);
#endif
  disable_sigpipe();
#if OPENSSL_USE_BIOMETHOD
  memcpy(&ma_BIO_method, BIO_s_socket(), sizeof(BIO_METHOD));
  ma_BIO_method.bread= ma_bio_read;
  ma_BIO_method.bwrite= ma_bio_write;
#endif
  rc= 0;
  ma_tls_initialized= TRUE;
end:
  pthread_mutex_unlock(&LOCK_openssl_config);
  return rc;
}
Esempio n. 18
0
/**
 * @brief Initialize the signing subsystem
 *
 * @param key_filename The pathname to the private key file
 * @param bad_passphrase Pointer to flag that is set if the failure was
 *        likley due to an incorrect passphrase
 *
 * @returns True on success, false on failure.
 */
bool sign_init(char * key_filename, bool * bad_passphrase) {
    FILE * fp;

    if (bad_passphrase) {
        *bad_passphrase = false;
    }

    if (!crypto_initialized) {

        /* (From: https://wiki.openssl.org/index.php/Libcrypto_API) */
        /* Load the human readable error strings for libcrypto */
        ERR_load_crypto_strings();

        /* Load all digest and cipher algorithms */
        OpenSSL_add_all_algorithms();

        /* Load config file, and other important initialisation */
        OPENSSL_config(NULL);

        crypto_initialized = true;
    }

    /**
     * Load the RSA key object from the private key file
     * (see: http://hayageek.com/rsa-encryption-decryption-openssl-c/#private-encrypt)
     */
    fp = fopen(key_filename,"rb");
    if (fp == NULL) {
        fprintf(stderr, "ERROR: Can't open private key '%s' (err %d)\n",
                key_filename, errno);
        return false;
    }
    rsa = RSA_new();
    if (rsa == NULL) {
        fprintf(stderr, "ERROR: Can't allocate RSA for key '%s': %s\n",
               key_filename, ERR_error_string(ERR_get_error(), NULL));
            return false;
    } else {
        rsa = PEM_read_RSAPrivateKey(fp, &rsa, NULL, passphrase);
        if (rsa == NULL) {
            fprintf(stderr,
                    "ERROR: Can't read private key '%s' (%s)\n", key_filename,
                    ERR_error_string(ERR_get_error(), NULL));
            if (bad_passphrase) {
                *bad_passphrase = true;
            }
            return false;
        }
    }

    return true;
}
struct cipher encryptAES(char *plaintext){
	//unsigned char *key = (unsigned char *)"01234567890123456789012345678901";
	struct cipher c;
	c.length=0;
	/* A 256 bit IV */
	unsigned char *iv = (unsigned char *)"01234567890123456";
	/*
	 Buffer for ciphertext. Ensure the buffer is long enough for the
	* ciphertext which may be longer than the plaintext, dependant on the
	* algorithm and mode
	*/
	unsigned char ciphertext[170];
	//puts(plaintext);
	//char pt[1510];
	
	int decryptedtext_len=0, ciphertext_len=0;
	int numpieces=0;
	/* Initialise the library */
	ERR_load_crypto_strings();
	OpenSSL_add_all_algorithms();
	OPENSSL_config(NULL);
	//int numbytes=sizeof(plaintext);
	
	//char *data[numpieces];
	int i=0;
	int j=0;
	int len=strlen(plaintext);
	numpieces=(len/1500);
	int count=0;
	
	//puts(data);
	/* Encrypt the plaintext */
  		
	ciphertext_len = encrypt (plaintext,strlen ((char *)plaintext), key, iv,ciphertext);
	
	
	//sendMsg(sock,str2);
	//BIO_dump_fp (stdout, (const char *)ciphertext, ciphertext_len);
	
	//int c=1;
	//int d=1;//introducing delay
	//for ( c = 1 ; c <= 32767 ; c++ )
       //{}
	//sendMsg(sock,ciphertext);
	puts("The Encrypted message is");
	puts(ciphertext);
	c.length=ciphertext_len;
	strcpy(c.value,ciphertext);
		
	return c;
//	
}
Esempio n. 20
0
int main(int argc, char *argv[])
{

  /* Socket Setup */
  // default socket number
  int socketNumber = 5000;

  // Init the GPIO
  wiringPiSetup();
  pinMode(0, OUTPUT);
  pinMode(1, OUTPUT);

  testEncrypt();
  return 1;

  if (argc > 1){
    socketNumber = atoi(argv[1]);
  }

  // Set up socket first
  struct sockaddr_in serv_addr;

  signal(SIGINT, intHandler);

  listenfd = socket(AF_INET, SOCK_STREAM, 0);

  memset(&serv_addr,  '0', sizeof(serv_addr));

  serv_addr.sin_family      = AF_INET;
  serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
  serv_addr.sin_port        = htons(socketNumber);

  bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));

  listen(listenfd, 10);
  sessionfd = accept(listenfd, (struct sockaddr*)NULL, NULL);

  /* End of Socket Setup */

  /* OpenSSL setup */
  ERR_load_crypto_strings();
  OpenSSL_add_all_algorithms();
  OPENSSL_config(NULL);

  /* End of OpenSSL setup */

  commandHandler(sessionfd);

  // Destructor for socket
  close(listenfd);
}
Esempio n. 21
0
static int
initialize_openssl(void)
{
#ifdef ENABLE_THREAD_SAFETY
  if (pthread_mutex_lock(&openssl_init_mutex)) {
    return -1;
  }
#endif /* ENABLE_THREAD_SAFETY */
  if (do_initialize_openssl) {
#ifdef ENABLE_THREAD_SAFETY
    if (NULL == amqp_openssl_lockarray) {
      int i = 0;
      amqp_openssl_lockarray = calloc(CRYPTO_num_locks(), sizeof(pthread_mutex_t));
      if (!amqp_openssl_lockarray) {
        pthread_mutex_unlock(&openssl_init_mutex);
        return -1;
      }
      for (i = 0; i < CRYPTO_num_locks(); ++i) {
        if (pthread_mutex_init(&amqp_openssl_lockarray[i], NULL)) {
          free(amqp_openssl_lockarray);
          amqp_openssl_lockarray = NULL;
          pthread_mutex_unlock(&openssl_init_mutex);
          return -1;
        }
      }
    }

    if (0 == open_ssl_connections) {
      CRYPTO_set_id_callback(amqp_ssl_threadid_callback);
      CRYPTO_set_locking_callback(amqp_ssl_locking_callback);
    }
#endif /* ENABLE_THREAD_SAFETY */

    if (!openssl_initialized) {
      OPENSSL_config(NULL);

      SSL_library_init();
      SSL_load_error_strings();

      openssl_initialized = 1;
    }
  }

  ++open_ssl_connections;

#ifdef ENABLE_THREAD_SAFETY
  pthread_mutex_unlock(&openssl_init_mutex);
#endif /* ENABLE_THREAD_SAFETY */
  return 0;
}
Esempio n. 22
0
void crypto_open( void )
{
    /* Load the human readable error strings for libcrypto */
    ERR_load_crypto_strings();

    /* Load all digest and cipher algorithms */
    OpenSSL_add_all_algorithms();

    /* Load config file, and other important initialisation */
    OPENSSL_config(NULL);

	if( ( mdctx = EVP_MD_CTX_create() ) == NULL )
		handleErrors();

}
Esempio n. 23
0
void task_body (void *cookie)
{
        int ciphertext_len; 
        unsigned char key[] = "01234567890123456789012345678901";
	unsigned char iv[] = "01234567890123456";
        unsigned char plaintext[] = "the quick brown fox jumps over the lazy dog";
        unsigned char ciphertext[128];
	// init library
	ERR_load_crypto_strings();
	OpenSSL_add_all_algorithms();
	OPENSSL_config(NULL);  
	// notify switch to userspace
	//rt_task_set_mode(T_WARNSW, 0, NULL); 
	#ifdef DEBUG
		rt_printf ("Task Start\n");
		delay(1000);
	#endif
	for(;;) {
		// poll input pin for trigger
		if(digitalRead(INPUT_PIN) != 0){
			//start task marker
			digitalWrite(0, 1);
			#ifdef DEBUG
				rt_printf ("Trigger\n");
			#endif
			// when triggered, do security task
			// alternatively, use delay or sleep
			//rt_task_sleep(100000);
			//delay(100);
			ciphertext_len = encrypt(plaintext, strlen(plaintext), key, iv, ciphertext);
			#ifdef DEBUG
				rt_printf("Ciphertext is %d:\n", ciphertext_len);
				BIO_dump_fp(stdout, ciphertext, ciphertext_len);
			#endif
			digitalWrite(0, 0);
			while(digitalRead(INPUT_PIN!=0)) {
				// wait for response
			}
		}
		else{
			// debug delay or sleep
			//delay(1);
			//rt_task_sleep(1);
		}
	}
	EVP_cleanup();
	ERR_free_strings();
}
Esempio n. 24
0
int main() {
    /* Set up the key and iv. Do I need to say to not hard code these in a
     * real application? :-)
     */
    
    /* A 128 bit key */
    unsigned char *key = (unsigned char *)"0123456789012345601234567890123456";
    
    /* A 128 bit IV (Initialization Vector) */
    unsigned char *iv =  (unsigned char *)"01234567890123456";
    
    /* Message to be encrypted */
    unsigned char *plaintext = (unsigned char *)
        "The Advanced Encryption Standard (AES), also known as Rijndael(its original name), is a specificatio"
        "n for the encryption of electronic data established by the U.S. National Institute of Standards and "
        "Technology (NIST) in 2001. AES is based on the Rijndael cipher developed by two Belgian cryptographe"
        "rs, Joan Daemen and Vincent Rijmen, who submitted a proposal to NIST during the AES selection proces"
        "s. Rijndael is a family of ciphers with different key and block sizes. For AES, NIST selected three "
        "members of the Rijndael family, each with a block size of 128 bits, but three different key lengths:"
        " 128, 192 and 256 bits. AES has been adopted by the U.S. government and is now used worldwide. It su"
        "persedes the Data Encryption Standard (DES), which was published in 1977. The algorithm described by"
        " AES is a symmetric-key algorithm, meaning the same key is used for both encrypting and decrypting t"
        "he data. In the United States, AES was announced by the NIST as U.S. FIPS PUB 197 on November 26, 20"
        "01.";

    /* Initialise the library */
    ERR_load_crypto_strings();
    OpenSSL_add_all_algorithms();
    OPENSSL_config(NULL);

    /* Test cases */

//    test_encrypt_decrypt_result(plaintext, key, iv);

    test_encrypt_decrypt_performance(plaintext, key, iv);

    test_encrypt_preformance(plaintext, key, iv);

    test_decrypt_performance(plaintext, key, iv);

//    GenerateKey();

    /* Clean up */
    EVP_cleanup();
    ERR_free_strings();
    
    return 0;
}
Esempio n. 25
0
// .. c:function::
ch_error_t
ch_en_openssl_init(void)
//    :noindex:
//
//    see: :c:func:`ch_en_openssl_init`
//
// .. code-block:: cpp
//
{
    SSL_library_init();
    OpenSSL_add_all_algorithms();
    SSL_load_error_strings();
    OPENSSL_config("chirp");

    return CH_SUCCESS;
}
Esempio n. 26
0
int main(int, char **) {
    init_agent_log();

    int ret;
    struct sigaction act;

    memset(&act, 0, sizeof(act));
    act.sa_handler = &kill_handler;
    if ((ret = sigaction(SIGTERM, &act, NULL)) < 0) {
        ALOGE("sigaction failed [<<" << ret << "]");
        return EXIT_FAILURE;
    }

    OpenSSL_add_all_algorithms();
    SSL_library_init();
    OPENSSL_config(NULL);
    SSL_load_error_strings();

    try {

        LicenseManager::AgentLogic *logic = new LicenseManager::AgentLogic;
        LicenseManager::Agent agent;
        if (!agent.initialize(logic)) {
            ALOGE("cynara initialization failed");
            return -1;
        }
        s_agentPtr = &agent;
        ret = sd_notify(0, "READY=1");
        if (ret == 0) {
            ALOGW("Agent was not configured to notify its status");
        } else if (ret < 0) {
            ALOGE("sd_notify failed: [" << ret << "]");
        }
        agent.mainLoop();
        s_agentPtr = nullptr;
    } catch (const std::exception &e) {
        std::string error = e.what();
        ALOGE("Exception: %s", error.c_str());
    }

    CONF_modules_free();
    EVP_cleanup();
    ERR_free_strings();
    CRYPTO_cleanup_all_ex_data();

    return 0;
}
Esempio n. 27
0
/*
  Initializes SSL and allocate global
  context SSL_context

  SYNOPSIS
    my_ssl_start
      mysql        connection handle

  RETURN VALUES
    0  success
    1  error
*/
int my_ssl_start(MYSQL *mysql)
{
  int rc= 0;
  DBUG_ENTER("my_ssl_start");
  /* lock mutex to prevent multiple initialization */
  pthread_mutex_lock(&LOCK_ssl_config);

  if (!my_ssl_initialized)
  {
    if (!(LOCK_crypto= 
          (pthread_mutex_t *)my_malloc(sizeof(pthread_mutex_t) * 
                                       CRYPTO_num_locks(), MYF(0))))
    {
      rc= 1;
      goto end;
    } else
    {
      int i;

      for (i=0; i < CRYPTO_num_locks(); i++)
        pthread_mutex_init(&LOCK_crypto[i], NULL);
      CRYPTO_set_id_callback(my_cb_threadid);
			CRYPTO_set_locking_callback(my_cb_locking);
    }
#if SSLEAY_VERSION_NUMBER >= 0x00907000L
    OPENSSL_config(NULL);
#endif

    /* always returns 1, so we can discard return code */
    SSL_library_init();
    /* load errors */
    SSL_load_error_strings();
    /* digests and ciphers */
    OpenSSL_add_all_algorithms();

    if (!(SSL_context= SSL_CTX_new(TLSv1_client_method())))
    {
      my_SSL_error(mysql);
      rc= 1;
      goto end;
    }
    my_ssl_initialized= TRUE;
  }
end:
  pthread_mutex_unlock(&LOCK_ssl_config);
  DBUG_RETURN(rc);
}
Esempio n. 28
0
void init_openssl(void){

	(void)SSL_library_init();

	SSL_load_error_strings();

	/* Load the human readable error strings for libcrypto */
	ERR_load_BIO_strings();

	/* Load the human readable error strings for libcrypto */
	ERR_load_crypto_strings();

	/* Load all digest and cipher algorithms */
	OpenSSL_add_all_algorithms();

	OPENSSL_config(NULL);
}
Esempio n. 29
0
void bb_socket_ssl(struct bb_acceptor *acceptor) {

        if (!blastbeat.ssl_initialized) {
                OPENSSL_config(NULL);
                SSL_library_init();
                SSL_load_error_strings();
                OpenSSL_add_all_algorithms();
                blastbeat.ssl_initialized = 1;
                blastbeat.ssl_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, NULL);
        }

        acceptor->ctx = SSL_CTX_new(SSLv23_server_method());
        if (!acceptor->ctx) {
                fprintf(stderr, "unable to initialize SSL context: SSL_CTX_new()");
                exit(1);
        }

        long ssloptions = SSL_OP_NO_SSLv2 | SSL_OP_ALL | SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION;
        // disable compression (if possibile)
#ifdef SSL_OP_NO_COMPRESSION
        ssloptions |= SSL_OP_NO_COMPRESSION;
#endif
        SSL_CTX_set_options(acceptor->ctx, ssloptions);

        // release/reuse buffers as soon as possibile
#ifdef SSL_MODE_RELEASE_BUFFERS
        SSL_CTX_set_mode(acceptor->ctx, SSL_MODE_RELEASE_BUFFERS);
#endif

        if (SSL_CTX_set_cipher_list(acceptor->ctx, "HIGH") == 0) {
                fprintf(stderr,"unable to set SSL ciphers: SSL_CTX_set_cipher_list()");
                exit(1);
        }

        SSL_CTX_set_options(acceptor->ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);

        SSL_CTX_set_info_callback(acceptor->ctx, bb_ssl_info_cb);
#ifdef OPENSSL_NPN_UNSUPPORTED
        SSL_CTX_set_next_protos_advertised_cb(acceptor->ctx, bb_ssl_npn, NULL);
#endif

        SSL_CTX_set_session_cache_mode(acceptor->ctx, SSL_SESS_CACHE_SERVER);

        acceptor->read = bb_ssl_read;
        acceptor->write = bb_ssl_write;
}
Esempio n. 30
0
int main(int argc, char **argv){
	char *keyfilename, *outputfilename;
	char **files;
	FILE *keyfile;
	char error = 0;
	if(argc < 5 || ((argc -1)%2) != 0){
		usage(argv[0]);
		exit(-1);
	}
	keyfilename = argv[1];
	outputfilename = argv[2];
	
	ERR_load_crypto_strings();
	OpenSSL_add_all_algorithms();
	OPENSSL_config(NULL);


	if(NULL == (keyfile = fopen(keyfilename, "r"))){
		print_error("main", "unable to open private key", keyfilename);
		exit(-1);
	}
	if(NULL == (private_key = PEM_read_PrivateKey(keyfile, NULL, NULL, NULL))){
		print_error("main", "reading private key file. File in PEM format?", keyfilename);
		error = 1; goto error;
	}
	if(NULL == (outputfile = fopen(outputfilename, "w"))){
		print_error("main", "unable to open output file", outputfilename);
		exit(-1);
	}


	files = argv+3;
	process_files(files, argc - 3);
	
	error:
	CONF_modules_free();
	EVP_cleanup();
	ERR_free_strings();
	
	if(keyfile) fclose(keyfile);
	if(outputfile) fclose(outputfile);
	if(error)
		return -1;
	return 0;
}