Exemplo n.º 1
0
int SSL_use_RSAPrivateKey(SSL *ssl, RSA *rsa)
	{
	EVP_PKEY *pkey;
	int ret;

	if (rsa == NULL)
		{
		SSLerr(SSL_F_SSL_USE_RSAPRIVATEKEY,ERR_R_PASSED_NULL_PARAMETER);
		return(0);
		}
	if (!ssl_cert_inst(&ssl->cert))
		{
		SSLerr(SSL_F_SSL_USE_RSAPRIVATEKEY,ERR_R_MALLOC_FAILURE);
		return(0);
		}
	if ((pkey=EVP_PKEY_new()) == NULL)
		{
		SSLerr(SSL_F_SSL_USE_RSAPRIVATEKEY,ERR_R_EVP_LIB);
		return(0);
		}

	RSA_up_ref(rsa);
	EVP_PKEY_assign_RSA(pkey,rsa);

	ret=ssl_set_pkey(ssl->cert,pkey);
	EVP_PKEY_free(pkey);
	return(ret);
	}
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;
}
EVP_PKEY* AuthorityCertificateManager::buildKeysForClient() {
  RSA *rsaKeyPair          = RSA_generate_key(1024, RSA_F4, NULL, NULL);
  EVP_PKEY *rsaKeyPairSpec = EVP_PKEY_new();
  
  EVP_PKEY_assign_RSA(rsaKeyPairSpec, rsaKeyPair);

  return rsaKeyPairSpec;
}
Exemplo n.º 4
0
int
EVP_PKEY_set1_RSA(EVP_PKEY *pkey, RSA *key)
{
	int ret = EVP_PKEY_assign_RSA(pkey, key);
	if (ret)
		RSA_up_ref(key);
	return ret;
}
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;
}
Exemplo n.º 6
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;
}
Exemplo n.º 7
0
Certificate::Certificate(const string& _subject, const string& _issuer, const string& _validity, const Node::Id_t _owner, RSA *_rsaPubKey) : 
#ifdef DEBUG_LEAKS
LeakMonitor(LEAK_TYPE_CERTIFICATE),
#endif
	stored(false), verified(false), hasSignature(false), x(NULL), subject(_subject), issuer(_issuer), validity(_validity), pubKey(NULL), rsaPubKey(NULL), x509_PEM_str(NULL)
{
	memcpy(owner, _owner, sizeof(Node::Id_t));
	
	x = X509_new();
	
	if (!x) {
		HAGGLE_ERR("Could not allocate X509 certificate struct\n");
		return;
	}
	
	X509_set_version(x, 2); 
	
	pubKey = EVP_PKEY_new();
	
	if (!pubKey) {
		X509_free(x);
		HAGGLE_ERR("Could not allocate X509 EVP_PKEY\n");
		return;
	}
	
	EVP_PKEY_assign_RSA(pubKey, RSAPublicKey_dup(_rsaPubKey));
	
	X509_set_pubkey(x, pubKey);
	rsaPubKey = EVP_PKEY_get1_RSA(pubKey);

	/* Set validity.
	 FIXME: currently hardcoded
	 */
	int days = 30;
	X509_gmtime_adj(X509_get_notBefore(x),0);
	X509_gmtime_adj(X509_get_notAfter(x),(long)60*60*24*days);

	X509_NAME *subject_name = X509_get_subject_name(x);
	
	/* Set subject */
	//X509_NAME_add_entry_by_txt(subname,"C", MBSTRING_ASC, "SE", -1, -1, 0); 
	X509_NAME_add_entry_by_txt(subject_name, "CN", MBSTRING_ASC, (const unsigned char *)subject.c_str(), -1, -1, 0); 
	X509_NAME_add_entry_by_txt(subject_name, "O", MBSTRING_ASC, (const unsigned char *)"Haggle", -1, -1, 0);  
	
	X509_set_subject_name(x, subject_name); 

	/* Set issuer */
	X509_NAME *issuer_name = X509_get_issuer_name(x);
	
	X509_NAME_add_entry_by_txt(issuer_name, "CN", MBSTRING_ASC, (const unsigned char *)issuer.c_str(), -1, -1, 0); 
	X509_NAME_add_entry_by_txt(issuer_name, "O", MBSTRING_ASC, (const unsigned char *)"Haggle", -1, -1, 0);  
	
	X509_set_issuer_name(x, issuer_name);
        
        //HAGGLE_DBG("Subject=\'%s\' issuer=\'%s\'\n", subject.c_str(), issuer.c_str());

        certificate_set_serial(x);
}
Exemplo n.º 8
0
static int old_rsa_priv_decode(EVP_PKEY *pkey, const unsigned char **pder,
                               int derlen) {
  RSA *rsa = d2i_RSAPrivateKey(NULL, pder, derlen);
  if (rsa == NULL) {
    OPENSSL_PUT_ERROR(EVP, old_rsa_priv_decode, ERR_R_RSA_LIB);
    return 0;
  }
  EVP_PKEY_assign_RSA(pkey, rsa);
  return 1;
}
Exemplo n.º 9
0
int
mono_btls_key_assign_rsa_private_key (EVP_PKEY *pkey, uint8_t *der_data, int der_length)
{
	RSA *rsa;

	rsa = RSA_private_key_from_bytes (der_data, der_length);
	if (!rsa)
		return 0;

	return EVP_PKEY_assign_RSA (pkey, rsa);
}
Exemplo n.º 10
0
static int old_rsa_priv_decode(EVP_PKEY *pkey,
                               const unsigned char **pder, int derlen)
{
    RSA *rsa;
    if (!(rsa = d2i_RSAPrivateKey(NULL, pder, derlen))) {
        RSAerr(RSA_F_OLD_RSA_PRIV_DECODE, ERR_R_RSA_LIB);
        return 0;
    }
    EVP_PKEY_assign_RSA(pkey, rsa);
    return 1;
}
Exemplo n.º 11
0
static void mkcert(std::shared_ptr<X509> &cert,
                  std::shared_ptr<EVP_PKEY> &pkey, int bits, int serial,
                  int days)
{
    RSA *rsa;
    X509_NAME *name=NULL;

    pkey.reset(EVP_PKEY_new(), &EVP_PKEY_free);
    if (!pkey)
        throw std::bad_alloc();
    cert.reset(X509_new(), &X509_free);
    if (!cert)
        throw std::bad_alloc();

    rsa = RSA_generate_key(bits,RSA_F4,NULL,NULL);
    MORDOR_VERIFY(EVP_PKEY_assign_RSA(pkey.get(),rsa));

    X509_set_version(cert.get(),2);
    ASN1_INTEGER_set(X509_get_serialNumber(cert.get()),serial);
    X509_gmtime_adj(X509_get_notBefore(cert.get()),0);
    X509_gmtime_adj(X509_get_notAfter(cert.get()),(long)60*60*24*days);
    X509_set_pubkey(cert.get(),pkey.get());

    name=X509_get_subject_name(cert.get());

    /* This function creates and adds the entry, working out the
     * correct string type and performing checks on its length.
     * Normally we'd check the return value for errors...
     */
    X509_NAME_add_entry_by_txt(name,"C",
                            MBSTRING_ASC,
                            (const unsigned char *)"United States",
                            -1, -1, 0);
    X509_NAME_add_entry_by_txt(name,"CN",
                            MBSTRING_ASC,
                            (const unsigned char *)"Mordor Default Self-signed Certificate",
                            -1, -1, 0);

    /* Its self signed so set the issuer name to be the same as the
     * subject.
     */
    X509_set_issuer_name(cert.get(),name);

    /* Add various extensions: standard extensions */
    add_ext(cert.get(), NID_basic_constraints, "critical,CA:TRUE");
    add_ext(cert.get(), NID_key_usage, "critical,keyCertSign,cRLSign");

    add_ext(cert.get(), NID_subject_key_identifier, "hash");

    /* Some Netscape specific extensions */
    add_ext(cert.get(), NID_netscape_cert_type, "sslCA");

    MORDOR_VERIFY(X509_sign(cert.get(),pkey.get(),EVP_md5()));
}
uint32 CRegProtocol::CreatePrivateKey(char *name, 
                                      EVP_PKEY **key)
{
    TU_RET err = TU_ERROR_CRYPTO_FAILED;
    RSA *rsaKey;
    EVP_PKEY *pkey;
    FILE *fp;

    rsaKey = RSA_generate_key(1024, 65537, NULL, NULL);
    if(rsaKey == NULL)
    {
        TUTRACE((TUTRACE_ERR, "Couldn't generate RSA key\n"));
        goto EXIT;
    }

    //Now store it in a PKEY
    pkey = EVP_PKEY_new();
    if(!pkey)
    {
        TUTRACE((TUTRACE_ERR, "Couldn't generate new EVP key\n"));
        goto EXIT;
    }

    if(!EVP_PKEY_assign_RSA(pkey, rsaKey))
    {
        TUTRACE((TUTRACE_ERR, "Couldn't assign RSA key to EVP key\n"));
        RSA_free(rsaKey);
        goto EXIT;
    }

    fp = fopen(name, "w");
    
    if(!PEM_write_PKCS8PrivateKey(fp, pkey, NULL, NULL, 0, NULL, NULL))
    {
        TUTRACE((TUTRACE_ERR, "Error writing Signing key to file\n"));
        fclose(fp);
        goto ERR_EVP;
    }
    
    fclose(fp);

    if(key)
        *key = pkey;
    else
        EVP_PKEY_free(pkey);

    return TU_SUCCESS;

ERR_EVP:
    EVP_PKEY_free(pkey);
EXIT:
    return err;
}
Exemplo n.º 13
0
void openssl_evp_asycrypt()
{
	RSA *rkey;
	BIGNUM *bne;
	EVP_PKEY *pubkey[2];
	EVP_CIPHER_CTX ctx1, ctx2;
	int i, ekl[2], len1 = 0, len2 = 0, len3 = 0;
	unsigned char ins[] = "openssl asymmetric encrypt test";
	unsigned char iv[8], pen[MAX1_LEN], *ek[2], sde[MAX1_LEN];

	ek[0] = (unsigned char *)malloc(MAX1_LEN);
	ek[1] = (unsigned char *)malloc(MAX1_LEN);
	memset(pen, 0, MAX1_LEN);
	memset(sde, 0, MAX1_LEN);
	memset(ek[0], 0, MAX1_LEN);
	memset(ek[1], 0, MAX1_LEN);

	bne = BN_new();
	BN_set_word(bne, RSA_3);
	rkey = RSA_new();
	RSA_generate_key_ex(rkey, MAX1_LEN, bne, NULL);
	pubkey[0] = EVP_PKEY_new();
	EVP_PKEY_assign_RSA(pubkey[0], rkey);

	EVP_CIPHER_CTX_init(&ctx1);
	EVP_SealInit(&ctx1, EVP_des_ede3_cbc(), ek, ekl, iv, pubkey, 1);
	EVP_SealUpdate(&ctx1, pen, &len1, ins, strlen((char *)ins));
	EVP_SealFinal(&ctx1, pen + len1, &len3);
	len1 += len3;
	printf("\nEVP_ASYEncry(%s) = ", ins);
	for (i = 0; i < len1; i++)
		printf("0x%.02x ", pen[i]);
	printf("\n");
	EVP_CIPHER_CTX_cleanup(&ctx1);

	len3 = 0;
	EVP_CIPHER_CTX_init(&ctx2);
	EVP_OpenInit(&ctx2, EVP_des_ede3_cbc(), ek[0], ekl[0], iv, pubkey[0]);
	EVP_OpenUpdate(&ctx2, sde, &len2, pen, len1);
	EVP_OpenFinal(&ctx2, sde + len2, &len3);
	len2 += len3;
	printf("EVP_ASYDecry(");
	for (i = 0; i < len1; i++)
		printf("0x%.02x ", pen[i]);
	printf(") = %s\n", sde);
	EVP_CIPHER_CTX_cleanup(&ctx2);

	free(ek[0]);
	free(ek[1]);
	EVP_PKEY_free(pubkey[0]);
	BN_free(bne);
}
Exemplo n.º 14
0
Try<EVP_PKEY*> generate_private_rsa_key(int bits, unsigned long _exponent)
{
  // Allocate the in-memory structure for the private key.
  EVP_PKEY* private_key = EVP_PKEY_new();
  if (private_key == NULL) {
    return Error("Failed to allocate key: EVP_PKEY_new");
  }

  // Allocate space for the exponent.
  BIGNUM* exponent = BN_new();
  if (exponent == NULL) {
    EVP_PKEY_free(private_key);
    return Error("Failed to allocate exponent: BN_new");
  }

  // Assign the exponent.
  if (BN_set_word(exponent, _exponent) != 1) {
    BN_free(exponent);
    EVP_PKEY_free(private_key);
    return Error("Failed to set exponent: BN_set_word");
  }

  // Allocate the in-memory structure for the key pair.
  RSA* rsa = RSA_new();
  if (rsa == NULL) {
    BN_free(exponent);
    EVP_PKEY_free(private_key);
    return Error("Failed to allocate RSA: RSA_new");
  }

  // Generate the RSA key pair.
  if (RSA_generate_key_ex(rsa, bits, exponent, NULL) != 1) {
    RSA_free(rsa);
    BN_free(exponent);
    EVP_PKEY_free(private_key);
    return Error(ERR_error_string(ERR_get_error(), NULL));
  }

  // We no longer need the exponent, so let's free it.
  BN_free(exponent);

  // Associate the RSA key with the private key. If this association
  // is successful, then the RSA key will be freed when the private
  // key is freed.
  if (EVP_PKEY_assign_RSA(private_key, rsa) != 1) {
    RSA_free(rsa);
    EVP_PKEY_free(private_key);
    return Error("Failed to assign RSA key: EVP_PKEY_assign_RSA");
  }

  return private_key;
}
Exemplo n.º 15
0
int generateKeysRSA(EVP_PKEY** privKey, EVP_PKEY** pubKey){
	RSA* rsa =  NULL;
	if(privKey == NULL || pubKey == NULL)
		return 0;

	*privKey = EVP_PKEY_new();
	if(*privKey == NULL){
		printf("ERR EVP_PKEY_new\n");
		return 0;
	}

	*pubKey = EVP_PKEY_new();
	if(*pubKey == NULL){
		printf("ERR EVP_PKEY_new\n");
		return 0;
	}
	
	rsa = RSA_generate_key(2048, RSA_F4, NULL, NULL);
	
	if(rsa == NULL){
		printf("ERR RSA_generate_key\n");
		return 0;		
	}
	
	if(1 != EVP_PKEY_assign_RSA(*privKey, 
						RSAPrivateKey_dup(rsa))){
		
		printf("ERR EVP_PKEY_assign_RSA\n");
		return 0;
	}

	if(1 != EVP_PKEY_assign_RSA(*pubKey, 
						RSAPublicKey_dup(rsa))){
		
		printf("ERR EVP_PKEY_assign_RSA\n");
		return 0;
	}
	return 1;
}
Exemplo n.º 16
0
SEXP PKI_RSAkeygen(SEXP sBits) {
    EVP_PKEY *key;
    RSA *rsa;
    int bits = asInteger(sBits);
    if (bits < 512)
	Rf_error("invalid key size");
    rsa = RSA_generate_key(bits, 65537, 0, 0);
    if (!rsa)
	Rf_error("%s", ERR_error_string(ERR_get_error(), NULL));
    key = EVP_PKEY_new();
    EVP_PKEY_assign_RSA(key, rsa);
    return wrap_EVP_PKEY(key, PKI_KT_PRIVATE | PKI_KT_PUBLIC);
}
Exemplo n.º 17
0
static int rsa_pub_decode(EVP_PKEY *pkey, X509_PUBKEY *pubkey)
{
    const unsigned char *p;
    int pklen;
    RSA *rsa = NULL;
    if (!X509_PUBKEY_get0_param(NULL, &p, &pklen, NULL, pubkey))
        return 0;
    if (!(rsa = d2i_RSAPublicKey(NULL, &p, pklen))) {
        RSAerr(RSA_F_RSA_PUB_DECODE, ERR_R_RSA_LIB);
        return 0;
    }
    EVP_PKEY_assign_RSA(pkey, rsa);
    return 1;
}
Exemplo n.º 18
0
/* Return 0 if OK, -1 otherwise */
static int
verifyCertChain (BYTE *rootMod, UINT32 rootModLen, UINT32 nCerts, BYTE *certs)
{
	X509		*tbsX509 = NULL;
	EVP_PKEY	*pkey = NULL;
	RSA			*rsa;
	BYTE		*pCert;
	UINT32		certLen;
	int			rslt = -1;
	int			i, j;

	EVP_add_digest(EVP_sha1());
	pkey = EVP_PKEY_new ();
	rsa = RSA_new ();
	rsa->n = BN_bin2bn (rootMod, rootModLen, rsa->n);
	rsa->e = BN_new();
	BN_set_word (rsa->e, 0x10001);
	EVP_PKEY_assign_RSA (pkey, rsa);

	for (i=nCerts-1; i>=0; i--) {
		pCert = certs;
		for (j=0; j<i; j++) {
			certLen = (pCert[0]<<16) | (pCert[1]<<8) | pCert[2];
			pCert += 3 + certLen;
		}
		certLen = (pCert[0]<<16) | (pCert[1]<<8) | pCert[2];
		pCert += 3;
		tbsX509 = d2i_X509 (NULL, (unsigned char const **)&pCert, certLen);
		if (!tbsX509)
			goto done;
		if (X509_verify (tbsX509, pkey) != 1)
			goto done;
		if (i > 0) {
			EVP_PKEY_free (pkey);
			pkey = X509_get_pubkey(tbsX509);
			if (pkey == NULL)
				goto done;
		}
		X509_free (tbsX509);
		tbsX509 = NULL;
	}
	/* Success */
	rslt = 0;
done:
	if (pkey)
		EVP_PKEY_free (pkey);
	if (tbsX509)
		X509_free (tbsX509);
	return rslt;
}
Exemplo n.º 19
0
EVP_PKEY *load_pubkey(const char *file)
{

    RSA *rsa_pkey = NULL;
    BIO *rsa_pkey_file = NULL;
    EVP_PKEY *pkey = EVP_PKEY_new();

    // Create a new BIO file structure to be used with PEM file
    rsa_pkey_file = BIO_new(BIO_s_file());
    if (rsa_pkey_file == NULL)
    {
        fprintf(stderr, "Error crating a new BIO file.\n");
        ERR_print_errors_fp(stderr);
        goto end;
    }

    // Read PEM file using BIO's file structure
    if (BIO_read_filename(rsa_pkey_file, file) <= 0)
    {
        fprintf(stderr, "Error opening %s\n",file);
        ERR_print_errors_fp(stderr);
        goto end;
    }

    // Read RSA based PEM file into rsa_pkey structure
    if (!PEM_read_bio_RSA_PUBKEY(rsa_pkey_file, &rsa_pkey, NULL, NULL))
    {
        fprintf(stderr, "Error loading RSA Public Key File.\n");
        ERR_print_errors_fp(stderr);
        goto end;
    }

    // Populate pkey with the rsa key. rsa_pkey is owned by pkey,
    // therefore if we free pkey, rsa_pkey will be freed  too
    if (!EVP_PKEY_assign_RSA(pkey, rsa_pkey))
    {
        fprintf(stderr, "Error assigning EVP_PKEY_assign_RSA: failed.\n");
        goto end;
    }

end:
    if (rsa_pkey_file != NULL)
        BIO_free(rsa_pkey_file);
    if (pkey == NULL)
    {
        fprintf(stderr, "Error unable to load %s\n", file);
        ERR_print_errors_fp(stderr);
    }
    return(pkey);
}
Exemplo n.º 20
0
void pki_evp::veryOldFromData(unsigned char *p, int size )
{
	unsigned char *sik, *pdec, *pdec1, *sik1;
	int outl, decsize;
	unsigned char iv[EVP_MAX_IV_LENGTH];
	unsigned char ckey[EVP_MAX_KEY_LENGTH];
	memset(iv, 0, EVP_MAX_IV_LENGTH);
	RSA *rsakey;
	EVP_CIPHER_CTX ctx;
	const EVP_CIPHER *cipher = EVP_des_ede3_cbc();
	sik = (unsigned char *)OPENSSL_malloc(size);
	check_oom(sik);
	pki_openssl_error();
	pdec = (unsigned char *)OPENSSL_malloc(size);
	if (pdec == NULL ) {
		OPENSSL_free(sik);
		check_oom(pdec);
	}
	pdec1=pdec;
	sik1=sik;
	memcpy(iv, p, 8); /* recover the iv */
	/* generate the key */
	EVP_BytesToKey(cipher, EVP_sha1(), iv, (unsigned char *)oldpasswd,
		strlen(oldpasswd), 1, ckey,NULL);
	/* we use sha1 as message digest,
	 * because an md5 version of the password is
	 * stored in the database...
	 */
	EVP_CIPHER_CTX_init (&ctx);
	EVP_DecryptInit( &ctx, cipher, ckey, iv);
	EVP_DecryptUpdate( &ctx, pdec , &outl, p + 8, size -8 );
	decsize = outl;
	EVP_DecryptFinal( &ctx, pdec + decsize , &outl );
	decsize += outl;
	pki_openssl_error();
	memcpy(sik, pdec, decsize);
	if (key->type == EVP_PKEY_RSA) {
		rsakey=d2i_RSAPrivateKey(NULL,(const unsigned char **)&pdec, decsize);
		if (pki_ign_openssl_error()) {
			rsakey = d2i_RSA_PUBKEY(NULL, (const unsigned char **)&sik, decsize);
		}
		pki_openssl_error();
		if (rsakey) EVP_PKEY_assign_RSA(key, rsakey);
	}
	OPENSSL_free(sik1);
	OPENSSL_free(pdec1);
	EVP_CIPHER_CTX_cleanup(&ctx);
	pki_openssl_error();
	encryptKey();
}
Exemplo n.º 21
0
SEXP PKI_load_public_RSA(SEXP what) {
    EVP_PKEY *key;
    RSA *rsa = 0;
    const unsigned char *ptr;
    if (TYPEOF(what) != RAWSXP)
	Rf_error("key must be a raw vector");
    ptr = (const unsigned char *) RAW(what);
    rsa = d2i_RSA_PUBKEY(&rsa, &ptr, LENGTH(what));
    if (!rsa)
	Rf_error("%s", ERR_error_string(ERR_get_error(), NULL));
    key = EVP_PKEY_new();
    EVP_PKEY_assign_RSA(key, rsa);
    return wrap_EVP_PKEY(key, PKI_KT_PUBLIC);
}
Exemplo n.º 22
0
void pki_evp::generate(int bits, int type, QProgressBar *progress, int curve_nid)
{
	RSA *rsakey;
	DSA *dsakey;
	EC_KEY *eckey;

	progress->setMinimum(0);
	progress->setMaximum(100);
	progress->setValue(50);

	switch (type) {
	case EVP_PKEY_RSA:
		rsakey = RSA_generate_key(bits, 0x10001, inc_progress_bar,
			progress);
		if (rsakey)
			EVP_PKEY_assign_RSA(key, rsakey);
		break;
	case EVP_PKEY_DSA:
		progress->setMaximum(500);
		dsakey = DSA_generate_parameters(bits, NULL, 0, NULL, NULL,
				inc_progress_bar, progress);
		DSA_generate_key(dsakey);
		if (dsakey)
			EVP_PKEY_assign_DSA(key, dsakey);
		break;
	case EVP_PKEY_EC:
		EC_GROUP *group = EC_GROUP_new_by_curve_name(curve_nid);
		if (!group)
			break;
		eckey = EC_KEY_new();
		if (eckey == NULL) {
			EC_GROUP_free(group);
			break;
		}
		EC_GROUP_set_asn1_flag(group, 1);
		if (EC_KEY_set_group(eckey, group)) {
			if (EC_KEY_generate_key(eckey)) {
				EVP_PKEY_assign_EC_KEY(key, eckey);
				EC_GROUP_free(group);
				break;
			}
		}
		EC_KEY_free(eckey);
		EC_GROUP_free(group);
		break;
	}
	pki_openssl_error();
	encryptKey();
}
Exemplo n.º 23
0
Settings::KeyPair CertWizard::generateNewCert(QString qsname, const QString &qsemail) {
	CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);

	X509 *x509 = X509_new();
	EVP_PKEY *pkey = EVP_PKEY_new();
	RSA *rsa = RSA_generate_key(2048,RSA_F4,NULL,NULL);
	EVP_PKEY_assign_RSA(pkey, rsa);

	X509_set_version(x509, 2);
	ASN1_INTEGER_set(X509_get_serialNumber(x509),1);
	X509_gmtime_adj(X509_get_notBefore(x509),0);
	X509_gmtime_adj(X509_get_notAfter(x509),60*60*24*365*20);
	X509_set_pubkey(x509, pkey);

	X509_NAME *name=X509_get_subject_name(x509);

	if (qsname.isEmpty())
		qsname = tr("Mumble User");

	X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, reinterpret_cast<unsigned char *>(qsname.toUtf8().data()), -1, -1, 0);
	X509_set_issuer_name(x509, name);
	add_ext(x509, NID_basic_constraints, SSL_STRING("critical,CA:FALSE"));
	add_ext(x509, NID_ext_key_usage, SSL_STRING("clientAuth"));
	add_ext(x509, NID_subject_key_identifier, SSL_STRING("hash"));
	add_ext(x509, NID_netscape_comment, SSL_STRING("Generated by Mumble"));
	add_ext(x509, NID_subject_alt_name, QString::fromLatin1("email:%1").arg(qsemail).toUtf8().data());

	X509_sign(x509, pkey, EVP_sha1());

	QByteArray crt, key;

	crt.resize(i2d_X509(x509, NULL));
	unsigned char *dptr=reinterpret_cast<unsigned char *>(crt.data());
	i2d_X509(x509, &dptr);

	QSslCertificate qscCert = QSslCertificate(crt, QSsl::Der);

	key.resize(i2d_PrivateKey(pkey, NULL));
	dptr=reinterpret_cast<unsigned char *>(key.data());
	i2d_PrivateKey(pkey, &dptr);

	QSslKey qskKey = QSslKey(key, QSsl::Rsa, QSsl::Der);

	QList<QSslCertificate> qlCert;
	qlCert << qscCert;

	return Settings::KeyPair(qlCert, qskKey);
}
Exemplo n.º 24
0
static int rsa_pub_decode(EVP_PKEY *pkey, X509_PUBKEY *pubkey) {
  const uint8_t *p;
  int pklen;
  RSA *rsa;

  if (!X509_PUBKEY_get0_param(NULL, &p, &pklen, NULL, pubkey)) {
    return 0;
  }
  rsa = d2i_RSAPublicKey(NULL, &p, pklen);
  if (rsa == NULL) {
    OPENSSL_PUT_ERROR(EVP, rsa_pub_decode, ERR_R_RSA_LIB);
    return 0;
  }
  EVP_PKEY_assign_RSA(pkey, rsa);
  return 1;
}
Exemplo n.º 25
0
std::string
CertificateManager::generateRSACertificate ()
{
  RSA *rsa;
  std::shared_ptr <EVP_PKEY> private_key;
  std::string pem;
  std::string rsaKey;
  std::string certificateRSA;

  rsa = RSA_generate_key(2048, RSA_F4, nullptr, nullptr);

  if (rsa == nullptr) {
    GST_ERROR ("RSA not created");
    return certificateRSA;
  }

  private_key = std::shared_ptr <EVP_PKEY> (EVP_PKEY_new (),
  [] (EVP_PKEY * obj) {
    EVP_PKEY_free (obj);
  });

  if (private_key == nullptr) {
    GST_ERROR ("Private key not created");
    RSA_free (rsa);
    return certificateRSA;
  }

  if (EVP_PKEY_assign_RSA (private_key.get(), rsa) == 0) {
    GST_ERROR ("Private key not assigned");
    RSA_free (rsa);
    return certificateRSA;
  }

  rsa = nullptr;

  pem = generateCertificate (private_key.get() );

  if (pem.empty () ) {
    GST_WARNING ("Certificate not generated");
    return certificateRSA;
  }

  rsaKey = privateKeyToPEMString (private_key.get() );
  certificateRSA = rsaKey + pem;

  return certificateRSA;
}
Exemplo n.º 26
0
static void Init() {
    ctx = SSL_CTX_new(SSLv23_method());
    const uint8_t *bufp = kRSAPrivateKeyDER;
    RSA *privkey = d2i_RSAPrivateKey(NULL, &bufp, sizeof(kRSAPrivateKeyDER));
    OPENSSL_assert(privkey != NULL);
    EVP_PKEY *pkey = EVP_PKEY_new();
    EVP_PKEY_assign_RSA(pkey, privkey);
    int ret = SSL_CTX_use_PrivateKey(ctx, pkey);
    OPENSSL_assert(ret == 1);
    EVP_PKEY_free(pkey);
    bufp = kCertificateDER;
    X509 *cert = d2i_X509(NULL, &bufp, sizeof(kCertificateDER));
    OPENSSL_assert(cert != NULL);
    ret = SSL_CTX_use_certificate(ctx, cert);
    OPENSSL_assert(ret == 1);
    X509_free(cert);
  }
Exemplo n.º 27
0
static int rsa_priv_decode(EVP_PKEY *pkey, PKCS8_PRIV_KEY_INFO *p8) {
  const uint8_t *p;
  int pklen;
  if (!PKCS8_pkey_get0(NULL, &p, &pklen, NULL, p8)) {
    OPENSSL_PUT_ERROR(EVP, ERR_R_MALLOC_FAILURE);
    return 0;
  }

  RSA *rsa = RSA_private_key_from_bytes(p, pklen);
  if (rsa == NULL) {
    OPENSSL_PUT_ERROR(EVP, ERR_R_RSA_LIB);
    return 0;
  }

  EVP_PKEY_assign_RSA(pkey, rsa);
  return 1;
}
Exemplo n.º 28
0
int COsslKey::setPublicKey( sqbind::CSqBinary *pBin )
{_STT();

	Destroy();

	if ( !pBin || !pBin->getUsed() )
		return 0;

	m_pkey = EVP_PKEY_new();
	if ( !m_pkey )
	{	oexERROR( 0, oexT( "EVP_PKEY_new() failed" ) );
		Destroy();
		return 0;
	} // end if

	BIO *pBio = BIO_new_mem_buf( pBin->_Ptr(), pBin->getUsed() );
	if ( !pBio )
	{	oexERROR( 0, oexT( "BIO_new_mem_buf() failed" ) );
		Destroy();
		return 0;
	} // end if

	RSA *rsa = PEM_read_bio_RSAPublicKey( pBio, oexNULL, oexNULL, (void*)getPasswordPtr() );
	if ( !rsa )
		rsa = PEM_read_bio_RSA_PUBKEY( pBio, oexNULL, oexNULL, (void*)getPasswordPtr() );
	if ( !rsa )
	{	const char *pErr = ERR_reason_error_string( ERR_get_error() );
		oexERROR( 0, oexMks( oexT( "PEM_read_bio_RSAPublicKey(), PEM_read_bio_RSA_PUBKEY() failed : " ), 
							 pErr ? oexMbToStr( pErr ) : oexT( "Unknown" ) ) );
		Destroy();
		return 0;
	} // end if

	// Assign key
	if ( !EVP_PKEY_assign_RSA( m_pkey, rsa ) )
	{	oexERROR( 0, oexT( "EVP_PKEY_assign_RSA() failed" ) );
		Destroy();
		return 0;
	} // end if
	rsa = oexNULL;

	BIO_free( pBio );

	return 1;
}
Exemplo n.º 29
0
void openssl_evp_rsacripher()
{
	RSA *rkey;
	BIGNUM *bne;
	EVP_PKEY *pubkey[2];
	const EVP_CIPHER *type;
	EVP_CIPHER_CTX ctx1, ctx2;
	int i, ekl[2], total = 0, len1 = 0, len2 = 0;
	const unsigned char ins[COMM_LEN] = "openssl evp";
	unsigned char outs[LINE_LEN], iv[8], *ek[2], de[LINE_LEN];

	bne = BN_new();
	BN_set_word(bne, RSA_3);
	rkey = RSA_new();
	RSA_generate_key_ex(rkey, MAX1_LEN, bne, NULL);
	pubkey[0] = EVP_PKEY_new();
	EVP_PKEY_assign_RSA(pubkey[0], rkey);
	type = EVP_des_cbc();

	ek[0] = malloc(LINE_LEN);
	ek[1] = malloc(LINE_LEN);
	EVP_CIPHER_CTX_init(&ctx1);
	EVP_SealInit(&ctx1, type, ek, ekl, iv, pubkey, 1);
	EVP_SealUpdate(&ctx1, outs, &total, ins, 11);
	EVP_SealFinal(&ctx1, outs + total, &len1);
	total += len1;
	printf("\nEVP_RSASEAL(%s) = ", ins);
	for (i = 0; i < total; i++)
		printf("0x%.02x ", outs[i]);
	EVP_CIPHER_CTX_cleanup(&ctx1);
	
	memset(de, 0, LINE_LEN);
	EVP_CIPHER_CTX_init(&ctx2);
	EVP_OpenInit(&ctx2, EVP_des_cbc(), ek[0], ekl[0], iv, pubkey[0]);
	EVP_OpenUpdate(&ctx2, de, &len2, outs, total);
	EVP_OpenFinal(&ctx2, de + len2, &len1);
	len2 += len1;
	printf("= %s\n", de);
	EVP_CIPHER_CTX_cleanup(&ctx2);

	free(ek[0]);
	free(ek[1]);
	EVP_PKEY_free(pubkey[0]);
	BN_free(bne);
}
Exemplo n.º 30
0
static EVP_PKEY *
gen_key()
{
  EVP_PKEY *pkey = EVP_PKEY_new();
  BIGNUM *exponent = BN_new();
  RSA *rsa = RSA_new();
  if (!pkey || !exponent || !rsa ||
      !BN_set_word(exponent, 0x10001) || // 65537
      !RSA_generate_key_ex(rsa, 1024, exponent, NULL) ||
      !EVP_PKEY_assign_RSA(pkey, rsa)) {
    EVP_PKEY_free(pkey);
    BN_free(exponent);
    RSA_free(rsa);
    return NULL;
  }
  BN_free(exponent);
  return pkey;
}