Example #1
0
    bytes public_key::serialize()const
    {
       bytes ba;
       if( !my ) { return ba; }

       BIO *mem = BIO_new(BIO_s_mem());
       int e = PEM_write_bio_RSAPublicKey( mem, my->rsa );
       if( e != 1 )
       {
           BIO_free(mem);
           FC_THROW_EXCEPTION( exception, "openssl: ${message}", ("message",fc::string(ERR_error_string( ERR_get_error(),NULL))) );
       }
       char* dat;
       uint32_t l = BIO_get_mem_data( mem, &dat );

       fc::stringstream ss( string( dat, l ) );
       fc::stringstream key;
       fc::string tmp;
       fc::getline( ss, tmp );
       fc::getline( ss, tmp );
       while( tmp.size() && tmp[0] != '-' )
       {
         key << tmp; 
         fc::getline( ss, tmp );
       }
       auto str = key.str();
       str = fc::base64_decode( str );
       ba = bytes( str.begin(), str.end() );

       BIO_free(mem);
       return ba;
    }
Example #2
0
sqbind::CSqBinary COsslKey::getPublicKey()
{_STT();

	if ( !m_pkey )
		return sqbind::CSqBinary();

	BIO *pBio = BIO_new( BIO_s_mem() );
	if ( !pBio )
	{	oexERROR( 0, oexT( "BIO_new_mem_buf() failed" ) );
		Destroy();
		return sqbind::CSqBinary();
	} // end if

	if ( !PEM_write_bio_RSAPublicKey( pBio, m_pkey->pkey.rsa ) )
	{	oexERROR( 0, oexT( "PEM_read_bio_RSA_PUBKEY() failed" ) );
		Destroy();
		return sqbind::CSqBinary();
	} // end if

	BUF_MEM *bm = oexNULL;
	BIO_get_mem_ptr( pBio, &bm );

	sqbind::CSqBinary bin;
	bin.MemCpy( bm->data, bm->length );

	BIO_free( pBio );

	return bin;
}
Example #3
0
/** Encode <b>key</b> in the format used in directory documents; return
 * a newly allocated string holding the result or NULL on failure. */
static char *
key_to_string(EVP_PKEY *key)
{
  BUF_MEM *buf;
  BIO *b;
  RSA *rsa = EVP_PKEY_get1_RSA(key);
  char *result;
  if (!rsa)
    return NULL;

  b = BIO_new(BIO_s_mem());
  if (!PEM_write_bio_RSAPublicKey(b, rsa)) {
    crypto_log_errors(LOG_WARN, "writing public key to string");
    return NULL;
  }

  BIO_get_mem_ptr(b, &buf);
  (void) BIO_set_close(b, BIO_NOCLOSE);
  BIO_free(b);
  result = tor_malloc(buf->length + 1);
  memcpy(result, buf->data, buf->length);
  result[buf->length] = 0;
  BUF_MEM_free(buf);

  return result;
}
Example #4
0
boolean
an_key_get_public_key (uint8_t *key_label, an_key_t *key)
{
    const char cert_filestr[] = PUBLIC_KEY_LOCATION;
    BIO  *outbio = NULL;
    outbio = BIO_new_fp(stdout, BIO_NOCLOSE);
    int ret;
    char *pub_key = NULL;
    size_t pub_len;

    BIO* rsa_pub_bio = BIO_new_file(cert_filestr, "r");
    RSA* rsa_pub = RSA_new();

    ret = (PEM_read_bio_RSAPublicKey(rsa_pub_bio, &rsa_pub, NULL, NULL)!= NULL);
    if (ret == 0) {
        DEBUG_AN_LOG(AN_LOG_BS_EVENT, AN_DEBUG_INFO, NULL,
                "\n%sFailed to read public key from key pair",an_bs_event);
        return FALSE;
    }
    BIO *pub = BIO_new(BIO_s_mem());
    PEM_write_bio_RSAPublicKey(pub, rsa_pub);
    pub_key = (char*)malloc(BN_num_bits(rsa_pub->n) + 1);
    pub_len = BN_num_bits(rsa_pub->n);
    BIO_read(pub, pub_key, pub_len);
    pub_key[pub_len] = '\0';
    key->data = pub_key;
    key->len = pub_len;
    BIO_free(rsa_pub_bio);
    return TRUE;
}
Example #5
0
/**
* @brief Prints an RSA keypair.
*
* @param keypair
*/
void print_keypair(RSA *keypair) {
    // To get the C-string PEM form:
    BIO *pri = BIO_new(BIO_s_mem());
    BIO *pub = BIO_new(BIO_s_mem());
    
    PEM_write_bio_RSAPrivateKey(pri, keypair, NULL, NULL, 0, NULL, NULL);
    PEM_write_bio_RSAPublicKey(pub, keypair);
    
    size_t pri_len = BIO_pending(pri);
    size_t pub_len = BIO_pending(pub);
    
	char *pri_key, *pub_key;
    pri_key = (char *)malloc(pri_len + 1);
    pub_key = (char *)malloc(pub_len + 1);
    
    BIO_read(pri, pri_key, pri_len);
    BIO_read(pub, pub_key, pub_len);
    
    pri_key[pri_len] = '\0';
    pub_key[pub_len] = '\0';
    
    printf("\n%s\n\n%s\n", pri_key, pub_key);

    BIO_free_all(pub);
    BIO_free_all(pri);
    free(pri_key);
    free(pub_key);
}
Example #6
0
int RSA_envoi_key_pub ()
{
    // Déclaration variables
    int flen = 0 ;
    unsigned char* key = NULL ;
    BIO *keybio = NULL ;
    int taille ;
    char* reponse = NULL ;

    // Initialisation
    flen = RSA_size ( client_key ) + 170 ;
    key = (unsigned char*) malloc ( flen * sizeof ( unsigned char ) ) ;
    memset ( key, '\0', flen ) ;

    // On aloue notre object BIO avec la clé
    if ( ( keybio = BIO_new ( BIO_s_mem() ) ) == NULL )
    {
        perror ( "Erreur_RSA_envoi_key_pub : BIO_new() " ) ;
        fprintf ( stderr, "Code erreur OpenSSL : %lu \n ", ERR_get_error () ) ;
        free ( key ) ;
        return 0 ;
    }

    // On écrit la clé dans le BIO
    if ( PEM_write_bio_RSAPublicKey ( keybio, client_key ) == 0 )
    {
        perror ( "Erreur_RSA_envoi_key_pub : PEM_write_bio_RSAPublicKey() " ) ;
        fprintf ( stderr, "Code erreur OpenSSL : %lu \n ", ERR_get_error () ) ;
        free ( key ) ;
        BIO_free ( keybio ) ;
        return 0 ;
    }

    // On récupère la clé du BIO au format texte
    if ( BIO_read ( keybio, key, flen ) != flen )
    {
        perror ( "Erreur_RSA_envoi_key_pub : BIO_read() " ) ;
        fprintf ( stderr, "Code erreur OpenSSL : %lu \n ", ERR_get_error () ) ;
        free ( key ) ;
        BIO_free ( keybio ) ;
        return 0 ;
    }

    // On free notre object BIO
    BIO_free ( keybio ) ;

    // On envoie la réponse
    taille = flen + 10 ;
    reponse = (char*) malloc ( taille * sizeof ( char ) ) ;
    memset ( reponse, '\0', taille ) ;
    sprintf ( reponse, "init*%s*EOF", key ) ;
    envoi_requete ( reponse , strlen(reponse), WANT) ;

    // Free
    free ( key ) ;
    free ( reponse ) ;

    // On indique que tout s'est bien déroulé
    return 1 ;
}
Example #7
0
//生成RSA公钥和私钥文件
int createRSAPEM()
{
    int ret = 0;
    BIO *bpub = NULL;
    BIO *bpri = NULL;

    bpub = BIO_new_file(PUBKEY_FILE, "w");
    if (!bpub)
    {
        printf("failed to create public bio file\n");
    }

    bpri = BIO_new_file(PRIKEY_FILE, "w");
    if (!bpri)
    {
        printf("failed to create private bio file\n");
    }

    if (!bpub || !bpri) 
    {
        goto EXIT;
    }

    RSA *pRSA;
    pRSA = RSA_generate_key( 1024, RSA_F4, NULL, NULL);
    if (pRSA != NULL)
    {
        if (!PEM_write_bio_RSAPublicKey(bpub, pRSA))//PEM_write_bio_RSA_PUBKEY
        {
            printf("PEM_write_bio_RSAPublicKey: failed\n");
            goto EXIT;
        }

        //if (!PEM_write_bio_RSAPrivateKey(bpri, pRSA, EVP_aes_256_cbc(), NULL, 0, NULL, NULL))//暂时设置密码
        if (!PEM_write_bio_RSAPrivateKey(bpri, pRSA, NULL, NULL, 0, NULL, NULL))
        {
            printf("PEM_write_bio_PrivateKey: failed\n");
            goto EXIT;
        }
        ret =1;
    }
EXIT:
    if (bpub)
    {
        BIO_free(bpub);
    }
    if (bpri)
    {
        BIO_free(bpri);
    }
    if (pRSA)
    { 
        RSA_free(pRSA);
    }

    return ret;
}
Example #8
0
void openssl_rsa_pemkey()
{
	long len;
	BIGNUM *bne;
	BIO *ins, *outs;
	RSA *r, *read;
	char *name, *head;
	unsigned char *data;
	const EVP_CIPHER *enc;
	EVP_CIPHER_INFO cipher;

	OpenSSL_add_all_algorithms();

	bne = BN_new();
	BN_set_word(bne, RSA_3);
	r = RSA_new();
	RSA_generate_key_ex(r, LINE_LEN, bne, NULL);

	enc = EVP_des_ede3_ofb();
	outs = BIO_new_file("/tmp/pri.pem", "w");
	PEM_write_bio_RSAPrivateKey(outs, r, enc, NULL, 0, NULL, "beike2012");
	BIO_free(outs);

	outs = BIO_new_file("/tmp/pub.pem", "w");
	PEM_write_bio_RSAPublicKey(outs, r);
	BIO_free(outs);

	ins = BIO_new_file("/tmp/pri.pem", "rb");
	r = RSA_new();
	read = PEM_read_bio_RSAPrivateKey(ins, &r, NULL, "beike2012");
	if (read->d == NULL) {
		printf("PEM_read_bio_RSAPrivateKey err!\n");
		return;
	}

	printf("\nEVP_CIPHER_INFO:\n");
	while (1) {
		if (PEM_read_bio(ins, &name, &head, &data, &len) == 0)
			break;

		if (strlen(head) > 0) {
			PEM_get_EVP_CIPHER_INFO(head, &cipher);
			if (PEM_do_header(&cipher, data, &len, NULL, NULL) == 0)
				return;
			printf("name=%s, head=%s, data=%s\n", name, head, data);
		}

		OPENSSL_free(name);
		OPENSSL_free(head);
		OPENSSL_free(data);
	}

	RSA_free(read);
	BIO_free(ins);
}
Example #9
0
void RSAKeyImpl::save(const std::string& publicKeyFile,
	const std::string& privateKeyFile,
	const std::string& privateKeyPassphrase) const
{
	if (!publicKeyFile.empty())
	{
		BIO* bio = BIO_new(BIO_s_file());
		if (!bio) throw Poco::IOException("Cannot create BIO for writing public key file", publicKeyFile);
		try
		{
			if (BIO_write_filename(bio, const_cast<char*>(publicKeyFile.c_str())))
			{
				if (!PEM_write_bio_RSAPublicKey(bio, _pRSA))
					throw Poco::WriteFileException("Failed to write public key to file", publicKeyFile);
			}
			else throw Poco::CreateFileException("Cannot create public key file");
		}
		catch (...)
		{
			BIO_free(bio);
			throw;
		}
		BIO_free(bio);
	}
	
	if (!privateKeyFile.empty())
	{
		BIO* bio = BIO_new(BIO_s_file());
		if (!bio) throw Poco::IOException("Cannot create BIO for writing private key file", privateKeyFile);
		try
		{
			if (BIO_write_filename(bio, const_cast<char*>(privateKeyFile.c_str())))
			{
				int rc = 0;
				if (privateKeyPassphrase.empty())
					rc = PEM_write_bio_RSAPrivateKey(bio, _pRSA, 0, 0, 0, 0, 0);
				else
					rc = PEM_write_bio_RSAPrivateKey(bio, _pRSA, EVP_des_ede3_cbc(), 
						reinterpret_cast<unsigned char*>(const_cast<char*>(privateKeyPassphrase.c_str())), 
						static_cast<int>(privateKeyPassphrase.length()), 0, 0);
				if (!rc) throw Poco::FileException("Failed to write private key to file", privateKeyFile);
			}
			else throw Poco::CreateFileException("Cannot create private key file", privateKeyFile);
		}
		catch (...)
		{
			BIO_free(bio);
			throw;
		}
		BIO_free(bio);
	}
}
Example #10
0
boolean
an_key_generate_keypair (uint8_t *key_label)
{
    int ret = 0;
    RSA *r = NULL;
    BIGNUM *bne = NULL;
    BIO *bp_public = NULL, *bp_private = NULL;
    unsigned long e = RSA_F4;

    // 1. generate rsa key
    bne = BN_new();
    ret = BN_set_word(bne,e);
    if(ret != 1){
        goto free_all;
    }

    r = RSA_new();
    ret = RSA_generate_key_ex(r, AN_RSA_KEY_MODULUS, bne, NULL);
    if(ret != 1){
        goto free_all;
    }

    // 2. save public key
    bp_public = BIO_new_file(PUBLIC_KEY_LOCATION, "w+");
    ret = PEM_write_bio_RSAPublicKey(bp_public, r);
    if(ret != 1){
        goto free_all;
    }

    // 3. save private key
    bp_private = BIO_new_file(PRIVATE_KEY_LOCATION, "w+");
    ret = PEM_write_bio_RSAPrivateKey(bp_private, r, NULL, NULL, 0, NULL, NULL);

    // 4. free
    free_all:
        BIO_free_all(bp_public);
        BIO_free_all(bp_private);
        RSA_free(r);
        BN_free(bne);

    return (ret == 1);
}
Example #11
0
/** Helper function to implement crypto_pk_write_*_key_to_string. */
int crypto_pk_write_key_to_string_impl(crypto_pk_t *env, char **dest,
                                   size_t *len, int is_public)
{
    BUF_MEM *buf;
    BIO *b;
    int r;

//    assert(env);
//    assert(env->key);
//    assert(dest);

    b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
    if (!b)
        return -1;

    /* Now you can treat b as if it were a file.  Just use the
     * PEM_*_bio_* functions instead of the non-bio variants.
     */
    if (is_public)
        r = PEM_write_bio_RSAPublicKey(b, env->key);
    else
        r = PEM_write_bio_RSAPrivateKey(b, env->key, NULL,NULL,0,NULL,NULL);

    if (!r) {
        err(1, "writing RSA key to string");
        BIO_free(b);
        return -1;
    }

    BIO_get_mem_ptr(b, &buf);
    (void)BIO_set_close(b, BIO_NOCLOSE); /* so BIO_free doesn't free buf */
    BIO_free(b);

    *dest = sgx_malloc(buf->length+1);
    sgx_memcpy(*dest, buf->data, buf->length);
    (*dest)[buf->length] = 0; /* nul terminate it */
    *len = buf->length;
    BUF_MEM_free(buf);

    return 0;
}
Example #12
0
void RSAKeyImpl::save(std::ostream* pPublicKeyStream,
	std::ostream* pPrivateKeyStream,
	const std::string& privateKeyPassphrase) const
{
	if (pPublicKeyStream)
	{
		BIO* bio = BIO_new(BIO_s_mem());
		if (!bio) throw Poco::IOException("Cannot create BIO for writing public key");
		if (!PEM_write_bio_RSAPublicKey(bio, _pRSA))
		{
			BIO_free(bio);
			throw Poco::WriteFileException("Failed to write public key to stream");
		}
		char* pData;
		long size = BIO_get_mem_data(bio, &pData);
		pPublicKeyStream->write(pData, static_cast<std::streamsize>(size));
		BIO_free(bio);
	}

	if (pPrivateKeyStream)
	{
		BIO* bio = BIO_new(BIO_s_mem());
		if (!bio) throw Poco::IOException("Cannot create BIO for writing public key");
		int rc = 0;
		if (privateKeyPassphrase.empty())
			rc = PEM_write_bio_RSAPrivateKey(bio, _pRSA, 0, 0, 0, 0, 0);
		else
			rc = PEM_write_bio_RSAPrivateKey(bio, _pRSA, EVP_des_ede3_cbc(), 
				reinterpret_cast<unsigned char*>(const_cast<char*>(privateKeyPassphrase.c_str())), 
				static_cast<int>(privateKeyPassphrase.length()), 0, 0);
		if (!rc) 
		{
			BIO_free(bio);
			throw Poco::FileException("Failed to write private key to stream");
		}
		char* pData;
		long size = BIO_get_mem_data(bio, &pData);
		pPrivateKeyStream->write(pData, static_cast<std::streamsize>(size));
		BIO_free(bio);
	}
}
Example #13
0
  bool AdbEndpoint::generate_key()
  {
    bool success = false;
    BIGNUM* bne = NULL;
    //BIO* bp_public = NULL;
    //BIO* bp_private = NULL;
    int bits = 2048;
    unsigned long e = RSA_F4;

    // Generate RSA key
    bne = BN_new();
    if (1 == BN_set_word(bne, e))
    {
      _key = RSA_new();
      if (1 == RSA_generate_key_ex(_key, bits, bne, NULL))
      {
        success = true;
        int ret;
        BIO* bp;

        wxLogDebug("generated RSA key");

        // save it.
        wxFileName key_file_name(globalSettings()->settings_folder());

        key_file_name.SetName("adb_public.pem");
        bp = BIO_new_file(key_file_name.GetFullPath(), "w+");
        ret = PEM_write_bio_RSAPublicKey(bp, _key);
        BIO_free_all(bp);

        key_file_name.SetName("adb_private.pem");
        bp = BIO_new_file(key_file_name.GetFullPath(), "w+");
        ret = PEM_write_bio_RSAPrivateKey(bp, _key, NULL, NULL, 0, NULL, NULL);
        BIO_free_all(bp);
      }
      BN_free(bne);
    }

    return success;
  }
	void SecureServer::generateRSAKey (const int& bits, const std::string& publicFilename, const std::string &privateFilename, const std::string &password) throw (boost::system::system_error) {
		const unsigned long e = RSA_F4;
		
		//Generate RSA key
		std::unique_ptr<BIGNUM,void (*)(BIGNUM*)> bignum(BN_new(), &BN_free);
		int ret;
		if((ret = BN_set_word(bignum.get(), e)) != 1){
			throw_system_error_ssl("Could not set BIGNUM word");
		}
		
		std::unique_ptr<RSA,void (*)(RSA*)> rsa(RSA_new(), &RSA_free);
		if(RSA_generate_key_ex(rsa.get(), bits, bignum.get(), nullptr) != 1){
			throw_system_error_ssl("Could not generate RSA key");
		}
		
		//Save public key
		std::unique_ptr<BIO,void (*)(BIO*)> publicBIO(BIO_new_file(publicFilename.c_str(), "w"), &BIO_free_all);
		if(!publicBIO){
			throw_system_error_ssl("Could not open "+publicFilename+" for writing");
		}
		if(PEM_write_bio_RSAPublicKey(publicBIO.get(), rsa.get()) != 1){
			throw_system_error_ssl("Could not write RSA public key");
		}
		
		//Save private key
		std::unique_ptr<BIO,void (*)(BIO*)> privateBIO(BIO_new_file(privateFilename.c_str(), "w"), &BIO_free_all);
		if(!privateBIO){
			throw_system_error_ssl("Could not open "+privateFilename+" for writing");
		}
		if(password.empty()){
			if(PEM_write_bio_RSAPrivateKey(privateBIO.get(), rsa.get(), nullptr, nullptr, 0, nullptr, nullptr) != 1){
				throw_system_error_ssl("Could not write RSA private key");
			}
		}else{
			if(PEM_write_bio_RSAPrivateKey(privateBIO.get(), rsa.get(), EVP_des_ede3_cbc(), (unsigned char *)password.data(), password.size(), nullptr, nullptr) != 1){
				throw_system_error_ssl("Could not write RSA private key");
			}
		}
	}
Example #15
0
PyObject *
get_key_pem_public(const struct ccn_pkey *key_ccn)
{
	unsigned long err;
	RSA *public_key_rsa = NULL;
	BIO *bio;
	BUF_MEM *bufmem;
	int r;
	PyObject *py_res;

	bio = BIO_new(BIO_s_mem());
	JUMP_IF_NULL(bio, openssl_error);

	public_key_rsa = EVP_PKEY_get1_RSA((EVP_PKEY *) key_ccn);
	JUMP_IF_NULL(public_key_rsa, openssl_error);

	r = PEM_write_bio_RSAPublicKey(bio, public_key_rsa);
	RSA_free(public_key_rsa);
	public_key_rsa = NULL;
	if (!r)
		goto openssl_error;

	BIO_get_mem_ptr(bio, &bufmem);
	py_res = PyBytes_FromStringAndSize(bufmem->data, bufmem->length);
	r = BIO_free(bio);
	if (!r)
		goto openssl_error;

	return py_res;

openssl_error:
	err = ERR_get_error();
	PyErr_Format(g_PyExc_CCNKeyError, "Unable to obtain PEM: %s",
			ERR_reason_error_string(err));
	RSA_free(public_key_rsa);
	BIO_free(bio);
	return NULL;
}
Example #16
0
int generate_rsa_key_pair(int size){
	RSA* rsa=NULL;
	BIGNUM* bn=NULL;
	BIO *bp_public=NULL;
	BIO *bp_private=NULL;
	unsigned long e=RSA_F4;
	bn=BN_new();
	int success = BN_set_word(bn,e); 
	if(success!=1){	
		printf("Issue with BN_set_word\n");
	}
	rsa=RSA_new();
	success = RSA_generate_key_ex(rsa,size,bn,NULL);
 	if(success!=1){
		printf("Issue with RSA generation\n");
	}	
	//Now save the key to a file
	bp_public= BIO_new_file("publickey.pem","w+");
	success=PEM_write_bio_RSAPublicKey(bp_public,rsa);
	if(success!=1){
		printf("Issue writing the public key to file\n");	
	}
	else{
		printf("\tPublic key saved to publickey.pem...\n");
	}
	bp_private=BIO_new_file("privatekey.pem","w+");
	success=PEM_write_bio_RSAPrivateKey(bp_private,rsa,NULL,NULL,0,NULL,NULL);
	if(success!=1){
		printf("Issue writing the private key to file\n");
	}
	
	//Free pointers
	BIO_free_all(bp_public);
	BIO_free_all(bp_private);
	RSA_free(rsa);
	BN_free(bn);
	return success;
}
Example #17
0
int MAIN(int argc, char **argv)
	{
	ENGINE *e = NULL;
	int ret=1;
	RSA *rsa=NULL;
	int i,badops=0, sgckey=0;
	const EVP_CIPHER *enc=NULL;
	BIO *out=NULL;
	int informat,outformat,text=0,check=0,noout=0;
	int pubin = 0, pubout = 0;
	char *infile,*outfile,*prog;
	char *passargin = NULL, *passargout = NULL;
	char *passin = NULL, *passout = NULL;
#ifndef OPENSSL_NO_ENGINE
	char *engine=NULL;
#endif
	int modulus=0;

	int pvk_encr = 2;

	apps_startup();

	if (bio_err == NULL)
		if ((bio_err=BIO_new(BIO_s_file())) != NULL)
			BIO_set_fp(bio_err,OPENSSL_TYPE__FILE_STDERR,BIO_NOCLOSE|BIO_FP_TEXT);

	if (!load_config(bio_err, NULL))
		goto end;

	infile=NULL;
	outfile=NULL;
	informat=FORMAT_PEM;
	outformat=FORMAT_PEM;

	prog=argv[0];
	argc--;
	argv++;
	while (argc >= 1)
		{
		if 	(TINYCLR_SSL_STRCMP(*argv,"-inform") == 0)
			{
			if (--argc < 1) goto bad;
			informat=str2fmt(*(++argv));
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-outform") == 0)
			{
			if (--argc < 1) goto bad;
			outformat=str2fmt(*(++argv));
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-in") == 0)
			{
			if (--argc < 1) goto bad;
			infile= *(++argv);
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-out") == 0)
			{
			if (--argc < 1) goto bad;
			outfile= *(++argv);
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-passin") == 0)
			{
			if (--argc < 1) goto bad;
			passargin= *(++argv);
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-passout") == 0)
			{
			if (--argc < 1) goto bad;
			passargout= *(++argv);
			}
#ifndef OPENSSL_NO_ENGINE
		else if (TINYCLR_SSL_STRCMP(*argv,"-engine") == 0)
			{
			if (--argc < 1) goto bad;
			engine= *(++argv);
			}
#endif
		else if (TINYCLR_SSL_STRCMP(*argv,"-sgckey") == 0)
			sgckey=1;
		else if (TINYCLR_SSL_STRCMP(*argv,"-pubin") == 0)
			pubin=1;
		else if (TINYCLR_SSL_STRCMP(*argv,"-pubout") == 0)
			pubout=1;
		else if (TINYCLR_SSL_STRCMP(*argv,"-RSAPublicKey_in") == 0)
			pubin = 2;
		else if (TINYCLR_SSL_STRCMP(*argv,"-RSAPublicKey_out") == 0)
			pubout = 2;
		else if (TINYCLR_SSL_STRCMP(*argv,"-pvk-strong") == 0)
			pvk_encr=2;
		else if (TINYCLR_SSL_STRCMP(*argv,"-pvk-weak") == 0)
			pvk_encr=1;
		else if (TINYCLR_SSL_STRCMP(*argv,"-pvk-none") == 0)
			pvk_encr=0;
		else if (TINYCLR_SSL_STRCMP(*argv,"-noout") == 0)
			noout=1;
		else if (TINYCLR_SSL_STRCMP(*argv,"-text") == 0)
			text=1;
		else if (TINYCLR_SSL_STRCMP(*argv,"-modulus") == 0)
			modulus=1;
		else if (TINYCLR_SSL_STRCMP(*argv,"-check") == 0)
			check=1;
		else if ((enc=EVP_get_cipherbyname(&(argv[0][1]))) == NULL)
			{
			BIO_printf(bio_err,"unknown option %s\n",*argv);
			badops=1;
			break;
			}
		argc--;
		argv++;
		}

	if (badops)
		{
bad:
		BIO_printf(bio_err,"%s [options] <infile >outfile\n",prog);
		BIO_printf(bio_err,"where options are\n");
		BIO_printf(bio_err," -inform arg     input format - one of DER NET PEM\n");
		BIO_printf(bio_err," -outform arg    output format - one of DER NET PEM\n");
		BIO_printf(bio_err," -in arg         input file\n");
		BIO_printf(bio_err," -sgckey         Use IIS SGC key format\n");
		BIO_printf(bio_err," -passin arg     input file pass phrase source\n");
		BIO_printf(bio_err," -out arg        output file\n");
		BIO_printf(bio_err," -passout arg    output file pass phrase source\n");
		BIO_printf(bio_err," -des            encrypt PEM output with cbc des\n");
		BIO_printf(bio_err," -des3           encrypt PEM output with ede cbc des using 168 bit key\n");
#ifndef OPENSSL_NO_IDEA
		BIO_printf(bio_err," -idea           encrypt PEM output with cbc idea\n");
#endif
#ifndef OPENSSL_NO_SEED
		BIO_printf(bio_err," -seed           encrypt PEM output with cbc seed\n");
#endif
#ifndef OPENSSL_NO_AES
		BIO_printf(bio_err," -aes128, -aes192, -aes256\n");
		BIO_printf(bio_err,"                 encrypt PEM output with cbc aes\n");
#endif
#ifndef OPENSSL_NO_CAMELLIA
		BIO_printf(bio_err," -camellia128, -camellia192, -camellia256\n");
		BIO_printf(bio_err,"                 encrypt PEM output with cbc camellia\n");
#endif
		BIO_printf(bio_err," -text           print the key in text\n");
		BIO_printf(bio_err," -noout          don't print key out\n");
		BIO_printf(bio_err," -modulus        print the RSA key modulus\n");
		BIO_printf(bio_err," -check          verify key consistency\n");
		BIO_printf(bio_err," -pubin          expect a public key in input file\n");
		BIO_printf(bio_err," -pubout         output a public key\n");
#ifndef OPENSSL_NO_ENGINE
		BIO_printf(bio_err," -engine e       use engine e, possibly a hardware device.\n");
#endif
		goto end;
		}

	ERR_load_crypto_strings();

#ifndef OPENSSL_NO_ENGINE
        e = setup_engine(bio_err, engine, 0);
#endif

	if(!app_passwd(bio_err, passargin, passargout, &passin, &passout)) {
		BIO_printf(bio_err, "Error getting passwords\n");
		goto end;
	}

	if(check && pubin) {
		BIO_printf(bio_err, "Only private keys can be checked\n");
		goto end;
	}

	out=BIO_new(BIO_s_file());

	{
		EVP_PKEY	*pkey;

		if (pubin)
			{
			int tmpformat=-1;
			if (pubin == 2)
				{
				if (informat == FORMAT_PEM)
					tmpformat = FORMAT_PEMRSA;
				else if (informat == FORMAT_ASN1)
					tmpformat = FORMAT_ASN1RSA;
				}
			else if (informat == FORMAT_NETSCAPE && sgckey)
				tmpformat = FORMAT_IISSGC;
			else
				tmpformat = informat;
					
			pkey = load_pubkey(bio_err, infile, tmpformat, 1,
				passin, e, "Public Key");
			}
		else
			pkey = load_key(bio_err, infile,
				(informat == FORMAT_NETSCAPE && sgckey ?
					FORMAT_IISSGC : informat), 1,
				passin, e, "Private Key");

		if (pkey != NULL)
			rsa = EVP_PKEY_get1_RSA(pkey);
		EVP_PKEY_free(pkey);
	}

	if (rsa == NULL)
		{
		ERR_print_errors(bio_err);
		goto end;
		}

	if (outfile == NULL)
		{
		BIO_set_fp(out,OPENSSL_TYPE__FILE_STDOUT,BIO_NOCLOSE);
#ifdef OPENSSL_SYS_VMS
		{
		BIO *tmpbio = BIO_new(BIO_f_linebuffer());
		out = BIO_push(tmpbio, out);
		}
#endif
		}
	else
		{
		if (BIO_write_filename(out,outfile) <= 0)
			{
			TINYCLR_SSL_PERROR(outfile);
			goto end;
			}
		}

	if (text) 
		if (!RSA_print(out,rsa,0))
			{
			TINYCLR_SSL_PERROR(outfile);
			ERR_print_errors(bio_err);
			goto end;
			}

	if (modulus)
		{
		BIO_printf(out,"Modulus=");
		BN_print(out,rsa->n);
		BIO_printf(out,"\n");
		}

	if (check)
		{
		int r = RSA_check_key(rsa);

		if (r == 1)
			BIO_printf(out,"RSA key ok\n");
		else if (r == 0)
			{
			unsigned long err;

			while ((err = ERR_peek_error()) != 0 &&
				ERR_GET_LIB(err) == ERR_LIB_RSA &&
				ERR_GET_FUNC(err) == RSA_F_RSA_CHECK_KEY &&
				ERR_GET_REASON(err) != ERR_R_MALLOC_FAILURE)
				{
				BIO_printf(out, "RSA key error: %s\n", ERR_reason_error_string(err));
				ERR_get_error(); /* remove e from error stack */
				}
			}
		
		if (r == -1 || ERR_peek_error() != 0) /* should happen only if r == -1 */
			{
			ERR_print_errors(bio_err);
			goto end;
			}
		}
		
	if (noout)
		{
		ret = 0;
		goto end;
		}
	BIO_printf(bio_err,"writing RSA key\n");
	if 	(outformat == FORMAT_ASN1) {
		if(pubout || pubin) 
			{
			if (pubout == 2)
				i=i2d_RSAPublicKey_bio(out,rsa);
			else
				i=i2d_RSA_PUBKEY_bio(out,rsa);
			}
		else i=i2d_RSAPrivateKey_bio(out,rsa);
	}
#ifndef OPENSSL_NO_RC4
	else if (outformat == FORMAT_NETSCAPE)
		{
		unsigned char *p,*pp;
		int size;

		i=1;
		size=i2d_RSA_NET(rsa,NULL,NULL, sgckey);
		if ((p=(unsigned char *)OPENSSL_malloc(size)) == NULL)
			{
			BIO_printf(bio_err,"Memory allocation failure\n");
			goto end;
			}
		pp=p;
		i2d_RSA_NET(rsa,&p,NULL, sgckey);
		BIO_write(out,(char *)pp,size);
		OPENSSL_free(pp);
		}
#endif
	else if (outformat == FORMAT_PEM) {
		if(pubout || pubin)
			{
			if (pubout == 2)
		    		i=PEM_write_bio_RSAPublicKey(out,rsa);
			else
		    		i=PEM_write_bio_RSA_PUBKEY(out,rsa);
			}
		else i=PEM_write_bio_RSAPrivateKey(out,rsa,
						enc,NULL,0,NULL,passout);
#if !defined(OPENSSL_NO_DSA) && !defined(OPENSSL_NO_RC4)
	} else if (outformat == FORMAT_MSBLOB || outformat == FORMAT_PVK) {
		EVP_PKEY *pk;
		pk = EVP_PKEY_new();
		EVP_PKEY_set1_RSA(pk, rsa);
		if (outformat == FORMAT_PVK)
			i = i2b_PVK_bio(out, pk, pvk_encr, 0, passout);
		else if (pubin || pubout)
			i = i2b_PublicKey_bio(out, pk);
		else
			i = i2b_PrivateKey_bio(out, pk);
		EVP_PKEY_free(pk);
#endif
	} else	{
		BIO_printf(bio_err,"bad output format specified for outfile\n");
		goto end;
		}
	if (i <= 0)
		{
		BIO_printf(bio_err,"unable to write key\n");
		ERR_print_errors(bio_err);
		}
	else
		ret=0;
end:
	if(out != NULL) BIO_free_all(out);
	if(rsa != NULL) RSA_free(rsa);
	if(passin) OPENSSL_free(passin);
	if(passout) OPENSSL_free(passout);
	apps_shutdown();
	OPENSSL_EXIT(ret);
	}
Example #18
0
void Key::generateNewKey(string publicKeyFile, string privateKeyFile)
{
    priName = privateKeyFile;
    pubName = publicKeyFile;
    
    RSA *rsa = RSA_generate_key(LENGTH, RSA_F4, NULL, NULL);
    if (rsa == NULL) {
        cout << "RSA_generate_key Error!" << endl;
        return ;
    }
    
    BIO *priBio = BIO_new_file(privateKeyFile.c_str(), "w");
    if (PEM_write_bio_RSAPrivateKey(priBio, rsa, NULL, NULL, 0, NULL, NULL) <= 0) {
        cout << "Save to private key file error!" << endl;
    }
    
    BIO *pubBio = BIO_new_file(publicKeyFile.c_str(), "w");
    if (PEM_write_bio_RSAPublicKey(pubBio, rsa) <= 0) {
        cout << "Save to public key file error!" << endl;
    }
    
    BIO_free(priBio);
    BIO_free(pubBio);
    
//    FILE *priFile = fopen(privateKeyFile.c_str(), "w+");
//    if (PEM_write_RSAPrivateKey(priFile, rsa, EVP_des_ede3_ofb(), NULL, NULL, NULL, NULL) <= 0) {
//        cout << "Save to private key file error!" << endl;
//    }
//    fclose(priFile);
//    
//    FILE *pubFile = fopen(publicKeyFile.c_str(), "w+");
//    if (PEM_write_RSA_PUBKEY(pubFile, rsa) <= 0) {
//        cout << "Save to public key file error!" << endl;
//    }
//    fclose(pubFile);
//    
//    BIO *bp = BIO_new(BIO_s_file());
//    if (bp == NULL) {
//        cout << "BIO_new Error!" << endl;
//        return ;
//    }
//    if (BIO_write_filename(bp, (void *)publicKeyFile.c_str()) <= 0) {
//        cout << "BIO_write_filename Error!" << endl;
//        return ;
//    }
//    if (PEM_write_bio_RSAPublicKey(bp, rsa) != 1) {
//        cout << "PEM_write_bio_RSAPublicKey Error!" << endl;
//        return ;
//    }
//    cout << "Created Public Key" << endl;
//    
//    bp = BIO_new_file(privateKeyFile.c_str(), "w+");
//    if(NULL == bp) {
//        cout << "BIO_new_file error(private key)!" << endl;
//        return ;
//    }
//    if (PEM_write_bio_RSAPrivateKey(bp, rsa, EVP_des_ede3_ofb(), NULL, NULL, NULL, NULL) != 1) {
//        cout << "PEM_write_bio_RSAPrivateKey Error!" << endl;
//        return ;
//    }
//
//    BIO_free_all(bp);
    this->rsa = rsa;
    privateKey = RSAPrivateKey_dup(rsa);
    publicKey = RSAPublicKey_dup(rsa);
}
Example #19
0
static LUA_FUNCTION(openssl_pkey_export)
{
  EVP_PKEY * key;
  int ispriv = 0;
  int exraw = 0;
  int expem = 1;
  size_t passphrase_len = 0;
  BIO * bio_out = NULL;
  int ret = 0;
  const EVP_CIPHER * cipher;
  const char * passphrase = NULL;

  key = CHECK_OBJECT(1, EVP_PKEY, "openssl.evp_pkey");
  ispriv = openssl_pkey_is_private(key);

  if (!lua_isnoneornil(L, 2))
    expem = lua_toboolean(L, 2);

  if (expem)
  {
    if (!lua_isnoneornil(L, 3))
      exraw = lua_toboolean(L, 3);
    passphrase = luaL_optlstring(L, 4, NULL, &passphrase_len);
  } else
  {
    passphrase = luaL_optlstring(L, 3, NULL, &passphrase_len);
  }

  if (passphrase)
  {
    cipher = (EVP_CIPHER *) EVP_des_ede3_cbc();
  }
  else
  {
    cipher = NULL;
  }

  bio_out = BIO_new(BIO_s_mem());
  if (expem)
  {
    if (exraw==0)
    {
      ret = ispriv ?
        PEM_write_bio_PrivateKey(bio_out, key, cipher, (unsigned char *)passphrase, passphrase_len, NULL, NULL) :
        PEM_write_bio_PUBKEY(bio_out, key);
    }
    else
    {
      /* export raw key format */
      switch (EVP_PKEY_type(key->type))
      {
      case EVP_PKEY_RSA:
      case EVP_PKEY_RSA2:
        ret = ispriv ? PEM_write_bio_RSAPrivateKey(bio_out, key->pkey.rsa, cipher, (unsigned char *)passphrase, passphrase_len, NULL, NULL)
          : PEM_write_bio_RSAPublicKey(bio_out, key->pkey.rsa);
      break;
      case EVP_PKEY_DSA:
      case EVP_PKEY_DSA2:
      case EVP_PKEY_DSA3:
      case EVP_PKEY_DSA4:
      {
        ret = ispriv ? PEM_write_bio_DSAPrivateKey(bio_out, key->pkey.dsa, cipher, (unsigned char *)passphrase, passphrase_len, NULL, NULL)
          : PEM_write_bio_DSA_PUBKEY(bio_out, key->pkey.dsa);
      }
      break;
      case EVP_PKEY_DH:
        ret = PEM_write_bio_DHparams(bio_out, key->pkey.dh);
      break;
#ifndef OPENSSL_NO_EC
      case EVP_PKEY_EC:
        ret = ispriv ? PEM_write_bio_ECPrivateKey(bio_out, key->pkey.ec, cipher, (unsigned char *)passphrase, passphrase_len, NULL, NULL)
        : PEM_write_bio_EC_PUBKEY(bio_out, key->pkey.ec);
      break;
#endif
      default:
      ret = 0;
      break;
      }
    }
  }
  else
  {
    if (ispriv)
    {
      if (passphrase == NULL)
      {
        ret = i2d_PrivateKey_bio(bio_out, key);
      } else
      {
        ret = i2d_PKCS8PrivateKey_bio(bio_out, key, cipher, (char *)passphrase, passphrase_len, NULL, NULL);
      }
    } else
    {
      int l;
      l = i2d_PublicKey(key, NULL);
      if (l > 0)
      {
        unsigned char* p = malloc(l);
        unsigned char* pp = p;
        l = i2d_PublicKey(key, &pp);
        if (l > 0)
        {
          BIO_write(bio_out, p, l);
          ret = 1;
        } else
          ret = 0;
        free(p);
      } else
        ret = 0;
    }
  }

  
  if (ret)
  {
    char * bio_mem_ptr;
    long bio_mem_len;

    bio_mem_len = BIO_get_mem_data(bio_out, &bio_mem_ptr);

    lua_pushlstring(L, bio_mem_ptr, bio_mem_len);
    ret  = 1;
  }

  if (bio_out)
  {
    BIO_free(bio_out);
  }
  return ret;
}
Example #20
0
int
main() {
    BIO *bio;
    RSA *rsa=0, *rsa_pub, *rsa_priv=0;
    char buf[4096], enc[4096], dec[4096];
    BUF_MEM *ptr;
    int len, enc_len, dec_len;
    int i;
    BF_KEY key;
    char ivec_orig[8] = {1, 2, 3, 4, 5, 6, 7, 8}, ivec[8];


    do {
        //OpenSSL_add_all_algorithms();
        //OpenSSL_add_all_ciphers();
        //OpenSSL_add_all_digests();

        printf("generate_key:\n");
        rsa = RSA_generate_key(1024, 3, gen_cb, 0);
        printf("\n");

        printf("pem public key:\n");
        bio = BIO_new(BIO_s_mem());
        i = PEM_write_bio_RSAPublicKey(bio, rsa);
        BIO_flush(bio);
        i = BIO_get_mem_ptr(bio, &ptr);
        printf("pem public key len=%d\n", ptr->length);
        fwrite(ptr->data, ptr->length, 1, stdout);
        len = ptr->length;
        memcpy(buf, ptr->data, len);
        BIO_free(bio);
        printf("\n");

        bio = BIO_new_mem_buf(buf, len);
        rsa_pub = PEM_read_bio_RSAPublicKey(bio, 0, 0, 0);
        BIO_free(bio);

        printf("pem private key:\n");
        bio = BIO_new(BIO_s_mem());
        i = PEM_write_bio_RSAPrivateKey(bio, rsa, 0, 0, 0, 0, 0);
        BIO_flush(bio);
        i = BIO_get_mem_ptr(bio, &ptr);
        printf("pem private key i=%d len=%d\n", i, ptr->length);
        fwrite(ptr->data, ptr->length, 1, stdout);
        len = ptr->length;
        memcpy(buf, ptr->data, len);
        BIO_free(bio);
        printf("\n");

        bio = BIO_new_mem_buf(buf, len);
        rsa_priv = PEM_read_bio_RSAPrivateKey(bio, 0, 0, 0);
        BIO_free(bio);

        /* encrypt */

        printf("buffer:\n");
        len = sprintf(buf, "1234567890123456");
        len = 128/8;
        RAND_bytes(buf, len);
        printf("buf_len=%d\n", len);
        //printf("%s", dec);
        for(i=0; i<len; i++) {
            printf("%02x", (unsigned int)buf[i]&0xff);
        }
        printf("\n");


        printf("public_encrypt:\n");
        memset(enc, 0, sizeof(enc));
        enc_len = RSA_public_encrypt(len, buf, enc, rsa_pub, RSA_PKCS1_OAEP_PADDING);
        if( enc_len < 0 ) {
            printf("err=%ld\n", ERR_get_error());
            break;

        }
        printf("enc_len=%d\n", enc_len);
        for(i=0; i<enc_len; i++) {
            printf("%02x", (unsigned int)enc[i]&0xff);
        }
        printf("\n");


        printf("public_decrypt:\n");
        memset(dec, 0, sizeof(dec));
        dec_len = RSA_private_decrypt(enc_len, enc, dec, rsa_priv, RSA_PKCS1_OAEP_PADDING);
        if( dec_len < 0 ) {
            printf("err=%ld\n", ERR_get_error());
            break;

        }
        printf("dec_len=%d\n", dec_len);
        for(i=0; i<dec_len; i++) {
            printf("%02x", (unsigned int)dec[i]&0xff);
        }
        printf("\n");

        // blowfish
        BF_set_key(&key, dec_len, dec);

        i = 0;
        memcpy(ivec, ivec_orig, 8);
        memset(buf, 0, sizeof(buf));
        BF_cfb64_encrypt(enc, buf, enc_len, &key, ivec, &i, BF_ENCRYPT);

        printf("BF_cfb64_encrypt:\n");
        for(i=0; i<enc_len; i++) {
            printf("%02x", (unsigned int)buf[i]&0xff);
        }
        printf("\n");

        i = 0;
        memcpy(ivec, ivec_orig, 8);
        memset(enc, 0, sizeof(buf));
        BF_cfb64_encrypt(buf, enc, enc_len, &key, ivec, &i, BF_DECRYPT);

        printf("BF_cfb64_decrypt:\n");
        for(i=0; i<enc_len; i++) {
            printf("%02x", (unsigned int)enc[i]&0xff);
        }
        printf("\n");

    } while(0);

    if( rsa ) {
        RSA_free(rsa);
    }


    return 0;
}
Example #21
0
int p2pserver_rsa_extract_and_store_keypair_into_db(RSA* keypair){
	
	//Define local variables
		int return_code = 0;
		
		//SQLite3 vars
		sqlite3 *db;
		char *zErrMsg = 0;
		int rc;
		
		//RSA vars
		BIO *pri = BIO_new(BIO_s_mem());
		BIO *pub = BIO_new(BIO_s_mem());


	//Begin local logic
	
		/** **
		 * 	RSA Description
		 * 	Convert the keypair into a "ascii" format to save into the DB
		 ** **/
		 
		//RSA:
		PEM_write_bio_RSAPrivateKey(pri, keypair, NULL, NULL, 0, NULL, NULL);
		PEM_write_bio_RSAPublicKey(pub, keypair);

		//RSA: get size
		size_t pri_len = BIO_pending(pri);
		size_t pub_len = BIO_pending(pub);

		//Memory: Allocate
		char *pri_key = malloc(pri_len + 1);
		char *pub_key = malloc(pub_len + 1);

		//Memory: Write
		BIO_read(pri, pri_key, pri_len);
		BIO_read(pub, pub_key, pub_len);

		//Memory: Set end of string
		pri_key[pri_len] = '\0';
		pub_key[pub_len] = '\0';
	

		/** **
		* 	SQLite3 Description
		* 	Save the keypair into the database
		** **/
			//Open database file
			rc = sqlite3_open("./db/identity_list", &db);
			if(rc){
				g_print("Can't open database: %s\n", sqlite3_errmsg(db));
				
				return_code = -1;
			}
			
			if(return_code == 0){
				//Insert keypair into database
				const char * insert_keypair_sql;
				insert_keypair_sql = g_strdup_printf("INSERT INTO `keypair` (`public_key`, `private_key`) VALUES('%s', '%s');", pub_key ,pri_key);
				g_print("%s", insert_keypair_sql);
				rc = sqlite3_exec(db, insert_keypair_sql, 0, 0, &zErrMsg);
				
				if(rc != SQLITE_OK){
					return_code = -2;
				}else if(rc == SQLITE_OK){
					return_code = 1;
				}
			}

	
		//Close DB connection
		sqlite3_close(db);
		
	return return_code;
}
Example #22
0
void handle_std_input(Client* client)
{
    char command[64];
    read(STDIN_FILENO, command, 64);
    if(command[0] == 'a') {
        char file_name[32];
        sscanf(command+1, " %s", file_name);
        client->server_msg.buffer[0]='a';
        strcpy(client->server_msg.buffer+1, file_name);
        if(ENCRYPTION_ENABLED)
            encrypt_buffer_with_key(client->server_msg.buffer, client->server_public_key);
        if(client->maintainer_fd != -1)
            FD_SET(client->maintainer_fd, &(client->fd_write_set));
        logger("<Client><handle_std_input>adding this file to the server\n");
    } else if(command[0] == 'q') {
        if(client->maintainer_fd != -1) {
            close(client->maintainer_fd);
            logger("<Client><handle_std_input>closing my connection to the server\n");
            exit(0);
        }
    } else if(command[0] == 'd') {
        char file_name[32];
        sscanf(command+1, " %s", file_name);
        client->server_msg.buffer[0]='d';
        strcpy(client->server_msg.buffer+1, file_name);
        if(ENCRYPTION_ENABLED)
            encrypt_buffer_with_key(client->server_msg.buffer, client->server_public_key);
        if(client->maintainer_fd != -1)
            FD_SET(client->maintainer_fd, &(client->fd_write_set));
        logger("<Client><handle_std_input>do not serving this file anymore\n");
    } else if(command[0] == 'l') {
        int listen_port;
        sscanf(command, "l %d", &listen_port);
        logger("<testing> listen port : %d", listen_port);
        sprintf(client->server_msg.buffer, "l%d", listen_port);
        if(ENCRYPTION_ENABLED)
            encrypt_buffer_with_key(client->server_msg.buffer, client->server_public_key);
        if(client->maintainer_fd != -1)
            FD_SET(client->maintainer_fd, &(client->fd_write_set));
        client->listening_fd=socket(AF_INET, SOCK_STREAM, 0);
        fcntl(client->listening_fd, F_SETFL, O_NONBLOCK);
        int opt=TRUE;
        setsockopt(client->listening_fd, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(opt));
        struct sockaddr_in address;
        address.sin_family = AF_INET;
        address.sin_addr.s_addr = INADDR_ANY;
        address.sin_port = htons(listen_port);
        bind(client->listening_fd, (struct sockaddr *)&(address), sizeof(address));
        listen(client->listening_fd, 10);
        FD_SET(client->listening_fd, &(client->fd_read_set));
        client->fdmax = client->fdmax > client->listening_fd ? client->fdmax : client->listening_fd;
        logger("<Client><handle_std_input>sending my listening port to the server\n");
    } else if(command[0] == 's') {
        int server_port;
        char server_ip[16];
        sscanf(command, "s %s %d", server_ip, &server_port);
        logger("<Client><handle_std_input>server : %s:%d\n", server_ip, server_port);
        struct sockaddr_in remote_addr;
        memset(&remote_addr, 0, sizeof(remote_addr));
        remote_addr.sin_family = AF_INET;
        inet_pton(AF_INET, server_ip, &(remote_addr.sin_addr));
        remote_addr.sin_port = htons(server_port);
        client->maintainer_ip = remote_addr.sin_addr.s_addr;
        client->maintainer_port = server_port;
        client->maintainer_fd = socket(AF_INET, SOCK_STREAM, 0);
        connect(client->maintainer_fd, (struct sockaddr *)&remote_addr, sizeof(struct sockaddr));
        FD_SET(client->maintainer_fd, &(client->fd_read_set));
        client->fdmax = client->fdmax > client->maintainer_fd ? client->fdmax : client->maintainer_fd;
        logger("<Client><handle_std_input>connected to the server\n");
    } else if(command[0] == 'g') {
        logger("<Client><handle_std_input>getting file info\n");
        char file_name[32];
        sscanf(command+1, " %s", file_name);
        client->server_msg.buffer[0]='g';
        strcpy(client->server_msg.buffer+1, file_name);
        if(ENCRYPTION_ENABLED)
            encrypt_buffer_with_key(client->server_msg.buffer, client->server_public_key);
        if(client->maintainer_fd != -1) {
            FD_SET(client->maintainer_fd, &(client->fd_write_set));
            FD_SET(client->maintainer_fd, &(client->fd_read_set));
        }
    } else if(command[0] == 'p') {
        if(client->maintainer_fd != -1) {
            logger("<Client><handle_std_input>sending my public key\n");
            client->server_msg.buffer[0] = 'p';
            BIO *pub = BIO_new(BIO_s_mem());
            PEM_write_bio_RSAPublicKey(pub, client->keypair);
            size_t pub_len = BIO_pending(pub);
            char* pub_key = malloc(BUFFER_SIZE*2);
            BIO_read(pub, pub_key, pub_len);
            pub_key[pub_len] = '\0';
            for(int i=1; i<BUFFER_SIZE; ++i)
                client->server_msg.buffer[i] = pub_key[i-1];
            client->server_msg.dual_msg = TRUE;
            client->server_msg.extended_buffer = pub_key+BUFFER_SIZE-2;
            client->server_msg.extended_buffer[0] = 'k';
            if(client->maintainer_fd != -1)
                FD_SET(client->maintainer_fd, &(client->fd_write_set));
        }
    }
}
Example #23
0
int rsa_main(int argc, char **argv)
{
    ENGINE *e = NULL;
    BIO *out = NULL;
    RSA *rsa = NULL;
    const EVP_CIPHER *enc = NULL;
    char *infile = NULL, *outfile = NULL, *prog;
    char *passin = NULL, *passout = NULL, *passinarg = NULL, *passoutarg = NULL;
    int i;
    int informat = FORMAT_PEM, outformat = FORMAT_PEM, text = 0, check = 0;
    int noout = 0, modulus = 0, pubin = 0, pubout = 0, pvk_encr = 2, ret = 1;
    OPTION_CHOICE o;

    prog = opt_init(argc, argv, rsa_options);
    while ((o = opt_next()) != OPT_EOF) {
        switch (o) {
        case OPT_EOF:
        case OPT_ERR:
#ifdef OPENSSL_NO_RC4
        case OPT_PVK_STRONG:
        case OPT_PVK_WEAK:
        case OPT_PVK_NONE:
#endif
 opthelp:
            BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
            goto end;
        case OPT_HELP:
            opt_help(rsa_options);
            ret = 0;
            goto end;
        case OPT_INFORM:
            if (!opt_format(opt_arg(), OPT_FMT_ANY, &informat))
                goto opthelp;
            break;
        case OPT_IN:
            infile = opt_arg();
            break;
        case OPT_OUTFORM:
            if (!opt_format(opt_arg(), OPT_FMT_ANY, &outformat))
                goto opthelp;
            break;
        case OPT_OUT:
            outfile = opt_arg();
            break;
        case OPT_PASSIN:
            passinarg = opt_arg();
            break;
        case OPT_PASSOUT:
            passoutarg = opt_arg();
            break;
        case OPT_ENGINE:
            e = setup_engine(opt_arg(), 0);
            break;
        case OPT_PUBIN:
            pubin = 1;
            break;
        case OPT_PUBOUT:
            pubout = 1;
            break;
        case OPT_RSAPUBKEY_IN:
            pubin = 2;
            break;
        case OPT_RSAPUBKEY_OUT:
            pubout = 2;
            break;
#ifndef OPENSSL_NO_RC4
        case OPT_PVK_STRONG:
            pvk_encr = 2;
            break;
        case OPT_PVK_WEAK:
            pvk_encr = 1;
            break;
        case OPT_PVK_NONE:
            pvk_encr = 0;
            break;
#endif
        case OPT_NOOUT:
            noout = 1;
            break;
        case OPT_TEXT:
            text = 1;
            break;
        case OPT_MODULUS:
            modulus = 1;
            break;
        case OPT_CHECK:
            check = 1;
            break;
        case OPT_CIPHER:
            if (!opt_cipher(opt_unknown(), &enc))
                goto opthelp;
            break;
        }
    }
    argc = opt_num_rest();
    argv = opt_rest();

    if (!app_passwd(passinarg, passoutarg, &passin, &passout)) {
        BIO_printf(bio_err, "Error getting passwords\n");
        goto end;
    }

    if (check && pubin) {
        BIO_printf(bio_err, "Only private keys can be checked\n");
        goto end;
    }

    {
        EVP_PKEY *pkey;

        if (pubin) {
            int tmpformat = -1;
            if (pubin == 2) {
                if (informat == FORMAT_PEM)
                    tmpformat = FORMAT_PEMRSA;
                else if (informat == FORMAT_ASN1)
                    tmpformat = FORMAT_ASN1RSA;
            } else
                tmpformat = informat;

            pkey = load_pubkey(infile, tmpformat, 1, passin, e, "Public Key");
        } else
            pkey = load_key(infile, informat, 1, passin, e, "Private Key");

        if (pkey != NULL)
            rsa = EVP_PKEY_get1_RSA(pkey);
        EVP_PKEY_free(pkey);
    }

    if (rsa == NULL) {
        ERR_print_errors(bio_err);
        goto end;
    }

    out = bio_open_default(outfile, "w");
    if (out == NULL)
        goto end;

    if (text)
        if (!RSA_print(out, rsa, 0)) {
            perror(outfile);
            ERR_print_errors(bio_err);
            goto end;
        }

    if (modulus) {
        BIO_printf(out, "Modulus=");
        BN_print(out, rsa->n);
        BIO_printf(out, "\n");
    }

    if (check) {
        int r = RSA_check_key(rsa);

        if (r == 1)
            BIO_printf(out, "RSA key ok\n");
        else if (r == 0) {
            unsigned long err;

            while ((err = ERR_peek_error()) != 0 &&
                   ERR_GET_LIB(err) == ERR_LIB_RSA &&
                   ERR_GET_FUNC(err) == RSA_F_RSA_CHECK_KEY &&
                   ERR_GET_REASON(err) != ERR_R_MALLOC_FAILURE) {
                BIO_printf(out, "RSA key error: %s\n",
                           ERR_reason_error_string(err));
                ERR_get_error(); /* remove e from error stack */
            }
        }

        /* should happen only if r == -1 */
        if (r == -1 || ERR_peek_error() != 0) {
            ERR_print_errors(bio_err);
            goto end;
        }
    }

    if (noout) {
        ret = 0;
        goto end;
    }
    BIO_printf(bio_err, "writing RSA key\n");
    if (outformat == FORMAT_ASN1) {
        if (pubout || pubin) {
            if (pubout == 2)
                i = i2d_RSAPublicKey_bio(out, rsa);
            else
                i = i2d_RSA_PUBKEY_bio(out, rsa);
        } else
            i = i2d_RSAPrivateKey_bio(out, rsa);
    }
# ifndef OPENSSL_NO_RC4
    else if (outformat == FORMAT_NETSCAPE) {
        unsigned char *p, *pp;
        int size;

        i = 1;
        size = i2d_RSA_NET(rsa, NULL, NULL, 0);
        if ((p = OPENSSL_malloc(size)) == NULL) {
            BIO_printf(bio_err, "Memory allocation failure\n");
            goto end;
        }
        pp = p;
        i2d_RSA_NET(rsa, &p, NULL, 0);
        BIO_write(out, (char *)pp, size);
        OPENSSL_free(pp);
    }
# endif
    else if (outformat == FORMAT_PEM) {
        if (pubout || pubin) {
            if (pubout == 2)
                i = PEM_write_bio_RSAPublicKey(out, rsa);
            else
                i = PEM_write_bio_RSA_PUBKEY(out, rsa);
        } else
            i = PEM_write_bio_RSAPrivateKey(out, rsa,
                                            enc, NULL, 0, NULL, passout);
# if !defined(OPENSSL_NO_DSA) && !defined(OPENSSL_NO_RC4)
    } else if (outformat == FORMAT_MSBLOB || outformat == FORMAT_PVK) {
        EVP_PKEY *pk;
        pk = EVP_PKEY_new();
        EVP_PKEY_set1_RSA(pk, rsa);
        if (outformat == FORMAT_PVK)
            i = i2b_PVK_bio(out, pk, pvk_encr, 0, passout);
        else if (pubin || pubout)
            i = i2b_PublicKey_bio(out, pk);
        else
            i = i2b_PrivateKey_bio(out, pk);
        EVP_PKEY_free(pk);
# endif
    } else {
        BIO_printf(bio_err, "bad output format specified for outfile\n");
        goto end;
    }
    if (i <= 0) {
        BIO_printf(bio_err, "unable to write key\n");
        ERR_print_errors(bio_err);
    } else
        ret = 0;
 end:
    BIO_free_all(out);
    RSA_free(rsa);
    if (passin)
        OPENSSL_free(passin);
    if (passout)
        OPENSSL_free(passout);
    return (ret);
}
Example #24
0
int
rsa_main(int argc, char **argv)
{
	int ret = 1;
	RSA *rsa = NULL;
	int i;
	BIO *out = NULL;
	char *passin = NULL, *passout = NULL;

	if (single_execution) {
		if (pledge("stdio cpath wpath rpath tty", NULL) == -1) {
			perror("pledge");
			exit(1);
		}
	}

	memset(&rsa_config, 0, sizeof(rsa_config));
	rsa_config.pvk_encr = 2;
	rsa_config.informat = FORMAT_PEM;
	rsa_config.outformat = FORMAT_PEM;

	if (options_parse(argc, argv, rsa_options, NULL, NULL) != 0) {
		rsa_usage();
		goto end;
	}

	if (!app_passwd(bio_err, rsa_config.passargin, rsa_config.passargout,
	    &passin, &passout)) {
		BIO_printf(bio_err, "Error getting passwords\n");
		goto end;
	}
	if (rsa_config.check && rsa_config.pubin) {
		BIO_printf(bio_err, "Only private keys can be checked\n");
		goto end;
	}
	out = BIO_new(BIO_s_file());

	{
		EVP_PKEY *pkey;

		if (rsa_config.pubin) {
			int tmpformat = -1;
			if (rsa_config.pubin == 2) {
				if (rsa_config.informat == FORMAT_PEM)
					tmpformat = FORMAT_PEMRSA;
				else if (rsa_config.informat == FORMAT_ASN1)
					tmpformat = FORMAT_ASN1RSA;
			} else if (rsa_config.informat == FORMAT_NETSCAPE &&
			    rsa_config.sgckey)
				tmpformat = FORMAT_IISSGC;
			else
				tmpformat = rsa_config.informat;

			pkey = load_pubkey(bio_err, rsa_config.infile,
			    tmpformat, 1, passin, "Public Key");
		} else
			pkey = load_key(bio_err, rsa_config.infile,
			    (rsa_config.informat == FORMAT_NETSCAPE &&
			    rsa_config.sgckey ? FORMAT_IISSGC :
			    rsa_config.informat), 1, passin, "Private Key");

		if (pkey != NULL)
			rsa = EVP_PKEY_get1_RSA(pkey);
		EVP_PKEY_free(pkey);
	}

	if (rsa == NULL) {
		ERR_print_errors(bio_err);
		goto end;
	}
	if (rsa_config.outfile == NULL) {
		BIO_set_fp(out, stdout, BIO_NOCLOSE);
	} else {
		if (BIO_write_filename(out, rsa_config.outfile) <= 0) {
			perror(rsa_config.outfile);
			goto end;
		}
	}

	if (rsa_config.text)
		if (!RSA_print(out, rsa, 0)) {
			perror(rsa_config.outfile);
			ERR_print_errors(bio_err);
			goto end;
		}
	if (rsa_config.modulus) {
		BIO_printf(out, "Modulus=");
		BN_print(out, rsa->n);
		BIO_printf(out, "\n");
	}
	if (rsa_config.check) {
		int r = RSA_check_key(rsa);

		if (r == 1)
			BIO_printf(out, "RSA key ok\n");
		else if (r == 0) {
			unsigned long err;

			while ((err = ERR_peek_error()) != 0 &&
			    ERR_GET_LIB(err) == ERR_LIB_RSA &&
			    ERR_GET_FUNC(err) == RSA_F_RSA_CHECK_KEY &&
			    ERR_GET_REASON(err) != ERR_R_MALLOC_FAILURE) {
				BIO_printf(out, "RSA key error: %s\n",
				    ERR_reason_error_string(err));
				ERR_get_error();	/* remove e from error
							 * stack */
			}
		}
		if (r == -1 || ERR_peek_error() != 0) {	/* should happen only if
							 * r == -1 */
			ERR_print_errors(bio_err);
			goto end;
		}
	}
	if (rsa_config.noout) {
		ret = 0;
		goto end;
	}
	BIO_printf(bio_err, "writing RSA key\n");
	if (rsa_config.outformat == FORMAT_ASN1) {
		if (rsa_config.pubout || rsa_config.pubin) {
			if (rsa_config.pubout == 2)
				i = i2d_RSAPublicKey_bio(out, rsa);
			else
				i = i2d_RSA_PUBKEY_bio(out, rsa);
		} else
			i = i2d_RSAPrivateKey_bio(out, rsa);
	}
#ifndef OPENSSL_NO_RC4
	else if (rsa_config.outformat == FORMAT_NETSCAPE) {
		unsigned char *p, *pp;
		int size;

		i = 1;
		size = i2d_RSA_NET(rsa, NULL, NULL, rsa_config.sgckey);
		if ((p = malloc(size)) == NULL) {
			BIO_printf(bio_err, "Memory allocation failure\n");
			goto end;
		}
		pp = p;
		i2d_RSA_NET(rsa, &p, NULL, rsa_config.sgckey);
		BIO_write(out, (char *) pp, size);
		free(pp);
	}
#endif
	else if (rsa_config.outformat == FORMAT_PEM) {
		if (rsa_config.pubout || rsa_config.pubin) {
			if (rsa_config.pubout == 2)
				i = PEM_write_bio_RSAPublicKey(out, rsa);
			else
				i = PEM_write_bio_RSA_PUBKEY(out, rsa);
		} else
			i = PEM_write_bio_RSAPrivateKey(out, rsa,
			    rsa_config.enc, NULL, 0, NULL, passout);
#if !defined(OPENSSL_NO_DSA) && !defined(OPENSSL_NO_RC4)
	} else if (rsa_config.outformat == FORMAT_MSBLOB ||
	    rsa_config.outformat == FORMAT_PVK) {
		EVP_PKEY *pk;
		pk = EVP_PKEY_new();
		EVP_PKEY_set1_RSA(pk, rsa);
		if (rsa_config.outformat == FORMAT_PVK)
			i = i2b_PVK_bio(out, pk, rsa_config.pvk_encr, 0,
			    passout);
		else if (rsa_config.pubin || rsa_config.pubout)
			i = i2b_PublicKey_bio(out, pk);
		else
			i = i2b_PrivateKey_bio(out, pk);
		EVP_PKEY_free(pk);
#endif
	} else {
		BIO_printf(bio_err,
		    "bad output format specified for outfile\n");
		goto end;
	}
	if (i <= 0) {
		BIO_printf(bio_err, "unable to write key\n");
		ERR_print_errors(bio_err);
	} else
		ret = 0;

end:
	BIO_free_all(out);
	RSA_free(rsa);
	free(passin);
	free(passout);

	return (ret);
}
Example #25
0
		inline void rsa_key::write_public_key(bio::bio_ptr bio) const
		{
			error::throw_error_if_not(PEM_write_bio_RSAPublicKey(bio.raw(), ptr().get()) != 0);
		}
Example #26
-1
int main()
{

  RSA *rsa;
  BIO *out;
  int err;

  rsa = RSA_generate_key(KEY_SIZE, PUBXP, NULL, NULL);
  if(rsa == NULL) {
    printf("Key generation failed\n");
    return 1;
  }

  if ((out = BIO_new(BIO_s_file())) == NULL) {
    printf("Unable to create BIO for output\n");
    return 1;
  }

  BIO_set_fp(out, stdout, BIO_NOCLOSE);

  PEM_write_bio_RSAPrivateKey(out, rsa, NULL, NULL, 0, NULL, NULL);
  printf("\n");
  PEM_write_bio_RSAPublicKey(out, rsa);
  
  RSA_free(rsa);
  BIO_free_all(out);
  
  return 0;
}