示例#1
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);
}
示例#2
0
文件: key_utils.c 项目: Emat12/PyCCN
int
write_key_pem_private(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_RSAPrivateKey(fp, private_key_rsa, NULL, NULL, 0, NULL, NULL)) {
		err = ERR_get_error();
		RSA_free(private_key_rsa);
		PyErr_Format(g_PyExc_CCNKeyError, "Unable to write Private Key: %s",
				ERR_reason_error_string(err));
		return -1;
	}

	//PEM_write_RSAPublicKey(stderr, private_key_rsa);
	RSA_free(private_key_rsa);

	return 0;
}
示例#3
0
void test_RSA_encryption(){
	unsigned char message[129];
  	strncpy((char*)message,"Hello. This is Timothy.",sizeof(message));
	unsigned char ciphertext[129];
	unsigned char decrypted[129];
	memset(ciphertext,'\0',129);
	memset(decrypted,'\0',129);
	FILE* fp=fopen("publickey.pem","r");
	RSA* pubkey=NULL;
	RSA* privkey=NULL;
	
	//Get public key
	if((pubkey=PEM_read_RSAPublicKey(fp,&pubkey,NULL,NULL))==NULL){
		printf("Error reading public key from file\n");
		return;
	}
	fclose(fp);
	printf("Original message: %s\n",message);	
	int encrypt_len=encrypt_with_public_key(pubkey,message,ciphertext,23);
	printf("Encrypted message: %s\n",ciphertext);
	privkey=get_private_key();
	fp=fopen("privatekeyTEST.pem","w+");
		
	int success=PEM_write_RSAPrivateKey(fp,privkey,NULL,NULL,0,NULL,NULL);
	fclose(fp);
	if(success!=1){
		perror("Issue writing the private key to file: ");
	}
	decrypt_with_private_key(privkey,ciphertext,decrypted,encrypt_len);
	printf("Decrypted message: %s\n",decrypted);
	RSA_free(pubkey);
	RSA_free(privkey);
}
示例#4
0
/**
 * Generates an RSA private key with the given exponent and number of bits
 * and writes it to the given file (if specified).
 */
RSA_key_t gen_RSA_key(int bits, int exponent, const char *filename)
{
    RSA_key_t rsa;
    FILE *f;

    if ((rsa = RSA_generate_key(bits ? bits : DEF_RSA_LEN,
                                exponent, NULL, NULL)) == NULL) {
        log_ssl_err("couldn't generate rsa key");
        return NULL;
    }

    if (strcmp(filename, "")) {
        if ((f = fopen(filename, "rb")) != NULL) {
            log(0, 0, "Private key file already exists, won't overwrite");
            fclose(f);
            return NULL;
        }
        if ((f = fopen(filename, "wb")) == NULL) {
            syserror(0, 0, "failed to open key file");
            return NULL;
        }
        if (!PEM_write_RSAPrivateKey(f, rsa, NULL, NULL, 0, NULL, NULL)) {
            log_ssl_err("couldn't write rsa private key");
            fclose(f);
            return NULL;
        }
        fclose(f);
    }

    return rsa;
}
示例#5
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);
}
示例#6
0
/** Generate a new signing key and write it to disk.  Return 0 on success,
 * nonzero on failure. */
static int
generate_signing_key(void)
{
  open_file_t *open_file;
  FILE *f;
  RSA *key;
  log_notice(LD_GENERAL, "Generating %d-bit RSA signing key.",
             SIGNING_KEY_BITS);
  if (!(key = generate_key(SIGNING_KEY_BITS))) {
    log_err(LD_GENERAL, "Couldn't generate signing key.");
    crypto_log_errors(LOG_ERR, "Generating signing key");
    return 1;
  }
  signing_key = EVP_PKEY_new();
  if (!(EVP_PKEY_assign_RSA(signing_key, key))) {
    log_err(LD_GENERAL, "Couldn't assign signing key.");
    return 1;
  }

  if (!(f = start_writing_to_stdio_file(signing_key_file,
                                        OPEN_FLAGS_REPLACE | O_TEXT, 0600,
                                        &open_file)))
    return 1;

  /* Write signing key with no encryption. */
  if (!PEM_write_RSAPrivateKey(f, key, NULL, NULL, 0, NULL, NULL)) {
    crypto_log_errors(LOG_WARN, "writing signing key");
    abort_writing_to_file(open_file);
    return 1;
  }

  finish_writing_to_file(open_file);

  return 0;
}
示例#7
0
void
save_privkey (RSA *key, const char *file)
{
    FILE *f;
    f = g_fopen (file, "wb");
    PEM_write_RSAPrivateKey(f, key, NULL, NULL, 0, NULL, NULL);
    fclose (f);
}
示例#8
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;
}
示例#9
0
文件: genrsa.c 项目: gitmo/uni
void writeRSAtoPEM (RSA *rsa, const char *fname) {
    FILE *fp;

    // Open file for writing
    if (!(fp = fopen(fname, "w"))) {
        perror(fname);
        exit(1);
    }

    // Write RSA key in PEM format
    if (!PEM_write_RSAPrivateKey(fp, rsa, NULL, NULL, 0, 0, NULL)) {
        printf("Error writing PEM file!\n");
    }

    fclose(fp);
}
示例#10
0
文件: crt2key.c 项目: ghoff/accessl
int main(int argc, char **argv)
{
    X509 *x509 = X509_new();
    EVP_PKEY *pkey;
    RSA *rsa;
    FILE *f;

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

    f = fopen(argv[1], "rb");
    x509 = PEM_read_X509(f, &x509, NULL, NULL);
    if (x509 == NULL) {
        printf("Error loading certificate\n");
        return 1;
    }
    pkey = X509_get_pubkey(x509);
    if (pkey->type != EVP_PKEY_RSA) {
        printf("Not an RSA key\n");
        return 1;
    }
    rsa = EVP_PKEY_get1_RSA(pkey);
    fclose(f);

    BN_dec2bn(&rsa->d, "0");
    BN_dec2bn(&rsa->p, "0");
    BN_dec2bn(&rsa->q, "0");
    BN_dec2bn(&rsa->dmp1, "0");
    BN_dec2bn(&rsa->dmq1, "0");
    BN_dec2bn(&rsa->iqmp, "0");

    f = fopen(argv[2], "wb");
    int ret = PEM_write_RSAPrivateKey(f, rsa, NULL, NULL, 0, NULL, NULL);
    fclose(f);

    if (ret) {
        ERR_print_errors_fp(stderr);
        return 1;
    }

    return 0;
}
		void SecurityKeyManager::createRSA(const dtn::data::EID &ref, const int bits)
		{
			const ibrcommon::File privkey = getKeyFile(ref, SecurityKey::KEY_PRIVATE);
			const ibrcommon::File pubkey = getKeyFile(ref, SecurityKey::KEY_PUBLIC);
			RSA* rsa = RSA_new();
			BIGNUM* e = BN_new();

			BN_set_word(e, 65537);

			RSA_generate_key_ex(rsa, bits, e, NULL);

			BN_free(e);
			e = NULL;

			// write private key
			int fd = ::open(privkey.getPath().c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0600);

			FILE * rsa_privkey_file = fdopen(fd, "w");
			if (!rsa_privkey_file) {
				IBRCOMMON_LOGGER_TAG(SecurityKeyManager::TAG, error) << "Failed to open " << privkey.getPath() << IBRCOMMON_LOGGER_ENDL;
				RSA_free(rsa);
				return;
			}
			PEM_write_RSAPrivateKey(rsa_privkey_file, rsa, NULL, NULL, 0, NULL, NULL);
			fclose(rsa_privkey_file);

			// write public key
			FILE * rsa_pubkey_file = fopen(pubkey.getPath().c_str(), "w+");
			if (!rsa_pubkey_file) {
				IBRCOMMON_LOGGER_TAG(SecurityKeyManager::TAG, error) << "Failed to open " << privkey.getPath() << IBRCOMMON_LOGGER_ENDL;
				RSA_free(rsa);
				return;
			}
			PEM_write_RSA_PUBKEY(rsa_pubkey_file, rsa);
			fclose(rsa_pubkey_file);

			RSA_free(rsa);

			// set trust-level to high
			SecurityKey key = get(ref, SecurityKey::KEY_PUBLIC);
			key.trustlevel = SecurityKey::HIGH;
			store(key);
		}
示例#12
0
int COsslKey::SavePrivateKey( const sqbind::stdString &sPrivate )
{_STT();

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

	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

	return 1;
}
示例#13
0
文件: rsa-keygen.c 项目: ia/-junk
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;
}
示例#14
0
void gen_keys( const char * priv_file, const char * pub_file )
{
   FILE   * fp;
   RSA    * rsa = RSA_new();
   BIGNUM * e   = BN_new();
   EVP_PKEY * pkey = EVP_PKEY_new();
   
   BN_dec2bn(&e, "65537");
   
   RSA_generate_key_ex(rsa, 512, e, NULL);

   fp = fopen(priv_file, "w");
   PEM_write_RSAPrivateKey(fp, rsa, 0, 0, 0, 0, 0);
   fclose(fp);

   fp = fopen(pub_file, "w");
   EVP_PKEY_assign_RSA(pkey,rsa);
   PEM_write_PUBKEY(fp, pkey);
   fclose(fp);

   BN_free(e);
   EVP_PKEY_free(pkey); // Also deletes rsa
}
示例#15
0
void test_onions(const void *s, const bool full) {
  char o[17];
  RSA *r = NULL;
  FILE *out = NULL;
  while (true) {
    r = gen_rsa();
    if (!r)
      goto end_loop;
    pthread_mutex_lock(&stats_lock);
    num_keys++;
    pthread_mutex_unlock(&stats_lock);
    if (!rsa_to_onion(r, o))
      goto end_loop;
    if (search_search(s, o, full) || search_pronounce(o)) {
      warnx("found '%s'", o);
      pthread_mutex_lock(&stats_lock);
      num_matches++;
      pthread_mutex_unlock(&stats_lock);
      out = fopen(o, "w");
      if (!out) {
        warn("fopen");
        goto end_loop;
      }
      PEM_write_RSAPrivateKey(out, r, NULL, NULL, 0, NULL, NULL);
    }
  end_loop:
    if (r) {
      RSA_free(r);
      r = NULL;
    }
    if (out) {
      fclose(out);
      out = NULL;
    }
  }
}
示例#16
0
void makersacert(int days, char* commonname, int bits)
{
	RSA *key;
	EVP_PKEY *pkey;
	X509 *x;
	FILE *out;

	key = RSA_generate_key(bits, RSA_F4, NULL, NULL);
	pkey = EVP_PKEY_new();
	EVP_PKEY_set1_RSA(pkey, key);

	x = makeselfcert(pkey, days, commonname, EVP_sha256());

	out = fopen("rsa_cert.pem", "w");
	if (out == NULL)
		exit(-1);
	PEM_write_X509(out, x);
	fclose(out);
	out = fopen("rsa_cert_key.pem", "w");
	if (out == NULL)
		exit(-1);
	PEM_write_RSAPrivateKey(out, key, NULL, NULL, 0, NULL, NULL);
	fclose(out);
}
示例#17
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");
        }
示例#18
0
文件: tincd.c 项目: 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;
}
示例#19
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;
}
示例#20
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;
    }
示例#21
0
文件: tincd.c 项目: 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;
}
示例#22
0
文件: crypto.c 项目: henri14/citadel
/*
 * initialize ssl engine, load certs and initialize openssl internals
 */
void init_ssl(void)
{
	const SSL_METHOD *ssl_method;
	RSA *rsa=NULL;
	X509_REQ *req = NULL;
	X509 *cer = NULL;
	EVP_PKEY *pk = NULL;
	EVP_PKEY *req_pkey = NULL;
	X509_NAME *name = NULL;
	FILE *fp;
	char buf[SIZ];
	int rv = 0;

	if (!access("/var/run/egd-pool", F_OK)) {
		RAND_egd("/var/run/egd-pool");
	}

	if (!RAND_status()) {
		syslog(LOG_WARNING, "PRNG not adequately seeded, won't do SSL/TLS\n");
		return;
	}
	SSLCritters = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t *));
	if (!SSLCritters) {
		syslog(LOG_ERR, "citserver: can't allocate memory!!\n");
		/* Nothing's been initialized, just die */
		ShutDownWebcit();
		exit(WC_EXIT_SSL);
	} else {
		int a;

		for (a = 0; a < CRYPTO_num_locks(); a++) {
			SSLCritters[a] = malloc(sizeof(pthread_mutex_t));
			if (!SSLCritters[a]) {
				syslog(LOG_EMERG,
					"citserver: can't allocate memory!!\n");
				/** Nothing's been initialized, just die */
				ShutDownWebcit();
				exit(WC_EXIT_SSL);
			}
			pthread_mutex_init(SSLCritters[a], NULL);
		}
	}

	/*
	 * Initialize SSL transport layer
	 */
	SSL_library_init();
	SSL_load_error_strings();
	ssl_method = SSLv23_server_method();
	if (!(ssl_ctx = SSL_CTX_new(ssl_method))) {
		syslog(LOG_WARNING, "SSL_CTX_new failed: %s\n", ERR_reason_error_string(ERR_get_error()));
		return;
	}

	syslog(LOG_INFO, "Requesting cipher list: %s\n", ssl_cipher_list);
	if (!(SSL_CTX_set_cipher_list(ssl_ctx, ssl_cipher_list))) {
		syslog(LOG_WARNING, "SSL_CTX_set_cipher_list failed: %s\n", ERR_reason_error_string(ERR_get_error()));
		return;
	}

	CRYPTO_set_locking_callback(ssl_lock);
	CRYPTO_set_id_callback(id_callback);

	/*
	 * Get our certificates in order. (FIXME: dirify. this is a setup job.)
	 * First, create the key/cert directory if it's not there already...
	 */
	mkdir(CTDL_CRYPTO_DIR, 0700);

	/*
	 * Before attempting to generate keys/certificates, first try
	 * link to them from the Citadel server if it's on the same host.
	 * We ignore any error return because it either meant that there
	 * was nothing in Citadel to link from (in which case we just
	 * generate new files) or the target files already exist (which
	 * is not fatal either).
	 */
	if (!strcasecmp(ctdlhost, "uds")) {
		sprintf(buf, "%s/keys/citadel.key", ctdlport);
		rv = symlink(buf, CTDL_KEY_PATH);
		if (!rv) syslog(LOG_DEBUG, "%s\n", strerror(errno));
		sprintf(buf, "%s/keys/citadel.csr", ctdlport);
		rv = symlink(buf, CTDL_CSR_PATH);
		if (!rv) syslog(LOG_DEBUG, "%s\n", strerror(errno));
		sprintf(buf, "%s/keys/citadel.cer", ctdlport);
		rv = symlink(buf, CTDL_CER_PATH);
		if (!rv) syslog(LOG_DEBUG, "%s\n", strerror(errno));
	}

	/*
	 * If we still don't have a private key, generate one.
	 */
	if (access(CTDL_KEY_PATH, R_OK) != 0) {
		syslog(LOG_INFO, "Generating RSA key pair.\n");
		rsa = RSA_generate_key(1024,	/* modulus size */
					65537,	/* exponent */
					NULL,	/* no callback */
					NULL	/* no callback */
		);
		if (rsa == NULL) {
			syslog(LOG_WARNING, "Key generation failed: %s\n", ERR_reason_error_string(ERR_get_error()));
		}
		if (rsa != NULL) {
			fp = fopen(CTDL_KEY_PATH, "w");
			if (fp != NULL) {
				chmod(CTDL_KEY_PATH, 0600);
				if (PEM_write_RSAPrivateKey(fp,	/* the file */
							rsa,	/* the key */
							NULL,	/* no enc */
							NULL,	/* no passphr */
							0,	/* no passphr */
							NULL,	/* no callbk */
							NULL	/* no callbk */
				) != 1) {
					syslog(LOG_WARNING, "Cannot write key: %s\n",
						ERR_reason_error_string(ERR_get_error()));
					unlink(CTDL_KEY_PATH);
				}
				fclose(fp);
			}
			else {
				syslog(LOG_WARNING, "Cannot write key: %s\n", CTDL_KEY_PATH);
				ShutDownWebcit();
				exit(0);
			}
			RSA_free(rsa);
		}
	}

	/*
	 * If there is no certificate file on disk, we will be generating a self-signed certificate
	 * in the next step.  Therefore, if we have neither a CSR nor a certificate, generate
	 * the CSR in this step so that the next step may commence.
	 */
	if ( (access(CTDL_CER_PATH, R_OK) != 0) && (access(CTDL_CSR_PATH, R_OK) != 0) ) {
		syslog(LOG_INFO, "Generating a certificate signing request.\n");

		/*
		 * Read our key from the file.  No, we don't just keep this
		 * in memory from the above key-generation function, because
		 * there is the possibility that the key was already on disk
		 * and we didn't just generate it now.
		 */
		fp = fopen(CTDL_KEY_PATH, "r");
		if (fp) {
			rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
			fclose(fp);
		}

		if (rsa) {

			/** Create a public key from the private key */
			if (pk=EVP_PKEY_new(), pk != NULL) {
				EVP_PKEY_assign_RSA(pk, rsa);
				if (req = X509_REQ_new(), req != NULL) {
					const char *env;
					/* Set the public key */
					X509_REQ_set_pubkey(req, pk);
					X509_REQ_set_version(req, 0L);

					name = X509_REQ_get_subject_name(req);

					/* Tell it who we are */

					/*
					 * We used to add these fields to the subject, but
					 * now we don't.  Someone doing this for real isn't
					 * going to use the webcit-generated CSR anyway.
					 *
					X509_NAME_add_entry_by_txt(name, "C",
						MBSTRING_ASC, "US", -1, -1, 0);
					*
					X509_NAME_add_entry_by_txt(name, "ST",
						MBSTRING_ASC, "New York", -1, -1, 0);
					*
					X509_NAME_add_entry_by_txt(name, "L",
						MBSTRING_ASC, "Mount Kisco", -1, -1, 0);
					*/

					env = getenv("O");
					if (env == NULL)
						env = "Organization name",

					X509_NAME_add_entry_by_txt(
						name, "O",
						MBSTRING_ASC, 
						(unsigned char*)env, 
						-1, -1, 0
					);

					env = getenv("OU");
					if (env == NULL)
						env = "Citadel server";

					X509_NAME_add_entry_by_txt(
						name, "OU",
						MBSTRING_ASC, 
						(unsigned char*)env, 
						-1, -1, 0
					);

					env = getenv("CN");
					if (env == NULL)
						env = "*";

					X509_NAME_add_entry_by_txt(
						name, "CN",
						MBSTRING_ASC, 
						(unsigned char*)env,
						-1, -1, 0
					);
				
					X509_REQ_set_subject_name(req, name);

					/* Sign the CSR */
					if (!X509_REQ_sign(req, pk, EVP_md5())) {
						syslog(LOG_WARNING, "X509_REQ_sign(): error\n");
					}
					else {
						/* Write it to disk. */	
						fp = fopen(CTDL_CSR_PATH, "w");
						if (fp != NULL) {
							chmod(CTDL_CSR_PATH, 0600);
							PEM_write_X509_REQ(fp, req);
							fclose(fp);
						}
						else {
							syslog(LOG_WARNING, "Cannot write key: %s\n", CTDL_CSR_PATH);
							ShutDownWebcit();
							exit(0);
						}
					}

					X509_REQ_free(req);
				}
			}

			RSA_free(rsa);
		}

		else {
			syslog(LOG_WARNING, "Unable to read private key.\n");
		}
	}



	/*
	 * Generate a self-signed certificate if we don't have one.
	 */
	if (access(CTDL_CER_PATH, R_OK) != 0) {
		syslog(LOG_INFO, "Generating a self-signed certificate.\n");

		/* Same deal as before: always read the key from disk because
		 * it may or may not have just been generated.
		 */
		fp = fopen(CTDL_KEY_PATH, "r");
		if (fp) {
			rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
			fclose(fp);
		}

		/* This also holds true for the CSR. */
		req = NULL;
		cer = NULL;
		pk = NULL;
		if (rsa) {
			if (pk=EVP_PKEY_new(), pk != NULL) {
				EVP_PKEY_assign_RSA(pk, rsa);
			}

			fp = fopen(CTDL_CSR_PATH, "r");
			if (fp) {
				req = PEM_read_X509_REQ(fp, NULL, NULL, NULL);
				fclose(fp);
			}

			if (req) {
				if (cer = X509_new(), cer != NULL) {

					ASN1_INTEGER_set(X509_get_serialNumber(cer), 0);
					X509_set_issuer_name(cer, req->req_info->subject);
					X509_set_subject_name(cer, req->req_info->subject);
					X509_gmtime_adj(X509_get_notBefore(cer), 0);
					X509_gmtime_adj(X509_get_notAfter(cer),(long)60*60*24*SIGN_DAYS);

					req_pkey = X509_REQ_get_pubkey(req);
					X509_set_pubkey(cer, req_pkey);
					EVP_PKEY_free(req_pkey);
					
					/* Sign the cert */
					if (!X509_sign(cer, pk, EVP_md5())) {
						syslog(LOG_WARNING, "X509_sign(): error\n");
					}
					else {
						/* Write it to disk. */	
						fp = fopen(CTDL_CER_PATH, "w");
						if (fp != NULL) {
							chmod(CTDL_CER_PATH, 0600);
							PEM_write_X509(fp, cer);
							fclose(fp);
						}
						else {
							syslog(LOG_WARNING, "Cannot write key: %s\n", CTDL_CER_PATH);
							ShutDownWebcit();
							exit(0);
						}
					}
					X509_free(cer);
				}
			}

			RSA_free(rsa);
		}
	}

	/*
	 * Now try to bind to the key and certificate.
	 * Note that we use SSL_CTX_use_certificate_chain_file() which allows
	 * the certificate file to contain intermediate certificates.
	 */
	SSL_CTX_use_certificate_chain_file(ssl_ctx, CTDL_CER_PATH);
	SSL_CTX_use_PrivateKey_file(ssl_ctx, CTDL_KEY_PATH, SSL_FILETYPE_PEM);
	if ( !SSL_CTX_check_private_key(ssl_ctx) ) {
		syslog(LOG_WARNING, "Cannot install certificate: %s\n",
				ERR_reason_error_string(ERR_get_error()));
	}
	
}
示例#23
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);
}
示例#24
0
	assert(NR_RSA_COMPONENTS * sizeof(char *) == sizeof(rsa_vals_sz));
	return (rsa_vals_sz *)(vals);
}

rsa_vals_sz * rsa_values_dec(RSA * rsa)
{
	return get_rsa_values(rsa, BN_bn2dec);
}

rsa_vals_sz * rsa_values_hex(RSA * rsa)
{
	return get_rsa_values(rsa, BN_bn2hex);
}

void rsa_values_free(rsa_vals_sz * vals)
{
	for (int i = 0; i < NR_RSA_COMPONENTS; i++) {
		OPENSSL_free(vals->array[i]);
	}
	free(vals);
}

#if 0
	assert(1 == PEM_write_RSAPrivateKey(
		stdout,
		rsa,
		NULL, NULL, 0, NULL, NULL, NULL));

#endif
示例#25
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;
}
示例#26
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;
}
示例#27
0
int main(int argc, char** argv) {
    R_RSA_PUBLIC_KEY public_key;
    R_RSA_PRIVATE_KEY private_key;
    int i, n, retval;
    bool is_valid;
    DATA_BLOCK signature, in, out;
    unsigned char signature_buf[256], buf[256], buf2[256];
    FILE *f, *fpriv, *fpub;
    char cbuf[256];
    RSA rsa_key;
    RSA *rsa_key_;
	BIO *bio_out=NULL;
    BIO *bio_err=NULL;
    char *certpath;
    bool b2o=false; // boinc key to openssl key ?
    bool kpriv=false; // private key ?

    if (argc == 1) {
        usage();
        exit(1);
    }
    if (!strcmp(argv[1], "-genkey")) {
        if (argc < 5) {
            usage();
            exit(1);
        }
        printf("creating keys in %s and %s\n", argv[3], argv[4]);
        n = atoi(argv[2]);

        srand(random_int());
        RSA* rp = RSA_generate_key(n,  65537, 0, 0);
        openssl_to_keys(rp, n, private_key, public_key);
        fpriv = fopen(argv[3], "w");
        if (!fpriv) die("fopen");
        fpub = fopen(argv[4], "w");
        if (!fpub) die("fopen");
        print_key_hex(fpriv, (KEY*)&private_key, sizeof(private_key));
        print_key_hex(fpub, (KEY*)&public_key, sizeof(public_key));

    } else if (!strcmp(argv[1], "-sign")) {
        if (argc < 4) {
            usage();
            exit(1);
        }
        fpriv = fopen(argv[3], "r");
        if (!fpriv) die("fopen");
        retval = scan_key_hex(fpriv, (KEY*)&private_key, sizeof(private_key));
        if (retval) die("scan_key_hex\n");
        signature.data = signature_buf;
        signature.len = 256;
        retval = sign_file(argv[2], private_key, signature);
        print_hex_data(stdout, signature);
    } else if (!strcmp(argv[1], "-sign_string")) {
        if (argc < 4) {
            usage();
            exit(1);
        }
        fpriv = fopen(argv[3], "r");
        if (!fpriv) die("fopen");
        retval = scan_key_hex(fpriv, (KEY*)&private_key, sizeof(private_key));
        if (retval) die("scan_key_hex\n");
        generate_signature(argv[2], cbuf, private_key);
        puts(cbuf);
    } else if (!strcmp(argv[1], "-verify")) {
        if (argc < 5) {
            usage();
            exit(1);
        }
        fpub = fopen(argv[4], "r");
        if (!fpub) die("fopen");
        retval = scan_key_hex(fpub, (KEY*)&public_key, sizeof(public_key));
        if (retval) die("read_public_key");
        f = fopen(argv[3], "r");
        signature.data = signature_buf;
        signature.len = 256;
        retval = scan_hex_data(f, signature);
        if (retval) die("scan_hex_data");
        retval = verify_file(argv[2], public_key, signature, is_valid);
        if (retval) die("verify_file");
        if (is_valid) {
            printf("file is valid\n");
        } else {
            printf("file is invalid\n");
            return 1;
        }
    } else if (!strcmp(argv[1], "-test_crypt")) {
        if (argc < 4) {
            usage();
            exit(1);
        }
        fpriv = fopen(argv[2], "r");
        if (!fpriv) die("fopen");
        retval = scan_key_hex(fpriv, (KEY*)&private_key, sizeof(private_key));
        if (retval) die("scan_key_hex\n");
        fpub = fopen(argv[3], "r");
        if (!fpub) die("fopen");
        retval = scan_key_hex(fpub, (KEY*)&public_key, sizeof(public_key));
        if (retval) die("read_public_key");
        strcpy((char*)buf2, "encryption test successful");
        in.data = buf2;
        in.len = strlen((char*)in.data);
        out.data = buf;
        encrypt_private(private_key, in, out);
        in = out;
        out.data = buf2;
        decrypt_public(public_key, in, out);
        printf("out: %s\n", out.data);
    } else if (!strcmp(argv[1], "-cert_verify")) {
        if (argc < 6)
            die("usage: crypt_prog -cert_verify file signature_file certificate_dir ca_dir \n");

        f = fopen(argv[3], "r");
        signature.data = signature_buf;
        signature.len = 256;
        retval = scan_hex_data(f, signature);
        if (retval) die("cannot scan_hex_data");
        certpath = check_validity(argv[4], argv[2], signature.data, argv[5]);
        if (certpath == NULL) {
            die("signature cannot be verfied.\n\n");
        } else {
            printf("siganture verified using certificate '%s'.\n\n", certpath);
            free(certpath);
        }
    // this converts, but an executable signed with sign_executable,
    // and signature converted to OpenSSL format cannot be verified with
    // OpenSSL
    } else if (!strcmp(argv[1], "-convsig")) {
        if (argc < 5) {
            usage();
            exit(1);
        }
        if (strcmp(argv[2], "b2o") == 0) {
            b2o = true;
        } else if (strcmp(argv[2], "o2b") == 0) {
            b2o = false;
        } else {
            die("either 'o2b' or 'b2o' must be defined for -convsig\n");
        }
        if (b2o) {
            f = fopen(argv[3], "r");
            signature.data = signature_buf;
            signature.len = 256;
            retval = scan_hex_data(f, signature);
            fclose(f);
            f = fopen(argv[4], "w+");
            print_raw_data(f, signature);
            fclose(f);
        } else {
            f = fopen(argv[3], "r");
            signature.data = signature_buf;
            signature.len = 256;
            retval = scan_raw_data(f, signature);
            fclose(f);
            f = fopen(argv[4], "w+");
            print_hex_data(f, signature);
            fclose(f);
        }
    } else if (!strcmp(argv[1], "-convkey")) {
        if (argc < 6) {
            usage();
            exit(1);
        }
        if (strcmp(argv[2], "b2o") == 0) {
            b2o = true;
        } else if (strcmp(argv[2], "o2b") == 0) {
            b2o = false;
        } else {
            die("either 'o2b' or 'b2o' must be defined for -convkey\n");
        }
        if (strcmp(argv[3], "pub") == 0) {
            kpriv = false;
        } else if (strcmp(argv[3], "priv") == 0)  {
            kpriv = true;
        } else {
            die("either 'pub' or 'priv' must be defined for -convkey\n");
        }
        OpenSSL_add_all_algorithms();
		ERR_load_crypto_strings();
		ENGINE_load_builtin_engines();
		if (bio_err == NULL) {
		    bio_err = BIO_new_fp(stdout, BIO_NOCLOSE);
        }
        //enc=EVP_get_cipherbyname("des");
        //if (enc == NULL)
        //    die("could not get cypher.\n");
        // no encription yet.
        bio_out=BIO_new(BIO_s_file());
		if (BIO_write_filename(bio_out,argv[5]) <= 0) {
			perror(argv[5]);
            die("could not create output file.\n");
        }
        if (b2o) {
            rsa_key_ = RSA_new();
            if (kpriv) {
                fpriv = fopen(argv[4], "r");
                if (!fpriv) {
                    die("fopen");
                }
                scan_key_hex(fpriv, (KEY*)&private_key, sizeof(private_key));
                fclose(fpriv);
                private_to_openssl(private_key, &rsa_key);

                //i = PEM_write_bio_RSAPrivateKey(bio_out, &rsa_key,
        		//				enc, NULL, 0, pass_cb, NULL);
        		// no encryption yet.
        		
                //i = PEM_write_bio_RSAPrivateKey(bio_out, &rsa_key,
        		//				NULL, NULL, 0, pass_cb, NULL);
                fpriv = fopen(argv[5], "w+");
                PEM_write_RSAPrivateKey(fpriv, &rsa_key, NULL, NULL, 0, 0, NULL);
                fclose(fpriv);
    		    //if (i == 0) {
                //    ERR_print_errors(bio_err);
                //    die("could not write key file.\n");
    		    //}
            } else {
                fpub = fopen(argv[4], "r");
                if (!fpub) {
                    die("fopen");
                }
                scan_key_hex(fpub, (KEY*)&public_key, sizeof(public_key));
                fclose(fpub);
                fpub = fopen(argv[5], "w+");
                if (!fpub) {
                    die("fopen");
                }
                public_to_openssl(public_key, rsa_key_);
    		    i = PEM_write_RSA_PUBKEY(fpub, rsa_key_);
    		    if (i == 0) {
                    ERR_print_errors(bio_err);
                    die("could not write key file.\n");
    		    }
                fclose(fpub);
            }
        } else {
            // o2b
            rsa_key_ = (RSA *)calloc(1, sizeof(RSA));
            memset(rsa_key_, 0, sizeof(RSA));
            if (rsa_key_ == NULL) {
                die("could not allocate memory for RSA structure.\n");
            }
            if (kpriv) {
                fpriv = fopen (argv[4], "r");
                rsa_key_ = PEM_read_RSAPrivateKey(fpriv, NULL, NULL, NULL);
                fclose(fpriv);
                if (rsa_key_ == NULL) {
                    ERR_print_errors(bio_err);
                    die("could not load private key.\n");
                }
                openssl_to_private(rsa_key_, &private_key);
                fpriv = fopen(argv[5], "w");
                if (!fpriv) {
                    die("fopen");
                }
                print_key_hex(fpriv, (KEY*)&private_key, sizeof(private_key));
            } else {
                fpub = fopen (argv[4], "r");
                rsa_key_ = PEM_read_RSA_PUBKEY(fpub, NULL, NULL, NULL);
                fclose(fpub);
                if (rsa_key_ == NULL) {
                    ERR_print_errors(bio_err);
                    die("could not load public key.\n");
                }
                openssl_to_keys(rsa_key_, 1024, private_key, public_key);
                //openssl_to_public(rsa_key_, &public_key);
                public_to_openssl(public_key, rsa_key_); //
                fpub = fopen(argv[5], "w");
                if (!fpub) {
                    die("fopen");
                }
                print_key_hex(fpub, (KEY*)&public_key, sizeof(public_key));
            }
        }
    } else {
        usage();
        exit(1);
    }
    return 0;
}
示例#28
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);
}
示例#29
0
文件: rsa.cpp 项目: 5432935/kbengine
//-------------------------------------------------------------------------------------
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);
}
示例#30
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);
}