Beispiel #1
9
int keygen_init(void)
{
	m_bignumber = BN_new();
	if(!m_bignumber)
	{
		fprintf(stderr, "Failed to init bignumber\n");
		return -1;
	}
	m_rsa=RSA_new();
	if(!m_rsa)
	{
		fprintf(stderr, "Failed to create RSA context\n");
		return -1;
	}
	if(!BN_set_word(m_bignumber, RSA_F4) || !RSA_generate_key_ex(m_rsa,RSA_KEY_BITS,m_bignumber,NULL))
	{
		fprintf(stderr, "Failed to generate RSA key\n");
		return -1;
	}
	m_evpkey=EVP_PKEY_new();
	if(!EVP_PKEY_set1_RSA(m_evpkey, m_rsa))
	{
		fprintf(stderr, "Unable to convert RSA key to EVP key\n");
		return -1;
	}
	m_p8info=EVP_PKEY2PKCS8(m_evpkey);
	if(!m_p8info)
	{
		fprintf(stderr, "Failed to convert EVP to PKCS8\n");
		return -1;
	}
	return 0;
}
Beispiel #2
0
static RSA *gen_rsa(void) {
  if (!RAND_status())
    seed_rng();
  int ret = 0;
  _Thread_local static int e_init = 0;
  _Thread_local static BIGNUM e;
  RSA *r = NULL;

  if (!e_init) {
    BN_init(&e);
    if (!BN_set_word(&e, 65537)) {
      warnx("BN_set_word");
      goto fail;
    }
    e_init = 1;
  }
  r = RSA_new();
  if (!r) {
    warnx("RSA_new");
    goto fail;
  }
  ret = RSA_generate_key_ex(r, 1024, &e, NULL);
  if (!ret) {
    warnx("RSA_generate_key");
    goto fail;
  }
  return r;
fail:
  if (r) {
    RSA_free(r);
    r = NULL;
  }
  return NULL;
}
int genRsaKey(const int bits, char * privkey)
{
  BIO * out = BIO_new(BIO_s_mem());
  RSA * rsa = 0;
  BIGNUM * bn = 0;
  int err = 0;
  if (!(rsa = RSA_new())) return -1;
  if (!(bn = BN_new())) return -2;
  if (!(err = BN_set_word(bn,RSA_F4))) {
    BN_free(bn);
    return err;
  }
  if (!(err = RSA_generate_key_ex(rsa,bits,bn,NULL))) {
    BN_free(bn);
    RSA_free(rsa);
    return err;
  }
  if (!(err = PEM_write_bio_RSAPrivateKey(out, rsa, NULL, NULL, 0, NULL, NULL))) {
    BIO_free_all(out);
    BN_free(bn);
    RSA_free(rsa);
    return err;
  }
  if (!(err = BIO_read(out,privkey,bits) <= 0)) {
    BIO_free_all(out);
    BN_free(bn);
    RSA_free(rsa);
    return err;
  }
  return 0;
}
Beispiel #4
0
/* Zeroize
*/
static int Zeroize()
    {
    RSA *key;
    BIGNUM *bn;
    unsigned char userkey[16] = 
	{ 0x48, 0x50, 0xf0, 0xa3, 0x3a, 0xed, 0xd3, 0xaf, 0x6e, 0x47, 0x7f, 0x83, 0x02, 0xb1, 0x09, 0x68 };
    int i, n;

    key = FIPS_rsa_new();
    bn = BN_new();
    if (!key || !bn)
	return 0;
    BN_set_word(bn, 65537);
    if (!RSA_generate_key_ex(key, 1024,bn,NULL))
	return 0;
    BN_free(bn);
    
    n = BN_num_bytes(key->d);
    printf(" Generated %d byte RSA private key\n", n);
    printf("\tBN key before overwriting:\n");
    do_bn_print(stdout, key->d);
    BN_rand(key->d,n*8,-1,0);
    printf("\tBN key after overwriting:\n");
    do_bn_print(stdout, key->d);

    printf("\tchar buffer key before overwriting: \n\t\t");
    for(i = 0; i < sizeof(userkey); i++) printf("%02x", userkey[i]);
        printf("\n");
    RAND_bytes(userkey, sizeof userkey);
    printf("\tchar buffer key after overwriting: \n\t\t");
    for(i = 0; i < sizeof(userkey); i++) printf("%02x", userkey[i]);
        printf("\n");

    return 1;
    }
Beispiel #5
0
// Generate a key pair. Caller is responsible for freeing the returned object.
static EVP_PKEY* MakeKey() {
  LOG(LS_INFO) << "Making key pair";
  EVP_PKEY* pkey = EVP_PKEY_new();
#if OPENSSL_VERSION_NUMBER < 0x00908000l
  // Only RSA_generate_key is available. Use that.
  RSA* rsa = RSA_generate_key(KEY_LENGTH, 0x10001, NULL, NULL);
  if (!EVP_PKEY_assign_RSA(pkey, rsa)) {
    EVP_PKEY_free(pkey);
    RSA_free(rsa);
    return NULL;
  }
#else
  // RSA_generate_key is deprecated. Use _ex version.
  BIGNUM* exponent = BN_new();
  RSA* rsa = RSA_new();
  if (!pkey || !exponent || !rsa ||
      !BN_set_word(exponent, 0x10001) ||  // 65537 RSA exponent
      !RSA_generate_key_ex(rsa, KEY_LENGTH, exponent, NULL) ||
      !EVP_PKEY_assign_RSA(pkey, rsa)) {
    EVP_PKEY_free(pkey);
    BN_free(exponent);
    RSA_free(rsa);
    return NULL;
  }
  // ownership of rsa struct was assigned, don't free it.
  BN_free(exponent);
#endif
  LOG(LS_INFO) << "Returning key pair";
  return pkey;
}
Beispiel #6
0
RSAKeyImpl::RSAKeyImpl(int keyLength, unsigned long exponent):
	_pRSA(0)
{
#if OPENSSL_VERSION_NUMBER >= 0x00908000L
	_pRSA = RSA_new();
	int ret = 0;
	BIGNUM* bn = 0;
	try
	{
		bn = BN_new();
		BN_set_word(bn, exponent);
		ret = RSA_generate_key_ex(_pRSA, keyLength, bn, 0);
		BN_free(bn);
	}
	catch (...)
	{
		BN_free(bn);
		throw;
	}
	if (!ret) throw Poco::InvalidArgumentException("Failed to create RSA context");
#else
	_pRSA = RSA_generate_key(keyLength, exponent, 0, 0);
	if (!_pRSA) throw Poco::InvalidArgumentException("Failed to create RSA context");
#endif
}
Beispiel #7
0
int main(void) 
{
    BIO*    bio_out;
    RSA*    key_pair            = NULL;
    BIGNUM* public_key_exponent = NULL;

    unsigned char   seed_data[ENTROPY_SIZE];
    
    /* Setup the output */
    bio_out = BIO_new_fp(stdout, BIO_NOCLOSE);

    /* Before generating the keys, the pseudo-random number generator must be seeded */
    obtain_seed_data(seed_data, ENTROPY_SIZE);
    RAND_seed(seed_data, ENTROPY_SIZE);

    BIO_printf(bio_out, "\nGenereating key pair:\n");
    
    /* Generate a 2048-bit key pair with a public exponent of 65537 (RSA_F4) */
    public_key_exponent = BN_new();
    key_pair            = RSA_new();

    BN_set_word(public_key_exponent, RSA_F4);
    RSA_generate_key_ex(key_pair, 2048, public_key_exponent, NULL);

    BIO_printf(bio_out, "-----------------------\n\n");
    
    BIO_printf(bio_out, "Value for the modulus \"n\":\n");
    BN_print(bio_out, key_pair -> n); 
    BIO_printf(bio_out, "\n\n");

    BIO_printf(bio_out, "Value for the distinct prime, \"p\":\n");
    BN_print(bio_out, key_pair -> p);
    BIO_printf(bio_out, "\n\n");

    BIO_printf(bio_out, "Value for the distinct prime, \"q\":\n");
    BN_print(bio_out, key_pair -> q);
    BIO_printf(bio_out, "\n\n");

    BIO_printf(bio_out, "Value for \"dP\":\n");
    BN_print(bio_out, key_pair -> dmp1);
    BIO_printf(bio_out, "\n\n");

    BIO_printf(bio_out, "Value for \"dQ\":\n");
    BN_print(bio_out, key_pair -> dmq1);
    BIO_printf(bio_out, "\n\n");

    BIO_printf(bio_out, "Value for \"qInv\":\n");
    BN_print(bio_out, key_pair -> iqmp);
    BIO_printf(bio_out, "\n\n");

    BIO_printf(bio_out, "Value for the public key exponent \"e\":\n");
    BN_print(bio_out, key_pair -> e);
    BIO_printf(bio_out, "\n\n");

    BIO_printf(bio_out, "Value for the private key exponent \"d\":\n");
    BN_print(bio_out, key_pair -> d);
    BIO_printf(bio_out, "\n\n");

    return 0;
}
Beispiel #8
0
		bool GenerateRSAKeyPair(int numBits, std::string& privKey, std::string& pubKey)
		{
			// TODO: add some error checking
			RSA* rsa = RSA_new();
			BIGNUM* bn = BN_new();
			BN_GENCB cb;
			BIO* bio_err = NULL;
			BN_GENCB_set(&cb, genrsa_cb, bio_err);
			BN_set_word(bn, RSA_F4);
			RSA_generate_key_ex(rsa, numBits, bn, &cb);

			BIO* privKeyBuff = BIO_new(BIO_s_mem());
			BIO* pubKeyBuff = BIO_new(BIO_s_mem());
			PEM_write_bio_RSAPrivateKey(privKeyBuff, rsa, 0, 0, 0, 0, 0);
			PEM_write_bio_RSA_PUBKEY(pubKeyBuff, rsa); // RSA_PUBKEY includes some data that RSAPublicKey doesn't have

			char* privKeyData;
			char* pubKeyData;
			auto privKeySize = BIO_get_mem_data(privKeyBuff, &privKeyData);
			auto pubKeySize = BIO_get_mem_data(pubKeyBuff, &pubKeyData);

			privKey = std::string(privKeyData, privKeySize);
			pubKey = std::string(pubKeyData, pubKeySize);
			
			BIO_free_all(privKeyBuff);
			BIO_free_all(pubKeyBuff);
			BN_free(bn);
			RSA_free(rsa);
			return true;
		}
Beispiel #9
0
static RSA *
tlso_tmp_rsa_cb( SSL *ssl, int is_export, int key_length )
{
	RSA *tmp_rsa;
	/* FIXME:  Pregenerate the key on startup */
	/* FIXME:  Who frees the key? */
#if OPENSSL_VERSION_NUMBER >= 0x00908000
	BIGNUM *bn = BN_new();
	tmp_rsa = NULL;
	if ( bn ) {
		if ( BN_set_word( bn, RSA_F4 )) {
			tmp_rsa = RSA_new();
			if ( tmp_rsa && !RSA_generate_key_ex( tmp_rsa, key_length, bn, NULL )) {
				RSA_free( tmp_rsa );
				tmp_rsa = NULL;
			}
		}
		BN_free( bn );
	}
#else
	tmp_rsa = RSA_generate_key( key_length, RSA_F4, NULL, NULL );
#endif

	if ( !tmp_rsa ) {
		Debug( LDAP_DEBUG_ANY,
			"TLS: Failed to generate temporary %d-bit %s RSA key\n",
			key_length, is_export ? "export" : "domestic", 0 );
	}
	return tmp_rsa;
}
Beispiel #10
0
static RSA*
rsa_genkey(u32 size)
{
    zassert(size >= DNSSEC_MINIMUM_KEY_SIZE && size <= DNSSEC_MAXIMUM_KEY_SIZE);

    BN_CTX *ctx;
    BIGNUM *e;
    RSA* rsa;

    ctx = BN_CTX_new();

    zassert(ctx != NULL);

    e = BN_new();
    BN_set_word(e, 0x10001);

    zassert(e != NULL);

    rsa = RSA_new();

    zassert(rsa != NULL);

    int err = RSA_generate_key_ex(rsa, size, e, NULL); /* no callback */

    if(err == 0)
    {
        RSA_free(rsa);
        rsa = NULL;
    }

    BN_free(e);
    BN_CTX_free(ctx);

    return rsa;
}
Beispiel #11
0
RSA *RSA_generate_key(int bits, unsigned long e_value,
                      void (*callback) (int, int, void *), void *cb_arg)
{
    int i;
    BN_GENCB *cb = BN_GENCB_new();
    RSA *rsa = RSA_new();
    BIGNUM *e = BN_new();

    if (cb == NULL || rsa == NULL || e == NULL)
        goto err;

    /*
     * The problem is when building with 8, 16, or 32 BN_ULONG, unsigned long
     * can be larger
     */
    for (i = 0; i < (int)sizeof(unsigned long) * 8; i++) {
        if (e_value & (1UL << i))
            if (BN_set_bit(e, i) == 0)
                goto err;
    }

    BN_GENCB_set_old(cb, callback, cb_arg);

    if (RSA_generate_key_ex(rsa, bits, e, cb)) {
        BN_free(e);
        BN_GENCB_free(cb);
        return rsa;
    }
 err:
    BN_free(e);
    RSA_free(rsa);
    BN_GENCB_free(cb);
    return 0;
}
static int generate_rsa_keypair(EVP_PKEY* pkey, const keymaster_rsa_keygen_params_t* rsa_params) {
    Unique_BIGNUM bn(BN_new());
    if (bn.get() == NULL) {
        logOpenSSLError("generate_rsa_keypair");
        return -1;
    }

    if (BN_set_word(bn.get(), rsa_params->public_exponent) == 0) {
        logOpenSSLError("generate_rsa_keypair");
        return -1;
    }

    /* initialize RSA */
    Unique_RSA rsa(RSA_new());
    if (rsa.get() == NULL) {
        logOpenSSLError("generate_rsa_keypair");
        return -1;
    }

    if (!RSA_generate_key_ex(rsa.get(), rsa_params->modulus_size, bn.get(), NULL) ||
        RSA_check_key(rsa.get()) < 0) {
        logOpenSSLError("generate_rsa_keypair");
        return -1;
    }

    if (EVP_PKEY_assign_RSA(pkey, rsa.get()) == 0) {
        logOpenSSLError("generate_rsa_keypair");
        return -1;
    }
    release_because_ownership_transferred(rsa);

    return 0;
}
Beispiel #13
0
std::unique_ptr<RSA_PrivateKey>
make_openssl_rsa_private_key(RandomNumberGenerator& rng, size_t rsa_bits)
   {
   if (rsa_bits > INT_MAX)
      throw Internal_Error("rsa_bits overflow");

   secure_vector<uint8_t> seed(BOTAN_SYSTEM_RNG_POLL_REQUEST);
   rng.randomize(seed.data(), seed.size());
   RAND_seed(seed.data(), seed.size());

   std::unique_ptr<BIGNUM, std::function<void (BIGNUM*)>> bn(BN_new(), BN_free);
   if(!bn)
      throw OpenSSL_Error("BN_new");
   if(!BN_set_word(bn.get(), RSA_F4))
      throw OpenSSL_Error("BN_set_word");

   std::unique_ptr<RSA, std::function<void (RSA*)>> rsa(RSA_new(), RSA_free);
   if(!rsa)
      throw OpenSSL_Error("RSA_new");
   if(!RSA_generate_key_ex(rsa.get(), rsa_bits, bn.get(), nullptr))
      throw OpenSSL_Error("RSA_generate_key_ex");

   uint8_t* der = nullptr;
   int bytes = i2d_RSAPrivateKey(rsa.get(), &der);
   if(bytes < 0)
      throw OpenSSL_Error("i2d_RSAPrivateKey");

   const secure_vector<uint8_t> keydata(der, der + bytes);
   memset(der, 0, bytes);
   free(der);
   return std::unique_ptr<Botan::RSA_PrivateKey>
      (new RSA_PrivateKey(AlgorithmIdentifier(), keydata));
   }
Beispiel #14
0
static EVP_PKEY * generate_private_key (void)
{
    RSA *rsa = RSA_new();
    BIGNUM *bn = BN_new();
    EVP_PKEY *pkey;

    /*
     * create an RSA keypair and assign them to a PKEY and return it.
     */
    BN_set_word(bn, 0x10001);
    RSA_generate_key_ex(rsa, 1024, bn, NULL);    

    pkey = EVP_PKEY_new();
    if (pkey==NULL) {
        printf("\nError allocating PKEY structure for new key pair\n");
        return NULL;
    }
    if (!EVP_PKEY_set1_RSA(pkey, rsa)) {
        printf("\nError assigning RSA key pair to PKEY structure\n");
        return NULL;
    }        
    
    RSA_free(rsa);
    BN_free(bn);
    
    return (pkey);
}
Beispiel #15
0
unsigned char* CreatePrivateKey(size_t* len, size_t* pubLen) {
    //MOD, PUB_EXP, PRIV_EXP
    RSA* msa = RSA_new();
    BIGNUM* e = BN_new();
    BN_set_word(e, 65537);
    RSA_generate_key_ex(msa, 4096, e, 0);
    BN_free(e);
    size_t pubSize = 4+BN_num_bytes(msa->n)+4+BN_num_bytes(msa->e);
    size_t privSize = 4+BN_num_bytes(msa->d);
    unsigned char* retval = (unsigned char*)malloc(pubSize+privSize);
    unsigned char* izard = retval;
    uint32_t count = BN_num_bytes(msa->n);
    memcpy(izard, &count, 4);
    izard+=4;
    BN_bn2bin(msa->n, izard);
    izard+=count;
    count = BN_num_bytes(msa->e);
    memcpy(izard, &count, 4);
    izard+=4;
    BN_bn2bin(msa->e, izard);
    izard+=count;
    count = BN_num_bytes(msa->d);
    memcpy(izard, &count, 4);
    izard+=4;
    BN_bn2bin(msa->d, izard);
    *len = pubSize+privSize;
    *pubLen = pubSize;
    RSA_free(msa);
    return retval;
}
RSA *RSA_generate_key(int bits, unsigned long e_value,
	     void (*callback)(int,int,void *), void *cb_arg)
	{
	BN_GENCB cb;
	int i;
	RSA *rsa = RSA_new();
	BIGNUM *e = BN_new();

	if(!rsa || !e) goto err;

	/* The problem is when building with 8, 16, or 32 BN_ULONG,
	 * unsigned long can be larger */
	for (i=0; i<(int)sizeof(unsigned long)*8; i++)
		{
		if (e_value & (1UL<<i))
			BN_set_bit(e,i);
		}

	BN_GENCB_set_old(&cb, callback, cb_arg);

	if(RSA_generate_key_ex(rsa, bits, e, &cb)) {
		BN_free(e);
		return rsa;
	}
err:
	if(e) BN_free(e);
	if(rsa) RSA_free(rsa);
	return 0;
	}
Beispiel #17
0
ndn_Error
ndn_RsaPrivateKey_generate(struct ndn_RsaPrivateKey *self, uint32_t keySize)
{
  BIGNUM* exponent = 0;
  int success = 0;

  if (self->privateKey) {
    // Free a previous value.
    RSA_free(self->privateKey);
    self->privateKey = 0;
  }

  exponent = BN_new();
  if (BN_set_word(exponent, RSA_F4) == 1) {
    self->privateKey = RSA_new();
    if (RSA_generate_key_ex(self->privateKey, keySize, exponent, NULL) == 1)
      success = 1;
  }

  BN_free(exponent);
  if (success)
    return NDN_ERROR_success;
  else {
    RSA_free(self->privateKey);
    self->privateKey = 0;
    return NDN_ERROR_Error_in_generate_operation;
  }
}
Beispiel #18
0
static int test_bad_key(void) {
  RSA *key = RSA_new();
  BIGNUM e;

  BN_init(&e);
  BN_set_word(&e, RSA_F4);

  if (!RSA_generate_key_ex(key, 512, &e, NULL)) {
    fprintf(stderr, "RSA_generate_key_ex failed.\n");
    ERR_print_errors_fp(stderr);
    return 0;
  }

  if (!BN_add(key->p, key->p, BN_value_one())) {
    fprintf(stderr, "BN error.\n");
    ERR_print_errors_fp(stderr);
    return 0;
  }

  if (RSA_check_key(key)) {
    fprintf(stderr, "RSA_check_key passed with invalid key!\n");
    return 0;
  }

  ERR_clear_error();
  BN_free(&e);
  RSA_free(key);
  return 1;
}
Beispiel #19
0
static int
lws_tls_openssl_rsa_new_key(RSA **rsa, int bits)
{
	BIGNUM *bn = BN_new();
	int n;

	if (!bn)
		return 1;

	if (BN_set_word(bn, RSA_F4) != 1) {
		BN_free(bn);
		return 1;
	}

	*rsa = RSA_new();
	if (!*rsa) {
		BN_free(bn);
		return 1;
	}

	n = RSA_generate_key_ex(*rsa, bits, bn, NULL);
	BN_free(bn);
	if (n == 1)
		return 0;

	RSA_free(*rsa);
	*rsa = NULL;

	return 1;
}
Beispiel #20
0
static int pkey_rsa_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey)
	{
	RSA *rsa = NULL;
	RSA_PKEY_CTX *rctx = ctx->data;
	BN_GENCB *pcb, cb;
	int ret;
	if (!rctx->pub_exp)
		{
		rctx->pub_exp = BN_new();
		if (!rctx->pub_exp || !BN_set_word(rctx->pub_exp, RSA_F4))
			return 0;
		}
	rsa = RSA_new();
	if (!rsa)
		return 0;
	if (ctx->pkey_gencb)
		{
		pcb = &cb;
		evp_pkey_set_cb_translate(pcb, ctx);
		}
	else
		pcb = NULL;
	ret = RSA_generate_key_ex(rsa, rctx->nbits, rctx->pub_exp, pcb);
	if (ret > 0)
		EVP_PKEY_assign_RSA(pkey, rsa);
	else
		RSA_free(rsa);
	return ret;
	}
Beispiel #21
0
static ERL_NIF_TERM rsa_generate_key(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{/* (ModulusSize, PublicExponent) */
    int modulus_bits;
    BIGNUM *pub_exp, *three;
    RSA *rsa;
    int success;
    ERL_NIF_TERM result;
    BN_GENCB *intr_cb;
#ifndef HAVE_OPAQUE_BN_GENCB
    BN_GENCB intr_cb_buf;
#endif

    if (!enif_get_int(env, argv[0], &modulus_bits) || modulus_bits < 256) {
	return enif_make_badarg(env);
    }

    if (!get_bn_from_bin(env, argv[1], &pub_exp)) {
	return enif_make_badarg(env);
    }

    /* Make sure the public exponent is large enough (at least 3).
     * Without this, RSA_generate_key_ex() can run forever. */
    three = BN_new();
    BN_set_word(three, 3);
    success = BN_cmp(pub_exp, three);
    BN_free(three);
    if (success < 0) {
	BN_free(pub_exp);
	return enif_make_badarg(env);
    }

    /* For large keys, prime generation can take many seconds. Set up
     * the callback which we use to test whether the process has been
     * interrupted. */
#ifdef HAVE_OPAQUE_BN_GENCB
    intr_cb = BN_GENCB_new();
#else
    intr_cb = &intr_cb_buf;
#endif
    BN_GENCB_set(intr_cb, check_erlang_interrupt, env);

    rsa = RSA_new();
    success = RSA_generate_key_ex(rsa, modulus_bits, pub_exp, intr_cb);
    BN_free(pub_exp);

#ifdef HAVE_OPAQUE_BN_GENCB
    BN_GENCB_free(intr_cb);
#endif

    if (!success) {
        RSA_free(rsa);
	return atom_error;
    }

    result = put_rsa_private_key(env, rsa);
    RSA_free(rsa);

    return result;
}
static int openssl_generate_keypair(const keymaster_device_t* dev,
        const keymaster_keypair_t key_type, const void* key_params,
        uint8_t** keyBlob, size_t* keyBlobLength) {
    ssize_t privateLen, publicLen;

    if (key_type != TYPE_RSA) {
        ALOGW("Unsupported key type %d", key_type);
        return -1;
    } else if (key_params == NULL) {
        ALOGW("key_params == null");
        return -1;
    }

    keymaster_rsa_keygen_params_t* rsa_params = (keymaster_rsa_keygen_params_t*) key_params;

    Unique_BIGNUM bn(BN_new());
    if (bn.get() == NULL) {
        logOpenSSLError("openssl_generate_keypair");
        return -1;
    }

    if (BN_set_word(bn.get(), rsa_params->public_exponent) == 0) {
        logOpenSSLError("openssl_generate_keypair");
        return -1;
    }

    /* initialize RSA */
    Unique_RSA rsa(RSA_new());
    if (rsa.get() == NULL) {
        logOpenSSLError("openssl_generate_keypair");
        return -1;
    }

    if (!RSA_generate_key_ex(rsa.get(), rsa_params->modulus_size, bn.get(), NULL)
            || RSA_check_key(rsa.get()) < 0) {
        logOpenSSLError("openssl_generate_keypair");
        return -1;
    }

    /* assign to EVP */
    Unique_EVP_PKEY pkey(EVP_PKEY_new());
    if (pkey.get() == NULL) {
        logOpenSSLError("openssl_generate_keypair");
        return -1;
    }

    if (EVP_PKEY_assign_RSA(pkey.get(), rsa.get()) == 0) {
        logOpenSSLError("openssl_generate_keypair");
        return -1;
    }
    OWNERSHIP_TRANSFERRED(rsa);

    if (wrap_key(pkey.get(), EVP_PKEY_RSA, keyBlob, keyBlobLength)) {
        return -1;
    }

    return 0;
}
Beispiel #23
0
/*
 * Generate and store a private key on the token
 * FIXME: We should check first whether the token supports
 * on-board key generation, and if it does, use its own algorithm
 */
int pkcs11_generate_key(PKCS11_TOKEN *token, int algorithm, unsigned int bits,
		char *label, unsigned char* id, size_t id_len)
{
	PKCS11_KEY *key_obj;
	EVP_PKEY *pk;
	RSA *rsa;
	BIO *err;
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
	BIGNUM *exp = NULL;
	BN_GENCB *gencb = NULL;
#endif
	int rc;

	if (algorithm != EVP_PKEY_RSA) {
		PKCS11err(PKCS11_F_PKCS11_GENERATE_KEY, PKCS11_NOT_SUPPORTED);
		return -1;
	}

	err = BIO_new_fp(stderr, BIO_NOCLOSE);

#if OPENSSL_VERSION_NUMBER >= 0x10100000L
	exp = BN_new();
	rsa = RSA_new();
	gencb = BN_GENCB_new();
	if (gencb)
	    BN_GENCB_set(gencb, NULL, err);

	if ( rsa == NULL  || exp == NULL || gencb == NULL
	    || !BN_set_word(exp, RSA_F4) || !RSA_generate_key_ex(rsa, bits, exp, gencb)) {
		RSA_free(rsa);
	}
	BN_GENCB_free(gencb);
	BN_free(exp);

#else
	rsa = RSA_generate_key(bits, RSA_F4, NULL, err);
#endif
	BIO_free(err);
	if (rsa == NULL) {
		PKCS11err(PKCS11_F_PKCS11_GENERATE_KEY, PKCS11_KEYGEN_FAILED);
		return -1;
	}

	pk = EVP_PKEY_new();
	EVP_PKEY_assign_RSA(pk, rsa);
	rc = pkcs11_store_key(token, pk, CKO_PRIVATE_KEY,
		label, id, id_len, &key_obj);

	if (rc == 0) {
		PKCS11_KEY_private *kpriv;

		kpriv = PRIVKEY(key_obj);
		rc = pkcs11_store_key(token, pk, CKO_PUBLIC_KEY,
			label, kpriv->id, kpriv->id_len, NULL);
	}
	EVP_PKEY_free(pk);
	return rc;
}
Beispiel #24
0
/* returns error
   generates a new rsa key
   exp is passed in and mod and pri are passed out */
int APP_CC
ssl_gen_key_xrdp1(int key_size_in_bits, char* exp, int exp_len,
                  char* mod, int mod_len, char* pri, int pri_len)
{
  BIGNUM* my_e;
  RSA* my_key;
  char* lexp;
  char* lmod;
  char* lpri;
  int error;
  int len;

  if ((exp_len != 4) || (mod_len != 64) || (pri_len != 64))
  {
    return 1;
  }
  lexp = (char*)g_malloc(exp_len, 0);
  lmod = (char*)g_malloc(mod_len, 0);
  lpri = (char*)g_malloc(pri_len, 0);
  g_memcpy(lexp, exp, exp_len);
  ssl_reverse_it(lexp, exp_len);
  my_e = BN_new();
  BN_bin2bn((tui8*)lexp, exp_len, my_e);
  my_key = RSA_new();
  error = RSA_generate_key_ex(my_key, key_size_in_bits, my_e, 0) == 0;
  if (error == 0)
  {
    len = BN_num_bytes(my_key->n);
    error = len != mod_len;
  }
  if (error == 0)
  {
    BN_bn2bin(my_key->n, (tui8*)lmod);
    ssl_reverse_it(lmod, mod_len);
  }
  if (error == 0)
  {
    len = BN_num_bytes(my_key->d);
    error = len != pri_len;
  }
  if (error == 0)
  {
    BN_bn2bin(my_key->d, (tui8*)lpri);
    ssl_reverse_it(lpri, pri_len);
  }
  if (error == 0)
  {
    g_memcpy(mod, lmod, mod_len);
    g_memcpy(pri, lpri, pri_len);
  }
  BN_free(my_e);
  RSA_free(my_key);
  g_free(lexp);
  g_free(lmod);
  g_free(lpri);
  return error;
}
Beispiel #25
0
static bool generate_keys(ScopedEVP_PKEY &private_key_out,
                          ScopedEVP_PKEY &public_key_out)
{
    ScopedEVP_PKEY private_key(EVP_PKEY_new(), EVP_PKEY_free);
    ScopedEVP_PKEY public_key(EVP_PKEY_new(), EVP_PKEY_free);
    ScopedRSA rsa(RSA_new(), RSA_free);
    ScopedBIGNUM e(BN_new(), BN_free);

    if (!private_key) {
        LOGE("Failed to allocate private key");
        openssl_log_errors();
        return false;
    }

    if (!public_key) {
        LOGE("Failed to allocate public key");
        openssl_log_errors();
        return false;
    }

    if (!rsa) {
        LOGE("Failed to allocate RSA");
        openssl_log_errors();
        return false;
    }

    if (!e) {
        LOGE("Failed to allocate BIGNUM");
        openssl_log_errors();
        return false;
    }

    BN_set_word(e.get(), RSA_F4);

    if (RSA_generate_key_ex(rsa.get(), 2048, e.get(), nullptr) < 0) {
        LOGE("RSA_generate_key_ex() failed");
        openssl_log_errors();
        return false;
    }

    if (!EVP_PKEY_assign_RSA(private_key.get(), RSAPrivateKey_dup(rsa.get()))) {
        LOGE("EVP_PKEY_assign_RSA() failed for private key");
        openssl_log_errors();
        return false;
    }

    if (!EVP_PKEY_assign_RSA(public_key.get(), RSAPublicKey_dup(rsa.get()))) {
        LOGE("EVP_PKEY_assign_RSA() failed for public key");
        openssl_log_errors();
        return false;
    }

    private_key_out = std::move(private_key);
    public_key_out = std::move(public_key);
    return true;
}
RSA* Crypto::GenerateKeyPair()
{
	BIGNUM* exp = BN_new();
	BN_set_word(exp, DEFAULT_RSA_EXP);

	RSA* rsaKeys = RSA_new();

	RSA_generate_key_ex(rsaKeys, DEFAULT_RSA_SIZE, exp, NULL);
	return rsaKeys;
}
Beispiel #27
0
int generate_RSA_keys ()
{
    // DEBUG
    printf ( "Generation cles RSA ... \n" ) ;

    // Déclaration variables
    BIGNUM *bne = NULL ;        // Exponent
    int bits = KEY_LENGTH ;     // Taille clé

    // On alloue notre object RSA
    if ( ( client_key = RSA_new() ) == NULL )
    {
        perror ( "Erreur_generate_RSA_keys : RSA_New() " ) ;
        fprintf ( stderr, "Code erreur OpenSSL : %lu \n ", ERR_get_error () ) ;
        return 0;
    }

    // On alloue notre object BIGNUM
    if ( ( bne = BN_new() ) == NULL )
    {
        perror ( "Erreur_generate_RSA_keys : BN_new() " ) ;
        fprintf ( stderr, "Code erreur OpenSSL : %lu \n ", ERR_get_error () ) ;
        return 0 ;
    }

    // On fixe l'exposant sur la valeur maximale courante
    if ( ( BN_set_word ( bne, 65537 ) ) == 0 )
    {
        perror ( "Erreur_generate_RSA_keys : BN_set_word() " ) ;
        fprintf ( stderr, "Code erreur OpenSSL : %lu \n ", ERR_get_error () ) ;
        return 0 ;
    }

    // On génère maintenant notre paire de clés RSA
    if ( ( RSA_generate_key_ex ( client_key, bits, bne, NULL ) ) != 1 )
    {
        perror ( "Erreur_generate_RSA_keys : RSA_generate_key_ex() " ) ;
        fprintf ( stderr, "Code erreur OpenSSL : %lu \n ", ERR_get_error () ) ;
        return 0 ;
    }

    // On free notre object BIGNUM
    BN_free ( bne ) ;

    // Dernière vérification
    if ( client_key == NULL )
    {
        perror ( "Erreur_generate_RSA_keys : impossible de generer les cles " ) ;
        return 0 ;
    }
    else{
        
        return 1 ;
    }
}
Beispiel #28
0
void openssl_rsa_pemkey()
{
	long len;
	BIGNUM *bne;
	BIO *ins, *outs;
	RSA *r, *read;
	char *name, *head;
	unsigned char *data;
	const EVP_CIPHER *enc;
	EVP_CIPHER_INFO cipher;

	OpenSSL_add_all_algorithms();

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

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

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

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

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

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

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

	RSA_free(read);
	BIO_free(ins);
}
Beispiel #29
0
/*
 * Generates RSA public and private key
 * @param public_key: where the DER encoded public key is put
 * @param private_key: where the DER encoded private key is put
 * @return: pointer to RSA object
 */
RSA *generate_rsa_keys(unsigned char **public_key, unsigned char **private_key) {
    RSA *key = RSA_new();
    kExp = BN_new();
    BN_set_word(kExp, kExp_long);

    if (RSA_generate_key_ex(key, kBits, kExp, 0) < 0) {
        printf("RSA_generate_key_ex failed\n");
        exit(EXIT_FAILURE);
    }

    return key;
}
Beispiel #30
0
void start_crypt(void)
{
  ctx = BN_CTX_new();
  BN_CTX_init(ctx);

  rsa = RSA_new();
  
  e = BN_new();
  BN_dec2bn(&e,"65537");
  
  RSA_generate_key_ex(rsa, 2048, e, NULL);
}