Esempio n. 1
0
int
write_key_pem_public(FILE *fp, struct ccn_pkey *private_key_ccn)
{
	RSA *private_key_rsa;
	unsigned long err;

	private_key_rsa = EVP_PKEY_get1_RSA((EVP_PKEY*) private_key_ccn);
	if (!private_key_rsa) {
		err = ERR_get_error();
		PyErr_Format(g_PyExc_CCNKeyError, "Unable to obtain EVP PKEY: %s",
				ERR_reason_error_string(err));
		return -1;
	}

	if (!PEM_write_RSAPublicKey(fp, private_key_rsa)) {
		err = ERR_get_error();
		RSA_free(private_key_rsa);
		PyErr_Format(g_PyExc_CCNKeyError, "Unable to write Public Key: %s",
				ERR_reason_error_string(err));
		return -1;
	}
	RSA_free(private_key_rsa);

	return 0;
}
Esempio n. 2
0
void SavePublicKey(const char *user, const char *digest, const RSA *key)
{
    char keyname[CF_MAXVARSIZE], filename[CF_BUFSIZE];
    struct stat statbuf;
    FILE *fp;
    int err;

    snprintf(keyname, CF_MAXVARSIZE, "%s-%s", user, digest);

    snprintf(filename, CF_BUFSIZE, "%s/ppkeys/%s.pub", CFWORKDIR, keyname);
    MapName(filename);

    if (stat(filename, &statbuf) != -1)
    {
        return;
    }

    Log(LOG_LEVEL_VERBOSE, "Saving public key to file '%s'", filename);

    if ((fp = fopen(filename, "w")) == NULL)
    {
        Log(LOG_LEVEL_ERR, "Unable to write a public key '%s'. (fopen: %s)", filename, GetErrorStr());
        return;
    }

    if (!PEM_write_RSAPublicKey(fp, key))
    {
        err = ERR_get_error();
        Log(LOG_LEVEL_ERR, "Error saving public key to '%s'. (PEM_write_RSAPublicKey: %s)", filename, ERR_reason_error_string(err));
    }

    fclose(fp);
}
Esempio n. 3
0
static void writeKeys(char *hostname) {
  
  /* Create a private and public key and save it to disk */
  struct stat dir_stat; 
  stat("data", &dir_stat);
    
  if (!(S_ISDIR(dir_stat.st_mode))) { 
    mkdir("data",S_IXUSR|S_IRUSR|S_IWUSR);
  }
  RSA *priv_key;
  priv_key = RSA_new();
  priv_key = RSA_generate_key(512,656537,NULL,NULL);
  RSA_check_key(priv_key);

  FILE *fp;
  char filename[256];
  sprintf(filename,"data/%s%s",hostname,"-pr-key.txt");
  fp = fopen(filename,"w");
  PEM_write_RSAPrivateKey(fp, priv_key, NULL, NULL, 0 ,0, NULL);
  fclose(fp);

  char filename2[256];
  sprintf(filename2,"data/%s%s",hostname,"-pub-key.txt");
  FILE *fp3;
  fp3 = fopen(filename2,"w");
  PEM_write_RSAPublicKey(fp3, priv_key);
  fclose(fp3);
}
Esempio n. 4
0
int main(int argc,char *argv[]) {

  RSA *r = NULL;
  FILE *priv_output_file;
  FILE *pub_output_file;
  int key_len;
  char *priv_file_name;
  char *pub_file_name;

  char priv_suffix[] = ".priv";
  char pub_suffix[] = ".pub";
  int len;

  if (argc != 4) {
    printf("Usage %s <key_file> <keylen> <password protect flag>\n",argv[0]);
    exit(0);
  }
  
  priv_file_name = malloc(40);
  pub_file_name = malloc(40);
  len = strlen(argv[1]);
  memcpy(priv_file_name, argv[1], len);
  memcpy(pub_file_name, argv[1], len);
  memcpy(priv_file_name+len, priv_suffix, 10);
  memcpy(pub_file_name+len, pub_suffix, 9);

  printf("%s %s\n",priv_file_name,pub_file_name);

  key_len = atoi(argv[2]);

  r = RSA_generate_key(key_len, RSA_EXPONENT, RSA_CALLBACK, RSA_CB_ARGS);
  
  if ((priv_output_file = fopen(priv_file_name, "w")) == NULL)
           fprintf(stderr, "Cannot open %s\n", argv[1]);
    
  if ((pub_output_file = fopen(pub_file_name, "w")) == NULL)
           fprintf(stderr, "Cannot open %s\n", argv[1]);

  if (strcmp(argv[3],"0")==0) {
    if (PEM_write_RSAPrivateKey(priv_output_file,r,EVP_des_ede3_cbc(),NULL,0,NULL,NULL) != 1) {
      printf("Error writing the private key\n");
    }
  }
  else {
     if (PEM_write_RSAPrivateKey(priv_output_file,r,NULL,NULL,0,NULL,NULL) != 1) {
       printf("Error writing the private key\n");
     }
  }
  if (PEM_write_RSAPublicKey(pub_output_file,r) != 1) {
    printf("Error writing the public key\n");
  }
  fclose(priv_output_file);
  fclose(pub_output_file);
  exit(0);
}
Esempio n. 5
0
/*
  Generate a public/private RSA keypair, and ask for a file to store
  them in.
*/
static bool keygen(int bits) {
	RSA *rsa_key;
	FILE *f;
	char *name = get_name();
	char *pubname, *privname;

	fprintf(stderr, "Generating %d bits keys:\n", bits);
	rsa_key = RSA_generate_key(bits, 0x10001, indicator, NULL);

	if(!rsa_key) {
		fprintf(stderr, "Error during key generation!\n");
		return false;
	} else
		fprintf(stderr, "Done.\n");

	xasprintf(&privname, "%s/rsa_key.priv", confbase);
	f = ask_and_open(privname, "private RSA key");
	free(privname);

	if(!f)
		return false;

#ifdef HAVE_FCHMOD
	/* Make it unreadable for others. */
	fchmod(fileno(f), 0600);
#endif
		
	fputc('\n', f);
	PEM_write_RSAPrivateKey(f, rsa_key, NULL, NULL, 0, NULL, NULL);
	fclose(f);

	if(name)
		xasprintf(&pubname, "%s/hosts/%s", confbase, name);
	else
		xasprintf(&pubname, "%s/rsa_key.pub", confbase);

	f = ask_and_open(pubname, "public RSA key");
	free(pubname);

	if(!f)
		return false;

	fputc('\n', f);
	PEM_write_RSAPublicKey(f, rsa_key);
	fclose(f);
	free(name);

	return true;
}
Esempio n. 6
0
void SavePublicKey(const char *user, const char *digest, const RSA *key)
{
    char keyname[CF_MAXVARSIZE], filename[CF_BUFSIZE];
    struct stat statbuf;
    FILE *fp;
    int ret;

    ret = snprintf(keyname, sizeof(keyname), "%s-%s", user, digest);
    if (ret >= sizeof(keyname))
    {
        Log(LOG_LEVEL_ERR, "USERNAME-KEY (%s-%s) string too long!",
            user, digest);
        return;
    }

    ret = snprintf(filename, sizeof(filename), "%s/ppkeys/%s.pub",
                   CFWORKDIR, keyname);
    if (ret >= sizeof(filename))
    {
        Log(LOG_LEVEL_ERR, "Filename too long!");
        return;
    }

    MapName(filename);
    if (stat(filename, &statbuf) != -1)
    {
        return;
    }

    Log(LOG_LEVEL_VERBOSE, "Saving public key to file '%s'", filename);

    if ((fp = fopen(filename, "w")) == NULL)
    {
        Log(LOG_LEVEL_ERR, "Unable to write a public key '%s'. (fopen: %s)", filename, GetErrorStr());
        return;
    }

    if (!PEM_write_RSAPublicKey(fp, key))
    {
        Log(LOG_LEVEL_ERR,
            "Error saving public key to '%s'. (PEM_write_RSAPublicKey: %s)",
            filename, CryptoLastErrorString());
    }

    fclose(fp);
}
Esempio n. 7
0
int COsslKey::SavePublicKey( const sqbind::stdString &sPublic )
{_STT();

	if ( !m_pkey || !sPublic.length() )
		return 0;

	oex::CStr8 name = oexStrToMb( oex::CStr( sPublic.c_str(), sPublic.length() ) );
	FILE *fp = fopen( ( oex::CStr8() << name ).Ptr(), "w" );
	if ( !fp )
		oexERROR( oexGetLastError(), oexMks( oexT( "fopen( '" ), oexMbToStr( name ), oexT( "' ) failed" ) ) );
	else
	{
		PEM_write_RSAPublicKey( fp, m_pkey->pkey.rsa );

		fclose( fp );

	} // end else

	return 1;
}
Esempio n. 8
0
int main(int argc, char **argv) {
  RSA *keypair = RSA_new();
  BIGNUM *n = BN_new();
  BIGNUM *e = BN_new();

  if(argc != 3) {
    printf("Usage : %s <n> <e>\n", argv[0]);
    return 1;
  }

  BN_dec2bn(&n, argv[1]);
  BN_dec2bn(&e, argv[2]);

  RSA_set0_key(keypair, n, e, NULL);

  PEM_write_RSAPublicKey(stdout, keypair);
  RSA_free(keypair);

  return 0;
}
Esempio n. 9
0
int main(int argc, char *argv[])
{
	RSA *key;
	FILE *fp;
	int keylen = 0;
	if (argc != 2) {
		fprintf(stderr, "Error: too many/few arguments.\nUsage: %s <numbits>\n", argv[0]);
		return 1;
	}
	
	keylen = atoi(argv[1]);
	if ((key = RSA_generate_key(keylen, 3, NULL, NULL)) == NULL) {
		fprintf(stderr, "%s\n", ERR_error_string(ERR_get_error(), NULL));
		return 1;
	}
	
	if (RSA_check_key(key) < 1)
	{
		fprintf(stderr, "Error: Problems while generating RSA Key.\nRetry.\n");
		return 1;
	}
	
	fp = fopen(SECFILE,"w");
	if (PEM_write_RSAPrivateKey(fp, key, NULL, NULL, 0, 0, NULL) == 0)
	{
		fprintf(stderr, "Error: problems while writing RSA Private Key.\n");
		return 1;
	}
	fclose(fp);
	
	fp = fopen(PUBFILE, "w");
	if (PEM_write_RSAPublicKey(fp, key) == 0) {
		fprintf(stderr, "Error: problems while writing RSA Public Key.\n");
		return 1;
	}
	fclose(fp);
	RSA_free(key);
	printf("RSA key generated.\nLenght (bits) = %d\n", keylen);
	return 0;
}
Esempio n. 10
0
int COsslKey::SaveKeys( const sqbind::stdString &sPrivate, const sqbind::stdString &sPublic )
{_STT();

	// Public key?
	if ( m_pkey )
	{
		oex::CStr8 name = oexStrToMb( oex::CStr( sPublic.c_str(), sPublic.length() ) );
		FILE *fp = fopen( ( oex::CStr8() << name ).Ptr(), "w" );
		if ( !fp )
			oexERROR( oexGetLastError(), oexMks( oexT( "fopen( '" ), oexMbToStr( name ), oexT( "' ) failed" ) ) );
		else
		{
			PEM_write_RSAPublicKey( fp, m_pkey->pkey.rsa );

			fclose( fp );

		} // end else

	} // end if

	// Private key?
	if ( m_pkey )
	{
		oex::CStr8 name = oexStrToMb( oex::CStr( sPrivate.c_str(), sPrivate.length() ) );
		FILE *fp = fopen( ( oex::CStr8() << name ).Ptr(), "w" );
		if ( !fp )
			oexERROR( oexGetLastError(), oexMks( oexT( "fopen( '" ), oexMbToStr( name ), oexT( "' ) failed" ) ) );
		else
		{

			PEM_write_RSAPrivateKey( fp, m_pkey->pkey.rsa, oexNULL, oexNULL, 0, oexNULL, oexNULL );

			fclose( fp );

		} // end else

	} // end if

	return 1;
}
Esempio n. 11
0
void SavePublicKey(char *user, char *ipaddress, char *digest, RSA *key)
{
    char keyname[CF_MAXVARSIZE], filename[CF_BUFSIZE];
    struct stat statbuf;
    FILE *fp;
    int err;

    CfDebug("SavePublicKey %s\n", ipaddress);

    snprintf(keyname, CF_MAXVARSIZE, "%s-%s", user, digest);

    snprintf(filename, CF_BUFSIZE, "%s/ppkeys/%s.pub", CFWORKDIR, keyname);
    MapName(filename);

    if (cfstat(filename, &statbuf) != -1)
    {
        return;
    }

    CfOut(OUTPUT_LEVEL_VERBOSE, "", "Saving public key %s\n", filename);

    if ((fp = fopen(filename, "w")) == NULL)
    {
        CfOut(OUTPUT_LEVEL_ERROR, "fopen", "Unable to write a public key %s", filename);
        return;
    }

    ThreadLock(cft_system);

    if (!PEM_write_RSAPublicKey(fp, key))
    {
        err = ERR_get_error();
        CfOut(OUTPUT_LEVEL_ERROR, "PEM_write", "Error saving public key %s = %s\n", filename, ERR_reason_error_string(err));
    }

    ThreadUnlock(cft_system);
    fclose(fp);
}
Esempio n. 12
0
        void RSAKey::writeToPEMKeyFile(const std::string& filename, PEMPassphraseCallback callback, void* userdata) const
        {
            FILE* fp = fopen(filename.c_str(), "w+");

            if (fp == NULL)
            {
                THROW_EXCEPTION_WITH_LOG(Exception::exception, "Cannot open the file.");
            }

            int result = 0;

            if (hasPrivateCompound())
            {
                result = PEM_write_RSAPrivateKey(fp, d_rsa.get(), NULL, NULL, 0, callback, userdata);
            }
            else
            {
                result = PEM_write_RSAPublicKey(fp, d_rsa.get());
            }

            fclose(fp);

            EXCEPTION_ASSERT_WITH_LOG(result != 0, OpenSSLException, "Cannot write PEM file");
        }
Esempio n. 13
0
File: tincd.c Progetto: Rumko/tinc
/*
  Generate a public/private RSA keypair, and ask for a file to store
  them in.
*/
static bool keygen(int bits) {
	RSA *rsa_key;
	FILE *f;
	char *name = NULL;
	char *filename;

	get_config_string(lookup_config(config_tree, "Name"), &name);

	if(name && !check_id(name)) {
		fprintf(stderr, "Invalid name for myself!\n");
		return false;
	}

	fprintf(stderr, "Generating %d bits keys:\n", bits);
	rsa_key = RSA_generate_key(bits, 0x10001, indicator, NULL);

	if(!rsa_key) {
		fprintf(stderr, "Error during key generation!\n");
		return false;
	} else
		fprintf(stderr, "Done.\n");

	xasprintf(&filename, "%s/rsa_key.priv", confbase);
	f = ask_and_open(filename, "private RSA key");

	if(!f)
		return false;

	if(disable_old_keys(f))
		fprintf(stderr, "Warning: old key(s) found and disabled.\n");
  
#ifdef HAVE_FCHMOD
	/* Make it unreadable for others. */
	fchmod(fileno(f), 0600);
#endif
		
	fputc('\n', f);
	PEM_write_RSAPrivateKey(f, rsa_key, NULL, NULL, 0, NULL, NULL);
	fclose(f);
	free(filename);

	if(name)
		xasprintf(&filename, "%s/hosts/%s", confbase, name);
	else
		xasprintf(&filename, "%s/rsa_key.pub", confbase);

	f = ask_and_open(filename, "public RSA key");

	if(!f)
		return false;

	if(disable_old_keys(f))
		fprintf(stderr, "Warning: old key(s) found and disabled.\n");

	fputc('\n', f);
	PEM_write_RSAPublicKey(f, rsa_key);
	fclose(f);
	free(filename);
	if(name)
		free(name);

	return true;
}
Esempio n. 14
0
int main(int argc, char **argv) {
  RSA *keypair = RSA_new();
  BN_CTX *ctx = BN_CTX_new();
  BN_CTX_start(ctx);

  BIGNUM *n = BN_new();
  BIGNUM *d = BN_new();
  BIGNUM *e = BN_new();
  BIGNUM *p = BN_new();
  BIGNUM *q = BN_new();
  BIGNUM *dmp1 = BN_new();
  BIGNUM *dmq1 = BN_new();
  BIGNUM *iqmp = BN_new();
  BIGNUM *r0 = BN_CTX_get(ctx);
  BIGNUM *r1 = BN_CTX_get(ctx);
  BIGNUM *r2 = BN_CTX_get(ctx);
  BIGNUM *r3 = BN_CTX_get(ctx);

  if(argc != 4) {
    printf("Usage : %s <p> <q> <e>\n", argv[0]);
    return 1;
  }

  BN_dec2bn(&p, argv[1]);
  BN_dec2bn(&q, argv[2]);
  BN_dec2bn(&e, argv[3]);

  if(BN_cmp(p,q) < 0) {
    BIGNUM *tmp = p;

    p = q;
    q = tmp;
  }

  BN_mul(n,p,q,ctx);
  BN_sub(r1,p,BN_value_one());
  BN_sub(r2,q,BN_value_one());
  BN_mul(r0,r1,r2,ctx);
  BN_mod_inverse(d,e,r0,ctx);
  BN_mod(dmp1, d, r1, ctx);
  BN_mod(dmp1, d, r2, ctx);

  BN_mod_inverse(iqmp,q,p,ctx);

  keypair->n = n;
  keypair->d = d;
  keypair->e = e;
  keypair->p = p;
  keypair->q = q;
  keypair->dmq1 = dmq1;
  keypair->dmp1 = dmp1;
  keypair->iqmp = iqmp;

  PEM_write_RSAPrivateKey(stdout, keypair, NULL, NULL, 0, NULL, NULL);
  PEM_write_RSAPublicKey(stdout, keypair);
  BN_CTX_end(ctx);
  BN_CTX_free(ctx);
  RSA_free(keypair);

  return 0;
}
Esempio n. 15
0
//-------------------------------------------------------------------------------------
bool KBE_RSA::generateKey(const std::string& pubkeyname, 
						  const std::string& prikeyname, int keySize, int e)
{
	KBE_ASSERT(rsa_public == NULL && rsa_private == NULL);
	
	RSA* rsa = NULL;
    FILE *fp = NULL;

	if ((rsa = RSA_generate_key(keySize, e, NULL, NULL)) == NULL) 
	{
		ERR_load_crypto_strings();
		char err[1024];
		char* errret = ERR_error_string(ERR_get_error(), err);
		ERROR_MSG(fmt::format("KBE_RSA::generateKey: RSA_generate_key error({} : {})\n",
			errret, err));

		return false;
	}

	if (!RSA_check_key(rsa)) 
	{
		ERROR_MSG("KBE_RSA::generateKey: invalid RSA Key.\n");
		RSA_free(rsa);
		return false;
	}

	fp = fopen(prikeyname.c_str(), "w");
	if (!fp) {
		RSA_free(rsa);
		return false;
	}

	if (!PEM_write_RSAPrivateKey(fp, static_cast<RSA*>(rsa), NULL, NULL, 0, 0, NULL)) 
	{
		ERR_load_crypto_strings();
		char err[1024];
		char* errret = ERR_error_string(ERR_get_error(), err);
		ERROR_MSG(fmt::format("KBE_RSA::generateKey: PEM_write_RSAPrivateKey error({} : {})\n",
			errret, err));

		fclose(fp);
		RSA_free(rsa);
		return false;
	}

	fclose(fp);
	fp = fopen(pubkeyname.c_str(), "w");
	if (!fp) {
		RSA_free(rsa);
		return false;
	}

	if (!PEM_write_RSAPublicKey(fp, static_cast<RSA*>(rsa))) 
	{
		ERR_load_crypto_strings();
		char err[1024];
		char* errret = ERR_error_string(ERR_get_error(), err);
		ERROR_MSG(fmt::format("KBE_RSA::generateKey: PEM_write_RSAPublicKey error({} : {})\n",
			errret, err));

		fclose(fp);
		RSA_free(rsa);
		return false;
	}

	INFO_MSG(fmt::format("KBE_RSA::generateKey: RSA key generated. keysize({}) bits.\n", keySize));

	RSA_free(rsa);
	fclose(fp);

	return loadPrivate(prikeyname) && loadPublic(pubkeyname);
}
Esempio n. 16
0
/*
 * generate public/private RSA keypairs for all hosts that don't have one.
 */
static int
keygen (int bits)
{
  RSA *rsa_key;
  FILE *f;
  char *name = NULL;
  char *fname;

  asprintf (&fname, "%s/hostkeys", confbase);
  mkdir (fname, 0700);
  free (fname);

  asprintf (&fname, "%s/pubkey", confbase);
  mkdir (fname, 0700);
  free (fname);

  for (configuration::node_vector::iterator i = conf.nodes.begin (); i != conf.nodes.end (); ++i)
    {
      conf_node *node = *i;

      asprintf (&fname, "%s/pubkey/%s", confbase, node->nodename);

      f = fopen (fname, "a");

      /* some libcs are buggy and require an extra seek to the end */
      if (!f || fseek (f, 0, SEEK_END))
        {
          perror (fname);
          exit (EXIT_FAILURE);
        }

      if (ftell (f))
        {
          if (!quiet)
            fprintf (stderr, "'%s' already exists, skipping this node %d\n",
                     fname, quiet);

          fclose (f);
          continue;
        }

      fprintf (stderr, _("generating %d bits key for %s:\n"), bits,
               node->nodename);

      rsa_key = RSA_generate_key (bits, 0xFFFF, indicator, NULL);

      if (!rsa_key)
        {
          fprintf (stderr, _("error during key generation!\n"));
          return -1;
        }
      else
        fprintf (stderr, _("Done.\n"));

      require (PEM_write_RSAPublicKey (f, rsa_key));
      fclose (f);
      free (fname);

      asprintf (&fname, "%s/hostkeys/%s", confbase, node->nodename);

      f = fopen (fname, "a");
      if (!f)
        {
          perror (fname);
          exit (EXIT_FAILURE);
        }

      require (PEM_write_RSAPrivateKey (f, rsa_key, NULL, NULL, 0, NULL, NULL));
      fclose (f);
      free (fname);
    }

  return 0;
}
Esempio n. 17
0
    int main(int argc, char *argv[])
    {
        int err = 0;
        int v;
        RSA *key;
        unsigned char ptext[256];
        unsigned char ctext[256];
        static unsigned char ptext_ex[] = "12345678";
        unsigned char ctext_ex[256];
        int plen;
        int clen = 0;
        int num;
        int n;
        int i;
        EVP_PKEY *pkey;

        printf("ptext_ex: %s\n", ptext_ex);
        {
            key = RSA_new();
            key5(key);

            plen = sizeof(ptext_ex) - 1;
            num = RSA_private_encrypt(plen, ptext_ex, ctext, key,
                    RSA_PKCS1_PADDING);
            if (num != 128)   //模数长度
            {
                printf("PKCS#1 v1.5 encryption failed!\n");
                err=1;
                goto next;
            }

            //加密后的数据
            printf("encrypted text: \n");
            for (i = 0; i < num; i++)
            {
                printf("\\x%02x", ctext[i]);
            }
            printf("\n");

            printf("RSA_private_encrypt num: %d\n", num);

            num = RSA_public_decrypt(num, ctext, ptext, key,
                    RSA_PKCS1_PADDING);
            if (num != plen || memcmp(ptext, ptext_ex, num) != 0)
            {
                printf("PKCS#1 v1.5 decryption failed!\n");
                err=1;
            }
            else
                printf("PKCS #1 v1.5 encryption/decryption ok\n");

            printf("RSA_public_decrypt num: %d\n", num);
            ptext[num] = '\0';    //字符串结尾
            printf("ptext: %s\n", ptext);

    next:
            //公钥和私钥输出为 PEM 格式:
            PEM_write_RSAPrivateKey(stdout, key, NULL, NULL, 0, NULL, NULL);
            PEM_write_RSAPublicKey(stdout, key);

            //释放申请的内存
            RSA_free(key);
        }

        if (err) printf("ERROR: %d\n", err);
        return err;
    }
Esempio n. 18
0
void KeepKeyPromises(const char *public_key_file, const char *private_key_file)
{
    unsigned long err;
#ifdef OPENSSL_NO_DEPRECATED
    RSA *pair = RSA_new();
    BIGNUM *rsa_bignum = BN_new();
#else
    RSA *pair;
#endif
    FILE *fp;
    struct stat statbuf;
    int fd;
    static char *passphrase = "Cfengine passphrase";
    const EVP_CIPHER *cipher;
    char vbuff[CF_BUFSIZE];

    cipher = EVP_des_ede3_cbc();

    if (stat(public_key_file, &statbuf) != -1)
    {
        printf("A key file already exists at %s\n", public_key_file);
        return;
    }

    if (stat(private_key_file, &statbuf) != -1)
    {
        printf("A key file already exists at %s\n", private_key_file);
        return;
    }

    printf("Making a key pair for cfengine, please wait, this could take a minute...\n");

#ifdef OPENSSL_NO_DEPRECATED
    BN_set_word(rsa_bignum, 35);

    if (!RSA_generate_key_ex(pair, 2048, rsa_bignum, NULL))
#else
    pair = RSA_generate_key(2048, 35, NULL, NULL);

    if (pair == NULL)
#endif
    {
        err = ERR_get_error();
        Log(LOG_LEVEL_ERR, "Unable to generate key '%s'", ERR_reason_error_string(err));
        return;
    }

    fd = open(private_key_file, O_WRONLY | O_CREAT | O_TRUNC, 0600);

    if (fd < 0)
    {
        Log(LOG_LEVEL_ERR, "Open '%s' failed. (open: %s)", private_key_file, GetErrorStr());
        return;
    }

    if ((fp = fdopen(fd, "w")) == NULL)
    {
        Log(LOG_LEVEL_ERR, "Couldn't open private key '%s'. (fdopen: %s)", private_key_file, GetErrorStr());
        close(fd);
        return;
    }

    Log(LOG_LEVEL_VERBOSE, "Writing private key to '%s'", private_key_file);

    if (!PEM_write_RSAPrivateKey(fp, pair, cipher, passphrase, strlen(passphrase), NULL, NULL))
    {
        err = ERR_get_error();
        Log(LOG_LEVEL_ERR, "Couldn't write private key. (PEM_write_RSAPrivateKey: %s)", ERR_reason_error_string(err));
        return;
    }

    fclose(fp);

    fd = open(public_key_file, O_WRONLY | O_CREAT | O_TRUNC, 0600);

    if (fd < 0)
    {
        Log(LOG_LEVEL_ERR, "Unable to open public key '%s'. (open: %s)",
            public_key_file, GetErrorStr());
        return;
    }

    if ((fp = fdopen(fd, "w")) == NULL)
    {
        Log(LOG_LEVEL_ERR, "Open '%s' failed. (fdopen: %s)", public_key_file, GetErrorStr());
        close(fd);
        return;
    }

    Log(LOG_LEVEL_VERBOSE, "Writing public key to file '%s'", public_key_file);

    if (!PEM_write_RSAPublicKey(fp, pair))
    {
        err = ERR_get_error();
        Log(LOG_LEVEL_ERR, "Unable to write public key. (PEM_write_RSAPublicKey: %s)", ERR_reason_error_string(err));
        return;
    }

    fclose(fp);

    snprintf(vbuff, CF_BUFSIZE, "%s/randseed", CFWORKDIR);
    RAND_write_file(vbuff);
    chmod(vbuff, 0644);
}
Esempio n. 19
0
File: tincd.c Progetto: seehuhn/tinc
/*
  Generate a public/private RSA keypair, and ask for a file to store
  them in.
*/
static bool keygen(int bits) {
	BIGNUM *e = NULL;
	RSA *rsa_key;
	FILE *f;
	char filename[PATH_MAX];
	BN_GENCB *cb;
	int result;

	fprintf(stderr, "Generating %d bits keys:\n", bits);

	cb = BN_GENCB_new();

	if(!cb) {
		abort();
	}

	BN_GENCB_set(cb, indicator, NULL);

	rsa_key = RSA_new();

	if(BN_hex2bn(&e, "10001") == 0) {
		abort();
	}

	if(!rsa_key || !e) {
		abort();
	}

	result = RSA_generate_key_ex(rsa_key, bits, e, cb);

	BN_free(e);
	BN_GENCB_free(cb);

	if(!result) {
		fprintf(stderr, "Error during key generation!\n");
		RSA_free(rsa_key);
		return false;
	} else {
		fprintf(stderr, "Done.\n");
	}

	snprintf(filename, sizeof(filename), "%s/rsa_key.priv", confbase);
	f = ask_and_open(filename, "private RSA key");

	if(!f) {
		RSA_free(rsa_key);
		return false;
	}

#ifdef HAVE_FCHMOD
	/* Make it unreadable for others. */
	fchmod(fileno(f), 0600);
#endif

	fputc('\n', f);
	PEM_write_RSAPrivateKey(f, rsa_key, NULL, NULL, 0, NULL, NULL);
	fclose(f);

	char *name = get_name();

	if(name) {
		snprintf(filename, sizeof(filename), "%s/hosts/%s", confbase, name);
		free(name);
	} else {
		snprintf(filename, sizeof(filename), "%s/rsa_key.pub", confbase);
	}

	f = ask_and_open(filename, "public RSA key");

	if(!f) {
		RSA_free(rsa_key);
		return false;
	}

	fputc('\n', f);
	PEM_write_RSAPublicKey(f, rsa_key);
	fclose(f);

	RSA_free(rsa_key);

	return true;
}
Esempio n. 20
0
int main(int argc,char *argv[]) {

  RSA *r = NULL;
  FILE *priv_output_file;
  FILE *pub_output_file;
  int key_len;
  char *priv_file_name;
  char *pub_file_name;

  char priv_suffix[] = "_priv.txt";
  char pub_suffix[] = "_pub.txt";
  int len;

  if (argc != 4) {
    printf("Usage %s <key_file> <keylen> <password protect flag>\n",argv[0]);
    exit(0);
  }
  
  priv_file_name = malloc(40);
  pub_file_name = malloc(40);
  len = strlen(argv[1]);
  memcpy(priv_file_name, argv[1], len);
  memcpy(pub_file_name, argv[1], len);
  memcpy(priv_file_name+len, priv_suffix, 10);
  memcpy(pub_file_name+len, pub_suffix, 9);

  printf("%s %s\n",priv_file_name,pub_file_name);

  key_len = atoi(argv[2]);

//daveti: add time measurement for this function call
struct timeval tpstart,tpend;
float timeuse = 0;
gettimeofday(&tpstart,NULL);

  r = RSA_generate_key(key_len, RSA_EXPONENT, RSA_CALLBACK, RSA_CB_ARGS);

gettimeofday(&tpend,NULL);
timeuse=1000000*(tpend.tv_sec-tpstart.tv_sec)+tpend.tv_usec-tpstart.tv_usec;
timeuse/=1000000;
printf("Total time on crypto_genkeypair() is [%f] ms\n", timeuse);
  
  if ((priv_output_file = fopen(priv_file_name, "w")) == NULL)
           fprintf(stderr, "Cannot open %s\n", argv[1]);
    
  if ((pub_output_file = fopen(pub_file_name, "w")) == NULL)
           fprintf(stderr, "Cannot open %s\n", argv[1]);

  if (strcmp(argv[3],"0")==0) {
    if (PEM_write_RSAPrivateKey(priv_output_file,r,EVP_des_ede3_cbc(),NULL,0,NULL,NULL) != 1) {
      printf("Error writing the private key\n");
    }
  }
  else {
     if (PEM_write_RSAPrivateKey(priv_output_file,r,NULL,NULL,0,NULL,NULL) != 1) {
       printf("Error writing the private key\n");
     }
  }
  if (PEM_write_RSAPublicKey(pub_output_file,r) != 1) {
    printf("Error writing the public key\n");
  }
  close(priv_output_file);
  close(pub_output_file);
  exit(0);
}
Esempio n. 21
0
static void KeepKeyPromises(void)
{
    unsigned long err;
    RSA *pair;
    FILE *fp;
    struct stat statbuf;
    int fd;
    static char *passphrase = "Cfengine passphrase";
    const EVP_CIPHER *cipher;
    char vbuff[CF_BUFSIZE];

    NewScope("common");

    cipher = EVP_des_ede3_cbc();

    if (cfstat(CFPUBKEYFILE, &statbuf) != -1)
    {
        CfOut(cf_cmdout, "", "A key file already exists at %s\n", CFPUBKEYFILE);
        return;
    }

    if (cfstat(CFPRIVKEYFILE, &statbuf) != -1)
    {
        CfOut(cf_cmdout, "", "A key file already exists at %s\n", CFPRIVKEYFILE);
        return;
    }

    printf("Making a key pair for cfengine, please wait, this could take a minute...\n");

    pair = RSA_generate_key(2048, 35, NULL, NULL);

    if (pair == NULL)
    {
        err = ERR_get_error();
        CfOut(cf_error, "", "Unable to generate key: %s\n", ERR_reason_error_string(err));
        return;
    }

    if (DEBUG)
    {
        RSA_print_fp(stdout, pair, 0);
    }

    fd = open(CFPRIVKEYFILE, O_WRONLY | O_CREAT | O_TRUNC, 0600);

    if (fd < 0)
    {
        CfOut(cf_error, "open", "Open %s failed: %s.", CFPRIVKEYFILE, strerror(errno));
        return;
    }

    if ((fp = fdopen(fd, "w")) == NULL)
    {
        CfOut(cf_error, "fdopen", "Couldn't open private key %s.", CFPRIVKEYFILE);
        close(fd);
        return;
    }

    CfOut(cf_verbose, "", "Writing private key to %s\n", CFPRIVKEYFILE);

    if (!PEM_write_RSAPrivateKey(fp, pair, cipher, passphrase, strlen(passphrase), NULL, NULL))
    {
        err = ERR_get_error();
        CfOut(cf_error, "", "Couldn't write private key: %s\n", ERR_reason_error_string(err));
        return;
    }

    fclose(fp);

    fd = open(CFPUBKEYFILE, O_WRONLY | O_CREAT | O_TRUNC, 0600);

    if (fd < 0)
    {
        CfOut(cf_error, "open", "Unable to open public key %s.", CFPUBKEYFILE);
        return;
    }

    if ((fp = fdopen(fd, "w")) == NULL)
    {
        CfOut(cf_error, "fdopen", "Open %s failed.", CFPUBKEYFILE);
        close(fd);
        return;
    }

    CfOut(cf_verbose, "", "Writing public key to %s\n", CFPUBKEYFILE);

    if (!PEM_write_RSAPublicKey(fp, pair))
    {
        err = ERR_get_error();
        CfOut(cf_error, "", "Unable to write public key: %s\n", ERR_reason_error_string(err));
        return;
    }

    fclose(fp);

    snprintf(vbuff, CF_BUFSIZE, "%s/randseed", CFWORKDIR);
    RAND_write_file(vbuff);
    cf_chmod(vbuff, 0644);
}
Esempio n. 22
0
void ssl_client_init()
{
    /*
     * This is twisted. We can generate the required keys by calling RSA_generate_key,
     * however we cannot put the private part and the public part in the two containers.
     * For that we need to save each part to a file and then load each part from
     * the respective file.
     */
    RSA *key = NULL;
    key = RSA_generate_key(1024, 17, NULL, NULL);
    if (!key)
    {
        correctly_initialized = false;
        return;
    }
    char name_template_private[] = "/tmp/tls_test/mnopqrXXXXXX";
    char name_template_public[] = "/tmp/tls_test/stuvwxXXXXXX";
    int private_key_file = 0;
    FILE *private_key_stream = NULL;
    int ret = 0;

    private_key_file = mkstemp(name_template_private);
    if (private_key_file < 0)
    {
        correctly_initialized = false;
        return;
    }
    private_key_stream = fdopen(private_key_file, "w+");
    if (!private_key_stream)
    {
        correctly_initialized = false;
        return;
    }
    ret = PEM_write_RSAPrivateKey(private_key_stream, key, NULL, NULL, 0, 0, NULL);
    if (ret == 0)
    {
        correctly_initialized = false;
        return;
    }
    fseek(private_key_stream, 0L, SEEK_SET);
    PRIVKEY = PEM_read_RSAPrivateKey(private_key_stream, (RSA **)NULL, NULL, NULL);
    if (!PRIVKEY)
    {
        correctly_initialized = false;
        return;
    }
    fclose(private_key_stream);

    int public_key_file = 0;
    FILE *public_key_stream = NULL;
    public_key_file = mkstemp(name_template_public);
    if (public_key_file < 0)
    {
        correctly_initialized = false;
        return;
    }
    public_key_stream = fdopen(public_key_file, "w+");
    if (!public_key_stream)
    {
        correctly_initialized = false;
        return;
    }
    ret = PEM_write_RSAPublicKey(public_key_stream, key);
    if (ret == 0)
    {
        correctly_initialized = false;
        return;
    }
    fseek(public_key_stream, 0L, SEEK_SET);
    PUBKEY = PEM_read_RSAPublicKey(public_key_stream, (RSA **)NULL, NULL, NULL);
    if (!PUBKEY)
    {
        correctly_initialized = false;
        return;
    }
    fclose(public_key_stream);
    RSA_free(key);

    SSLCLIENTCONTEXT = SSL_CTX_new(SSLv23_client_method());
    if (SSLCLIENTCONTEXT == NULL)
    {
        Log(LOG_LEVEL_ERR, "SSL_CTX_new: %s",
            ERR_reason_error_string(ERR_get_error()));
        goto err1;
    }

    /* Use only TLS v1 or later.
       TODO option for SSL_OP_NO_TLSv{1,1_1} */
    SSL_CTX_set_options(SSLCLIENTCONTEXT,
                        SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);

    /* Never bother with retransmissions, SSL_write() should
     * always either write the whole amount or fail. */
    SSL_CTX_set_mode(SSLCLIENTCONTEXT, SSL_MODE_AUTO_RETRY);

    /*
     * Create cert into memory and load it into SSL context.
     */

    if (PRIVKEY == NULL || PUBKEY == NULL)
    {
        correctly_initialized = false;
        return;
    }

    /* Generate self-signed cert valid from now to 50 years later. */
    {
        X509 *x509 = X509_new();
        X509_gmtime_adj(X509_get_notBefore(x509), 0);
        X509_time_adj(X509_get_notAfter(x509), 60*60*24*365*50, NULL);
        EVP_PKEY *pkey = EVP_PKEY_new();
        EVP_PKEY_set1_RSA(pkey, PRIVKEY);
        X509_NAME *name = X509_get_subject_name(x509);
        X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
                                   (const char *) "",
                                   -1, -1, 0);
        X509_set_issuer_name(x509, name);
        X509_set_pubkey(x509, pkey);

        const EVP_MD *md = EVP_get_digestbyname("sha384");
        if (md == NULL)
        {
            correctly_initialized = false;
            return;
        }
        ret = X509_sign(x509, pkey, md);

        EVP_PKEY_free(pkey);
        SSLCLIENTCERT = x509;

        if (ret <= 0)
        {
            Log(LOG_LEVEL_ERR,
                "Couldn't sign the public key for the TLS handshake: %s",
                ERR_reason_error_string(ERR_get_error()));
            goto err3;
        }
    }
    /* Log(LOG_LEVEL_ERR, "generate cert from priv key: %s", */
    /*     ERR_reason_error_string(ERR_get_error())); */

    SSL_CTX_use_certificate(SSLCLIENTCONTEXT, SSLCLIENTCERT);

    ret = SSL_CTX_use_RSAPrivateKey(SSLCLIENTCONTEXT, PRIVKEY);
    if (ret != 1)
    {
        Log(LOG_LEVEL_ERR, "Failed to use RSA private key: %s",
            ERR_reason_error_string(ERR_get_error()));
        goto err3;
    }

    /* Verify cert consistency. */
    ret = SSL_CTX_check_private_key(SSLCLIENTCONTEXT);
    if (ret != 1)
    {
        Log(LOG_LEVEL_ERR, "Inconsistent key and TLS cert: %s",
            ERR_reason_error_string(ERR_get_error()));
        goto err3;
    }

    /* Set options to always request a certificate from the peer, either we
     * are client or server. */
    SSL_CTX_set_verify(SSLCLIENTCONTEXT, SSL_VERIFY_PEER, NULL);
    /* Always accept that certificate, we do proper checking after TLS
     * connection is established since OpenSSL can't pass a connection
     * specific pointer to the callback (so we would have to lock).  */
    SSL_CTX_set_cert_verify_callback(SSLCLIENTCONTEXT, TLSVerifyCallback, NULL);

    correctly_initialized = true;
    return;

  err3:
    X509_free(SSLCLIENTCERT);
    SSLCLIENTCERT = NULL;
    SSL_CTX_free(SSLCLIENTCONTEXT);
    SSLCLIENTCONTEXT = NULL;
  err1:
    correctly_initialized = false;
    return;
}
Esempio n. 23
0
int main(int argc, char* argv[]){
  
  // Local Variable definitions
  int i, j, k;
  size_t ret;
  int rsa_byte_size = RSA_KEY_SIZE/8;

  // buffer used to seed the PRNG
  unsigned char seed[rsa_byte_size];
  //unsigned char *keybuff;
  unsigned char *priv;
  unsigned char *pub;
  unsigned char *mod;
  size_t keybuff_len=0;

  // File pointers
  FILE *urand;
  FILE *pubkeyfile;
  FILE *privkeyfile;

  // RSA Struct used to store Priv/Pub key vals
  RSA *key = RSA_new();

  // Set the exponent size, e, to be used by RSA.
  BIGNUM *e = BN_new();

  // Open the public keyfile
  pubkeyfile = fopen("./publickey.txt","w+");
  if(pubkeyfile == NULL){
      fprintf(stderr, "ERROR: Unable to open publickey.txt for writing!\n");
      exit(-1);
  }

  // Open the private keyfile
  privkeyfile = fopen("./secretkey.txt","w+");
  if(privkeyfile == NULL){
      fprintf(stderr, "ERROR: Unable to open privatekey.txt for writing!\n");
      exit(-1);
  }

  // Open dev rand to seed our random data.
  urand = fopen("/dev/urandom","r");
  if(urand == NULL){
      fprintf(stderr, "ERROR: Unable to open /dev/urandom for reading!\n");
      exit(-1);
  }

  // Read the rand data from /dev/urandom
  ret = fread(&seed, sizeof(char), RSA_KEY_SIZE/8, urand);
  if(ret < RSA_KEY_SIZE/8){
      fprintf(stderr, "ERROR: Unable to obtain random seed from /dev/urandom!\n");
      exit(-1);
  }
  
  // Seed the PRNG
  RAND_seed(&seed, RSA_KEY_SIZE/8);

  // Setup our BIGNUM, this acts as the exponent e and will be stored with the pub/priv keys struct
  // read the BN_rand description to see why the last two args are 1.
  //ret = BN_generate_prime_ex(e, RSA_KEY_SIZE, 1, NULL, NULL, NULL);
  ret = BN_set_word(e, 0x10001); // 65537
  if(!ret){
    fprintf(stderr, "ERROR: There was a problem generating the mod 'e'\n");
    exit(-1);
  }


  // NOTE: As per the OpenSSL docs, RSA_generate_key(...) is deprecated.
  // int RSA_generate_key_ex(RSA *rsa, int bits, BIGNUM *e, BN_GENCB *cb);
  // Generate the RSA keys
  ret = RSA_generate_key_ex(key, RSA_KEY_SIZE, e, NULL);

  /* Currently, the OpenSSL doc does not detail the return value of RSA_generate_key_ex :-( */
  if(!ret){
    fprintf(stderr, "ERROR: There was a problem generating RSA key!\n");
    exit(-1);
  }

/*
  printf("DBG: Public Key - ");
  char * n_val = BN_bn2hex(key->n);
  for(i = 0; i < 256; i++){
    printf("%c", n_val[i]);
  }
  printf("\n");
*/


  if(!PEM_write_RSAPublicKey(pubkeyfile, key)){
    fprintf(stderr, "ERROR: There was a problem writing the Public RSA key!\n");
    exit(-1);
  }
  if(!PEM_write_RSAPrivateKey(privkeyfile, key, NULL, NULL, 0, NULL, NULL)){
    fprintf(stderr, "ERROR: There was a problem writing the Private RSA key!\n");
    exit(-1);
  }

/*
  // Write the public and private key values out to disk respectively
  //i = BN_num_bytes(key->e);
  //j = BN_num_bits(key->e);
  //keybuff = BN_bn2hex(key->e);
  priv = BN_bn2hex(key->d);
  pub  = BN_bn2hex(key->e);
  mod  = BN_bn2hex(key->n);

  // Write out the public modulus, n
  j = BN_num_bytes(key->e);
  for(i = 0; i < j; i++){
    fprintf(pubkeyfile, "%c", mod[i]);
    fprintf(privkeyfile, "%c", mod[i]);
  }
  fprintf(pubkeyfile,"\n");
  fprintf(privkeyfile,"\n");

  // Write out the public key
  j = BN_num_bytes(key->e);
  for(i = 0; i < j; i++){
    fprintf(pubkeyfile, "%c", pub[i]);
  }

  // Write out the private key
  j = BN_num_bytes(key->d);
  for(i = 0; i < j; i++){
    fprintf(privkeyfile, "%c", priv[i]);
  }
*/

  //printf("DBG: Number of bytes in e - %d\n", i);
  //DBG: Number of bytes in e - 256
  //printf("DBG: Number of bits in e - %d\n", j);
  //DBG: Number of bits in e - 2048

  /*
  printf("DBG: Print e:\n");
  for(k = 0; k < i; k++){
    printf("%c",keybuff[k]);
  }
  printf("\nDone.\n");

  // Note, the below is 256 characters, or 2048 bits worth of data.

  DBG: Print e:
  DF61CD9DCFF8B60F8302098EEA099F1B9ECED5C5AD3C98E129D380121A765BE089D6FAFEBACF272B5A87FC98995
  A259D6F9D069805436F0B93AFBB02ABAD2C19DD767F25DC25226DA99B24C92727A0F583FE8CAD4C60702A1F4EDB
  7F8E3A872519A8515DCBB963E676939FDCC2DFFD40C970137952FADB5048F7DAB4632646C8
  Done.

  */


  // Free allocated memory
  fclose(urand);
  fclose(pubkeyfile);
  fclose(privkeyfile);

  // Free the allocated RSA structures.
  RSA_free(key);
  BN_free(e);

  return 1;
}
Esempio n. 24
0
		inline void rsa_key::write_public_key(file _file) const
		{
			error::throw_error_if_not(PEM_write_RSAPublicKey(_file.raw(), ptr().get()) != 0);
		}