예제 #1
0
void RSAKeyImpl::save(const std::string& publicKeyFile,
	const std::string& privateKeyFile,
	const std::string& privateKeyPassphrase) const
{
	if (!publicKeyFile.empty())
	{
		BIO* bio = BIO_new(BIO_s_file());
		if (!bio) throw Poco::IOException("Cannot create BIO for writing public key file", publicKeyFile);
		try
		{
			if (BIO_write_filename(bio, const_cast<char*>(publicKeyFile.c_str())))
			{
				if (!PEM_write_bio_RSAPublicKey(bio, _pRSA))
					throw Poco::WriteFileException("Failed to write public key to file", publicKeyFile);
			}
			else throw Poco::CreateFileException("Cannot create public key file");
		}
		catch (...)
		{
			BIO_free(bio);
			throw;
		}
		BIO_free(bio);
	}
	
	if (!privateKeyFile.empty())
	{
		BIO* bio = BIO_new(BIO_s_file());
		if (!bio) throw Poco::IOException("Cannot create BIO for writing private key file", privateKeyFile);
		try
		{
			if (BIO_write_filename(bio, const_cast<char*>(privateKeyFile.c_str())))
			{
				int rc = 0;
				if (privateKeyPassphrase.empty())
					rc = PEM_write_bio_RSAPrivateKey(bio, _pRSA, 0, 0, 0, 0, 0);
				else
					rc = PEM_write_bio_RSAPrivateKey(bio, _pRSA, EVP_des_ede3_cbc(), 
						reinterpret_cast<unsigned char*>(const_cast<char*>(privateKeyPassphrase.c_str())), 
						static_cast<int>(privateKeyPassphrase.length()), 0, 0);
				if (!rc) throw Poco::FileException("Failed to write private key to file", privateKeyFile);
			}
			else throw Poco::CreateFileException("Cannot create private key file", privateKeyFile);
		}
		catch (...)
		{
			BIO_free(bio);
			throw;
		}
		BIO_free(bio);
	}
}
예제 #2
0
static const char *RSAPrivKeyToString(RSA *key)
{
	static char buffer[2000];
	
	BIO *bp = BIO_new(BIO_s_mem());

	if (!bp)
		return NULL;
	
	if (!PEM_write_bio_RSAPrivateKey(bp, key, NULL, NULL, 0, NULL, NULL)) {
		BIO_free(bp);
		return NULL;
	}

	int len = BIO_read(bp, buffer, sizeof(buffer));
	
	BIO_free(bp);

	if (len <= 0)
		return NULL;

	buffer[len] = '\0';

	//printf("Key string:\n%s\n", buffer);

	return buffer;
}
예제 #3
0
sqbind::CSqBinary COsslKey::getPrivateKey()
{_STT();

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

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

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

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

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

	BIO_free( pBio );

	return bin;
}
예제 #4
0
/**
* @brief Prints an RSA keypair.
*
* @param keypair
*/
void print_keypair(RSA *keypair) {
    // To get the C-string PEM form:
    BIO *pri = BIO_new(BIO_s_mem());
    BIO *pub = BIO_new(BIO_s_mem());
    
    PEM_write_bio_RSAPrivateKey(pri, keypair, NULL, NULL, 0, NULL, NULL);
    PEM_write_bio_RSAPublicKey(pub, keypair);
    
    size_t pri_len = BIO_pending(pri);
    size_t pub_len = BIO_pending(pub);
    
	char *pri_key, *pub_key;
    pri_key = (char *)malloc(pri_len + 1);
    pub_key = (char *)malloc(pub_len + 1);
    
    BIO_read(pri, pri_key, pri_len);
    BIO_read(pub, pub_key, pub_len);
    
    pri_key[pri_len] = '\0';
    pub_key[pub_len] = '\0';
    
    printf("\n%s\n\n%s\n", pri_key, pub_key);

    BIO_free_all(pub);
    BIO_free_all(pri);
    free(pri_key);
    free(pub_key);
}
예제 #5
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;
		}
예제 #6
0
파일: vm_api.c 프로젝트: macm00v/vmcam
int generate_rsa_pkey() {
	FILE * fp;
	RSA * rsa_priv_key;
	const int kBits = 1024;
	const int kExp = 3;
	int keylen;
	char *pem_key;
        
	rsa_priv_key = RSA_generate_key(kBits, kExp, 0, 0);

	/* To get the C-string PEM form: */
	BIO *bio = BIO_new(BIO_s_mem());
	PEM_write_bio_RSAPrivateKey(bio, rsa_priv_key, NULL, NULL, 0, NULL, NULL);

	keylen = BIO_pending(bio);
	pem_key = calloc(keylen + 1, 1); /* Null-terminate */
	BIO_read(bio, pem_key, keylen);

	fp = fopen(f_rsa_private_key, "w");
	if (fp) {
		fwrite(pem_key, keylen, 1, fp);
		fclose(fp);
	} else {
		LOG(ERROR, "[API] RSA key generation failed, could not write key to %s", f_rsa_private_key);
		return -1;
	}

	LOG(VERBOSE, "[API] Private key created:%s", pem_key);

	BIO_free_all(bio);
	free(pem_key);
        pem_key = NULL;
	return 0;
}
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;
}
예제 #8
0
파일: pke.cpp 프로젝트: BrownBear2/fc
    bool generate_keys( char* pubkey, fc::vector<char>& privkey, uint32_t key_size, uint32_t pe )
    {
        static bool init = true;
        if( init ) { ERR_load_crypto_strings(); init = false; }

        RSA* rsa = RSA_generate_key( key_size, pe, NULL, NULL );
        BN_bn2bin( rsa->n, (unsigned char*)pubkey );

        BIO *mem = BIO_new(BIO_s_mem());
        int e = PEM_write_bio_RSAPrivateKey(mem, rsa,  NULL, NULL, 0, NULL, NULL ); 
        if( e != 1 )
        {
            BIO_free(mem);
            RSA_free(rsa);
		        FC_THROW(generic_exception("Error writing PrivateKey") );
        }

        char* dat;
        uint32_t l = BIO_get_mem_data( mem, &dat );
        privkey.resize(l);
        memcpy( &privkey.front(), dat, l );

        BIO_free(mem);
        RSA_free(rsa);
        return true;
    }
예제 #9
0
//生成RSA公钥和私钥文件
int createRSAPEM()
{
    int ret = 0;
    BIO *bpub = NULL;
    BIO *bpri = NULL;

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

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

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

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

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

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

	if (pPrivateKeyStream)
	{
		BIO* bio = BIO_new(BIO_s_mem());
		if (!bio) throw Poco::IOException("Cannot create BIO for writing public key");
		int rc = 0;
		if (privateKeyPassphrase.empty())
			rc = PEM_write_bio_RSAPrivateKey(bio, _pRSA, 0, 0, 0, 0, 0);
		else
			rc = PEM_write_bio_RSAPrivateKey(bio, _pRSA, EVP_des_ede3_cbc(), 
				reinterpret_cast<unsigned char*>(const_cast<char*>(privateKeyPassphrase.c_str())), 
				static_cast<int>(privateKeyPassphrase.length()), 0, 0);
		if (!rc) 
		{
			BIO_free(bio);
			throw Poco::FileException("Failed to write private key to stream");
		}
		char* pData;
		long size = BIO_get_mem_data(bio, &pData);
		pPrivateKeyStream->write(pData, static_cast<std::streamsize>(size));
		BIO_free(bio);
	}
}
예제 #12
0
//Additional SSL Encryption functions
QList<QByteArray> AuthorizationManager::GenerateSSLKeyPair(){
  const int kBits = 4096;
  const int kExp = 3;

  char *pem_key, *pem_key_pub;

  RSA *rsa = RSA_generate_key(kBits, kExp, 0, 0);

  //Private key in PEM form:
  BIO *bio = BIO_new(BIO_s_mem());
  PEM_write_bio_RSAPrivateKey(bio, rsa, NULL, NULL, 0, NULL, NULL);
  int keylen = BIO_pending(bio);
  pem_key = (char *)malloc(keylen); /* Null-terminate */
  BIO_read(bio, pem_key, keylen);
  QByteArray privkey = QByteArray::fromRawData(pem_key, keylen);

  //Public key in PEM form:
  BIO *bio2 = BIO_new(BIO_s_mem());
  PEM_write_bio_RSA_PUBKEY(bio2, rsa);
  int keylen2 = BIO_pending(bio2);
  pem_key_pub = (char *)malloc(keylen2); /* Null-terminate */
  BIO_read(bio2, pem_key_pub, keylen2);
  QByteArray pubkey = QByteArray::fromRawData(pem_key_pub, keylen2);

  BIO_free_all(bio);
  BIO_free_all(bio2);
  RSA_free(rsa);

  //See if the keys can be loaded for use later
  /*RSA *rsa1= NULL;
  BIO *keybio1 = NULL;
  //qDebug() << " - Generate keybio";
  keybio1 = BIO_new_mem_buf(pubkey.data(), -1);
  if(keybio1!=NULL){
    rsa1 = PEM_read_bio_RSA_PUBKEY(keybio1, &rsa1,NULL, NULL);
    qDebug() << "Can read new public key:" << (rsa1!=NULL);
    RSA_free(rsa1);
  }
  BIO_free_all(keybio1);

  RSA *rsa2= NULL;
  BIO *keybio2 = NULL;
  //qDebug() << " - Generate keybio";
  keybio2 = BIO_new_mem_buf(privkey.data(), -1);
  if(keybio2!=NULL){
    rsa2 = PEM_read_bio_RSAPrivateKey(keybio2, &rsa1,NULL, NULL);
    qDebug() << "Can read new private key:" << (rsa2!=NULL);
    RSA_free(rsa2);
  }
  BIO_free_all(keybio2);
  */
  return (QList<QByteArray>() << pubkey << privkey);
}
예제 #13
0
static void rsakey_hexdump(gpointer key, gpointer value, gpointer user_data)
{
	struct rsa_key_t *rsa_key = (struct rsa_key_t *)value;
	/* HACK: dump key for openssl verification
	 * e.g. echo -n <something> | openssl rsautl -in <encoded.bin> -inkey <privkey>  -oaep -d
	 * delete when keys stored to file */
	printf("RSA: keylen: %d, privkey:\n", rsa_key->keylen);
	BIO *bio = BIO_new_fp(stdout, BIO_NOCLOSE);
	PEM_write_bio_RSAPrivateKey(bio, rsa_key->rsa, NULL, NULL, 0, NULL, NULL);
	BIO_free(bio);
	printf("\n");
}
예제 #14
0
	void SecureServer::generateRSAKey (const int& bits, const std::string& publicFilename, const std::string &privateFilename, const std::string &password) throw (boost::system::system_error) {
		const unsigned long e = RSA_F4;
		
		//Generate RSA key
		std::unique_ptr<BIGNUM,void (*)(BIGNUM*)> bignum(BN_new(), &BN_free);
		int ret;
		if((ret = BN_set_word(bignum.get(), e)) != 1){
			throw_system_error_ssl("Could not set BIGNUM word");
		}
		
		std::unique_ptr<RSA,void (*)(RSA*)> rsa(RSA_new(), &RSA_free);
		if(RSA_generate_key_ex(rsa.get(), bits, bignum.get(), nullptr) != 1){
			throw_system_error_ssl("Could not generate RSA key");
		}
		
		//Save public key
		std::unique_ptr<BIO,void (*)(BIO*)> publicBIO(BIO_new_file(publicFilename.c_str(), "w"), &BIO_free_all);
		if(!publicBIO){
			throw_system_error_ssl("Could not open "+publicFilename+" for writing");
		}
		if(PEM_write_bio_RSAPublicKey(publicBIO.get(), rsa.get()) != 1){
			throw_system_error_ssl("Could not write RSA public key");
		}
		
		//Save private key
		std::unique_ptr<BIO,void (*)(BIO*)> privateBIO(BIO_new_file(privateFilename.c_str(), "w"), &BIO_free_all);
		if(!privateBIO){
			throw_system_error_ssl("Could not open "+privateFilename+" for writing");
		}
		if(password.empty()){
			if(PEM_write_bio_RSAPrivateKey(privateBIO.get(), rsa.get(), nullptr, nullptr, 0, nullptr, nullptr) != 1){
				throw_system_error_ssl("Could not write RSA private key");
			}
		}else{
			if(PEM_write_bio_RSAPrivateKey(privateBIO.get(), rsa.get(), EVP_des_ede3_cbc(), (unsigned char *)password.data(), password.size(), nullptr, nullptr) != 1){
				throw_system_error_ssl("Could not write RSA private key");
			}
		}
	}
예제 #15
0
/* convert SSH v2 key in OpenSSL PEM format */
static int
sshkey_private_pem_to_blob(struct sshkey *key, struct sshbuf *blob,
    const char *_passphrase, const char *comment)
{
	int success, r;
	int blen, len = strlen(_passphrase);
	u_char *passphrase = (len > 0) ? (u_char *)_passphrase : NULL;
	const EVP_CIPHER *cipher = (len > 0) ? EVP_aes_128_cbc() : NULL;
	const u_char *bptr;
	BIO *bio = NULL;

	if (len > 0 && len <= 4)
		return SSH_ERR_PASSPHRASE_TOO_SHORT;
	if ((bio = BIO_new(BIO_s_mem())) == NULL)
		return SSH_ERR_ALLOC_FAIL;

	switch (key->type) {
	case KEY_DSA:
		success = PEM_write_bio_DSAPrivateKey(bio, key->dsa,
		    cipher, passphrase, len, NULL, NULL);
		break;
	case KEY_ECDSA:
		success = PEM_write_bio_ECPrivateKey(bio, key->ecdsa,
		    cipher, passphrase, len, NULL, NULL);
		break;
	case KEY_RSA:
		success = PEM_write_bio_RSAPrivateKey(bio, key->rsa,
		    cipher, passphrase, len, NULL, NULL);
		break;
	default:
		success = 0;
		break;
	}
	if (success == 0) {
		r = SSH_ERR_LIBCRYPTO_ERROR;
		goto out;
	}
	if ((blen = BIO_get_mem_data(bio, &bptr)) <= 0) {
		r = SSH_ERR_INTERNAL_ERROR;
		goto out;
	}
	if ((r = sshbuf_put(blob, bptr, blen)) != 0)
		goto out;
	r = 0;
 out:
	BIO_free(bio);
	return r;
}
예제 #16
0
/* 
 * Takes in an RSA object and PEM encodes it in out
 * @param key: the RSA private key
 * @param out: the string the PEM encoding goes to
 * @param pem_password: the password to unlock the pem encoding
 * @return: the length of the PEM encoding
 */
unsigned int rsa_privatekey_to_pem(RSA *key, unsigned char **out, unsigned char *password) {
    BIO *pubKey = BIO_new(BIO_s_mem());

    PEM_write_bio_RSAPrivateKey(pubKey, key, NULL, NULL, 0, NULL, NULL);

    unsigned char line[65];
    int len = 0;
    unsigned char *pem = NULL;
    unsigned char *new_pem = NULL;

    if (!BIO_eof(pubKey)) {
        BIO_gets(pubKey, line, sizeof *pubKey);

        len += strlen(line);

        new_pem = (unsigned char *)realloc(pem, len*sizeof(unsigned char));
        if (!new_pem) {
            printf("realloc failed at length:%d\n", len);
        } else {
            memcpy(new_pem, "-----BEGIN PRIVATE KEY-----\n", (size_t)len);
            pem = new_pem;
        }
    }

    while (!BIO_eof(pubKey)) {
        BIO_gets(pubKey, line, sizeof *pubKey);

        //  current length of PEM (including newlines)
        len += strlen(line);

        new_pem = (unsigned char *)realloc(pem, len*sizeof(unsigned char));
        if (!new_pem) {
            printf("realloc failed at length:%d\n", len);
            exit(EXIT_FAILURE);
        } else {
            memcpy(new_pem, strcat(new_pem, line), (size_t)len);
            pem = new_pem;
        }
    }

    *out = pem;

    return len;
}
예제 #17
0
boolean
an_key_generate_keypair (uint8_t *key_label)
{
    int ret = 0;
    RSA *r = NULL;
    BIGNUM *bne = NULL;
    BIO *bp_public = NULL, *bp_private = NULL;
    unsigned long e = RSA_F4;

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

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

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

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

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

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

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

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

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

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

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

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

    return 0;
}
예제 #19
0
/*
 *  When the -x option isn't used from the CLI, we will implicitly generate
 *  an RSA key to be used to sign the CSR.
 */
static unsigned char * generate_private_key (int *key_len)
{
    RSA *rsa = RSA_new();
    BIGNUM *bn = BN_new();
    BIO *out;
    unsigned char *tdata;
    unsigned char *key_data;

    BN_set_word(bn, 0x10001);

    RSA_generate_key_ex(rsa, SRP_MINIMAL_N, bn, NULL);
    out = BIO_new(BIO_s_mem());
    PEM_write_bio_RSAPrivateKey(out, rsa, NULL, NULL, 0, NULL, NULL);
    *key_len = BIO_get_mem_data(out, &tdata);
    key_data = malloc(*key_len + 1);
    memcpy(key_data, tdata, *key_len);
    BIO_free(out);
    RSA_free(rsa);
    BN_free(bn);
    return (key_data);
}
예제 #20
0
파일: ftk-adb.cpp 프로젝트: gregsimon/ftk
  bool AdbEndpoint::generate_key()
  {
    bool success = false;
    BIGNUM* bne = NULL;
    //BIO* bp_public = NULL;
    //BIO* bp_private = NULL;
    int bits = 2048;
    unsigned long e = RSA_F4;

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

        wxLogDebug("generated RSA key");

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

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

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

    return success;
  }
예제 #21
0
파일: key_utils.c 프로젝트: Emat12/PyCCN
PyObject *
get_key_pem_private(const struct ccn_pkey *private_key_ccn)
{
	unsigned long err;
	RSA *private_key_rsa = NULL;
	BIO *bio;
	BUF_MEM *bufmem;
	int r;
	PyObject *py_res;

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

	private_key_rsa = EVP_PKEY_get1_RSA((EVP_PKEY *) private_key_ccn);
	JUMP_IF_NULL(private_key_rsa, openssl_error);

	r = PEM_write_bio_RSAPrivateKey(bio, private_key_rsa, NULL, NULL, 0, NULL,
			NULL);
	RSA_free(private_key_rsa);
	private_key_rsa = NULL;
	if (!r)
		goto openssl_error;

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

	return py_res;

openssl_error:
	err = ERR_get_error();
	PyErr_Format(g_PyExc_CCNKeyError, "Unable to obtain PEM: %s",
			ERR_reason_error_string(err));
	RSA_free(private_key_rsa);
	BIO_free(bio);
	return NULL;
}
예제 #22
0
        std::vector<unsigned char> RSAKey::getPEM(bool discard_private_compound, PEMPassphraseCallback callback, void* userdata) const
        {
            std::shared_ptr<BIO> pbio(BIO_new(BIO_s_mem()), BIO_free);

            if (hasPrivateCompound() && (!discard_private_compound))
            {
                EXCEPTION_ASSERT_WITH_LOG(PEM_write_bio_RSAPrivateKey(pbio.get(), d_rsa.get(), NULL, NULL, 0, callback, userdata), OpenSSLException, "Cannot write PEM data");
            }
            else
            {
                EXCEPTION_ASSERT_WITH_LOG(PEM_write_bio_RSA_PUBKEY(pbio.get(), d_rsa.get()), OpenSSLException, "Cannot write PEM data");
            }

            int len = BIO_pending(pbio.get());

            std::vector<unsigned char> buffer(len);

            BIO_read(pbio.get(), buffer.data(), len);
            buffer.resize(len);

            return buffer;
        }
예제 #23
0
파일: security.c 프로젝트: llinsky/Anonynet
int generate_rsa_key_pair(int size){
	RSA* rsa=NULL;
	BIGNUM* bn=NULL;
	BIO *bp_public=NULL;
	BIO *bp_private=NULL;
	unsigned long e=RSA_F4;
	bn=BN_new();
	int success = BN_set_word(bn,e); 
	if(success!=1){	
		printf("Issue with BN_set_word\n");
	}
	rsa=RSA_new();
	success = RSA_generate_key_ex(rsa,size,bn,NULL);
 	if(success!=1){
		printf("Issue with RSA generation\n");
	}	
	//Now save the key to a file
	bp_public= BIO_new_file("publickey.pem","w+");
	success=PEM_write_bio_RSAPublicKey(bp_public,rsa);
	if(success!=1){
		printf("Issue writing the public key to file\n");	
	}
	else{
		printf("\tPublic key saved to publickey.pem...\n");
	}
	bp_private=BIO_new_file("privatekey.pem","w+");
	success=PEM_write_bio_RSAPrivateKey(bp_private,rsa,NULL,NULL,0,NULL,NULL);
	if(success!=1){
		printf("Issue writing the private key to file\n");
	}
	
	//Free pointers
	BIO_free_all(bp_public);
	BIO_free_all(bp_private);
	RSA_free(rsa);
	BN_free(bn);
	return success;
}
예제 #24
0
int MakeX509CSR(const char *cn, const char *keyfile, const char *csrfile)
{
	InitializeOpenSSL(); 
	
	RSA *rsa = RSA_generate_key(4096, RSA_F4, NULL, NULL);

	BIO *bio = BIO_new(BIO_s_file());
	BIO_write_filename(bio, const_cast<char *>(keyfile));
	PEM_write_bio_RSAPrivateKey(bio, rsa, NULL, NULL, 0, NULL, NULL);
	BIO_free(bio);

	X509_REQ *req = X509_REQ_new();

	if (!req)
		return 0;

	EVP_PKEY *key = EVP_PKEY_new();
	EVP_PKEY_assign_RSA(key, rsa);
	X509_REQ_set_version(req, 0);
	X509_REQ_set_pubkey(req, key);

	X509_NAME *name = X509_REQ_get_subject_name(req);
	X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, (unsigned char *)cn, -1, -1, 0);

	X509_REQ_sign(req, key, EVP_sha1());

	EVP_PKEY_free(key);

	bio = BIO_new(BIO_s_file());
	BIO_write_filename(bio, const_cast<char *>(csrfile));
	PEM_write_bio_X509_REQ(bio, req);
	BIO_free(bio);

	X509_REQ_free(req);

	return 1;
}
예제 #25
0
int
openssl_write_key(RSA *rsa, char *filename, CK_BYTE *pPin)
{
	BIO *b = NULL;
	char loc[PATH_MAX];
	struct passwd *pw = NULL;

	errno = 0;
	if ((pw = getpwuid(getuid())) == NULL) {
		TRACE_ERROR("Error getting username: %s\n", strerror(errno));
		return -1;
	}

	sprintf(loc, "%s/%s/%s", pk_dir, pw->pw_name, filename);

	b = BIO_new_file(loc, "w");
	if (!b) {
		TRACE_ERROR("Error opening file for write: %s\n", loc);
		return -1;
	}

	if (!PEM_write_bio_RSAPrivateKey(b, rsa, EVP_aes_256_cbc(), NULL, 0, 0, pPin)) {
		BIO_free(b);
		TRACE_ERROR("Writing key %s to disk failed.\n", loc);
		DEBUG_openssl_print_errors();
		return -1;
	}

	BIO_free(b);

	if (util_set_file_mode(loc, (S_IRUSR|S_IWUSR))) {
		TRACE_ERROR("Setting file mode of %s failed\n", loc);
	}

	return 0;
}
예제 #26
0
int
rsa_main(int argc, char **argv)
{
	int ret = 1;
	RSA *rsa = NULL;
	int i;
	BIO *out = NULL;
	char *passin = NULL, *passout = NULL;

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

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

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

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

	{
		EVP_PKEY *pkey;

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

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

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

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

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

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

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

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

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

	return (ret);
}
예제 #27
0
int MAIN(int argc, char **argv)
	{
	BN_GENCB cb;
#ifndef OPENSSL_NO_ENGINE
	ENGINE *e = NULL;
#endif
	int ret=1;
	int i,num=DEFBITS;
	long l;
	const EVP_CIPHER *enc=NULL;
	unsigned long f4=RSA_F4;
	char *outfile=NULL;
	char *passargout = NULL, *passout = NULL;
#ifndef OPENSSL_NO_ENGINE
	char *engine=NULL;
#endif
	char *inrand=NULL;
	BIO *out=NULL;
	BIGNUM *bn = BN_new();
	RSA *rsa = NULL;

	if(!bn) goto err;

	apps_startup();
	BN_GENCB_set(&cb, genrsa_cb, bio_err);

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

	if (!load_config(bio_err, NULL))
		goto err;
	if ((out=BIO_new(BIO_s_file())) == NULL)
		{
		BIO_printf(bio_err,"unable to create BIO for output\n");
		goto err;
		}

	argv++;
	argc--;
	for (;;)
		{
		if (argc <= 0) break;
		if (TINYCLR_SSL_STRCMP(*argv,"-out") == 0)
			{
			if (--argc < 1) goto bad;
			outfile= *(++argv);
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-3") == 0)
			f4=3;
		else if (TINYCLR_SSL_STRCMP(*argv,"-F4") == 0 || TINYCLR_SSL_STRCMP(*argv,"-f4") == 0)
			f4=RSA_F4;
#ifndef OPENSSL_NO_ENGINE
		else if (TINYCLR_SSL_STRCMP(*argv,"-engine") == 0)
			{
			if (--argc < 1) goto bad;
			engine= *(++argv);
			}
#endif
		else if (TINYCLR_SSL_STRCMP(*argv,"-rand") == 0)
			{
			if (--argc < 1) goto bad;
			inrand= *(++argv);
			}
#ifndef OPENSSL_NO_DES
		else if (TINYCLR_SSL_STRCMP(*argv,"-des") == 0)
			enc=EVP_des_cbc();
		else if (TINYCLR_SSL_STRCMP(*argv,"-des3") == 0)
			enc=EVP_des_ede3_cbc();
#endif
#ifndef OPENSSL_NO_IDEA
		else if (TINYCLR_SSL_STRCMP(*argv,"-idea") == 0)
			enc=EVP_idea_cbc();
#endif
#ifndef OPENSSL_NO_SEED
		else if (TINYCLR_SSL_STRCMP(*argv,"-seed") == 0)
			enc=EVP_seed_cbc();
#endif
#ifndef OPENSSL_NO_AES
		else if (TINYCLR_SSL_STRCMP(*argv,"-aes128") == 0)
			enc=EVP_aes_128_cbc();
		else if (TINYCLR_SSL_STRCMP(*argv,"-aes192") == 0)
			enc=EVP_aes_192_cbc();
		else if (TINYCLR_SSL_STRCMP(*argv,"-aes256") == 0)
			enc=EVP_aes_256_cbc();
#endif
#ifndef OPENSSL_NO_CAMELLIA
		else if (TINYCLR_SSL_STRCMP(*argv,"-camellia128") == 0)
			enc=EVP_camellia_128_cbc();
		else if (TINYCLR_SSL_STRCMP(*argv,"-camellia192") == 0)
			enc=EVP_camellia_192_cbc();
		else if (TINYCLR_SSL_STRCMP(*argv,"-camellia256") == 0)
			enc=EVP_camellia_256_cbc();
#endif
		else if (TINYCLR_SSL_STRCMP(*argv,"-passout") == 0)
			{
			if (--argc < 1) goto bad;
			passargout= *(++argv);
			}
		else
			break;
		argv++;
		argc--;
		}
	if ((argc >= 1) && ((sscanf(*argv,"%d",&num) == 0) || (num < 0)))
		{
bad:
		BIO_printf(bio_err,"usage: genrsa [args] [numbits]\n");
		BIO_printf(bio_err," -des            encrypt the generated key with DES in cbc mode\n");
		BIO_printf(bio_err," -des3           encrypt the generated key with DES in ede cbc mode (168 bit key)\n");
#ifndef OPENSSL_NO_IDEA
		BIO_printf(bio_err," -idea           encrypt the generated key with IDEA in cbc mode\n");
#endif
#ifndef OPENSSL_NO_SEED
		BIO_printf(bio_err," -seed\n");
		BIO_printf(bio_err,"                 encrypt PEM output with cbc seed\n");
#endif
#ifndef OPENSSL_NO_AES
		BIO_printf(bio_err," -aes128, -aes192, -aes256\n");
		BIO_printf(bio_err,"                 encrypt PEM output with cbc aes\n");
#endif
#ifndef OPENSSL_NO_CAMELLIA
		BIO_printf(bio_err," -camellia128, -camellia192, -camellia256\n");
		BIO_printf(bio_err,"                 encrypt PEM output with cbc camellia\n");
#endif
		BIO_printf(bio_err," -out file       output the key to 'file\n");
		BIO_printf(bio_err," -passout arg    output file pass phrase source\n");
		BIO_printf(bio_err," -f4             use F4 (0x10001) for the E value\n");
		BIO_printf(bio_err," -3              use 3 for the E value\n");
#ifndef OPENSSL_NO_ENGINE
		BIO_printf(bio_err," -engine e       use engine e, possibly a hardware device.\n");
#endif
		BIO_printf(bio_err," -rand file%cfile%c...\n", LIST_SEPARATOR_CHAR, LIST_SEPARATOR_CHAR);
		BIO_printf(bio_err,"                 load the file (or the files in the directory) into\n");
		BIO_printf(bio_err,"                 the random number generator\n");
		goto err;
		}
		
	ERR_load_crypto_strings();

	if(!app_passwd(bio_err, NULL, passargout, NULL, &passout)) {
		BIO_printf(bio_err, "Error getting password\n");
		goto err;
	}

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

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

	if (!app_RAND_load_file(NULL, bio_err, 1) && inrand == NULL
		&& !RAND_status())
		{
		BIO_printf(bio_err,"warning, not much extra random data, consider using the -rand option\n");
		}
	if (inrand != NULL)
		BIO_printf(bio_err,"%ld semi-random bytes loaded\n",
			app_RAND_load_files(inrand));

	BIO_printf(bio_err,"Generating RSA private key, %d bit long modulus\n",
		num);
#ifdef OPENSSL_NO_ENGINE
	rsa = RSA_new();
#else
	rsa = RSA_new_method(e);
#endif
	if (!rsa)
		goto err;

	if(!BN_set_word(bn, f4) || !RSA_generate_key_ex(rsa, num, bn, &cb))
		goto err;
		
	app_RAND_write_file(NULL, bio_err);

	/* We need to do the following for when the base number size is <
	 * long, esp windows 3.1 :-(. */
	l=0L;
	for (i=0; i<rsa->e->top; i++)
		{
#ifndef SIXTY_FOUR_BIT
		l<<=BN_BITS4;
		l<<=BN_BITS4;
#endif
		l+=rsa->e->d[i];
		}
	BIO_printf(bio_err,"e is %ld (0x%lX)\n",l,l);
	{
	PW_CB_DATA cb_data;
	cb_data.password = passout;
	cb_data.prompt_info = outfile;
	if (!PEM_write_bio_RSAPrivateKey(out,rsa,enc,NULL,0,
		(pem_password_cb *)password_callback,&cb_data))
		goto err;
	}

	ret=0;
err:
	if (bn) BN_free(bn);
	if (rsa) RSA_free(rsa);
	if (out) BIO_free_all(out);
	if(passout) OPENSSL_free(passout);
	if (ret != 0)
		ERR_print_errors(bio_err);
	apps_shutdown();
	OPENSSL_EXIT(ret);
	}
예제 #28
0
static ERL_NIF_TERM rsa_generate_key_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
  ERL_NIF_TERM ret;
  ERL_NIF_TERM private_keyterm, public_keyterm;
  BIO *bio_private_pem=NULL, *bio_public_pem=NULL;
  RSA *rsa = NULL;
  BIGNUM *bn_rsa_genkey=NULL;
  int rsa_keylen=-1;
  int private_pemlen, public_pemlen;
  unsigned long f4=RSA_F4;
  int dlen;

  /* BUGBUG: Need better validation of key length here [cb] */
  if (!enif_get_int(env, argv[0], &rsa_keylen)) {
	return enif_make_badarg(env);
  }

  /* Do all allocations and fail function call if any single alloc failed */
  rsa = RSA_new();
  bn_rsa_genkey = BN_new();
  bio_private_pem = BIO_new(BIO_s_mem());
  bio_public_pem = BIO_new(BIO_s_mem());

  /* Do actual OpenSSL work */
  if(rsa && bn_rsa_genkey && bio_private_pem && bio_public_pem){
    BN_set_word(bn_rsa_genkey, f4);

    if (RSA_generate_key_ex(rsa, rsa_keylen, bn_rsa_genkey, NULL)) {
      unsigned char *private_pemdata;
      unsigned char *public_pemdata;

      PEM_write_bio_RSA_PUBKEY(bio_public_pem,rsa);
      PEM_write_bio_RSAPrivateKey(bio_private_pem,rsa,NULL,NULL,0,NULL,NULL);
        
      private_pemlen = BIO_get_mem_data(bio_private_pem, &private_pemdata);
      public_pemlen = BIO_get_mem_data(bio_public_pem, &public_pemdata);
        
      dlen = sizeof(int)+private_pemlen+sizeof(int)+public_pemlen;
      private_pemdata[private_pemlen]=0;
      public_pemdata[public_pemlen]=0;

      memcpy(enif_make_new_binary(env, private_pemlen, &private_keyterm), private_pemdata, private_pemlen);
      memcpy(enif_make_new_binary(env, public_pemlen, &public_keyterm), public_pemdata, public_pemlen);
      ret = enif_make_tuple3(env, atom_ok, public_keyterm, private_keyterm);
    }
    else {
      ret = enif_make_tuple2(env, atom_error, atom_bad_keylen);
    }

  } else {
    ret = enif_make_tuple2(env, atom_error, atom_bad_ssl_init);
  }

  /* dealloc */
  if(bio_private_pem)
    BIO_free_all(bio_private_pem);
  if(bio_public_pem)
    BIO_free_all(bio_public_pem);
  if(bn_rsa_genkey)
    BN_free(bn_rsa_genkey);
  if(rsa)
    RSA_free(rsa);

  return ret;
}
예제 #29
-1
파일: pke.cpp 프로젝트: FollowMyVote/fc
    bytes private_key::serialize()const
    {
       bytes ba;
       if( !my ) { return ba; }

       BIO *mem = BIO_new(BIO_s_mem());
       int e = PEM_write_bio_RSAPrivateKey( mem, my->rsa, NULL, NULL, 0, NULL, NULL );
       if( e != 1 )
       {
           BIO_free(mem);
           FC_THROW_EXCEPTION( exception, "Error writing private key, ${message}", ("message",fc::string(ERR_error_string( ERR_get_error(),NULL))) );
       }
       char* dat;
       uint32_t l = BIO_get_mem_data( mem, &dat );
    //   return bytes( dat, dat + l );

       stringstream ss( string( dat, l ) );
       stringstream key;
       string tmp;
       fc::getline( ss, tmp );
       fc::getline( ss, tmp );

       while( tmp.size() && tmp[0] != '-' )
       {
         key << tmp; 
         fc::getline( ss, tmp );
       }
       auto str = key.str();
       str = fc::base64_decode( str );
       ba = bytes( str.begin(), str.end() );
    //   ba = bytes( dat, dat + l );
       BIO_free(mem);
       return ba;
    }
예제 #30
-1
int main()
{

  RSA *rsa;
  BIO *out;
  int err;

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

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

  BIO_set_fp(out, stdout, BIO_NOCLOSE);

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