Exemple #1
0
static int cardfingerprint(void *ctx,char *file,void *out)
{
	int r=NOCARD;
	int len;
	EVP_PKEY *key;
	RSA *rsa=NULL;
	EC_KEY *ec=NULL;
	ENGINE *e=(ENGINE *)ctx;
	unsigned char bfr[2048];
	unsigned char *p=bfr;

	resume_engine(e,engbits);

	if(!(key=ENGINE_load_public_key(e,file,NULL,NULL)))goto err1;

	r=CRYPTOFAIL;

#if OPENSSL_VERSION_NUMBER >= 0x1010000fL
	if(EVP_PKEY_get0_RSA(key))
	{
		if(!(rsa=EVP_PKEY_get1_RSA(key)))goto err2;
		if((len=i2d_RSA_PUBKEY(rsa,NULL))>sizeof(bfr))goto err3;
		if(i2d_RSA_PUBKEY(rsa,&p)!=len)goto err3;
	}
	else if(EVP_PKEY_get0_EC_KEY(key))
	{
		if(!(ec=EVP_PKEY_get1_EC_KEY(key)))goto err2;
		if((len=i2d_EC_PUBKEY(ec,NULL))>sizeof(bfr))goto err3;
		if(i2d_EC_PUBKEY(ec,&p)!=len)goto err3;
	}
	else goto err2;
#else
	switch(EVP_PKEY_type(key->type))
	{
	case EVP_PKEY_RSA:
		if(!(rsa=EVP_PKEY_get1_RSA(key)))goto err2;
		if((len=i2d_RSA_PUBKEY(rsa,NULL))>sizeof(bfr))goto err3;
		if(i2d_RSA_PUBKEY(rsa,&p)!=len)goto err3;
		break;

	case EVP_PKEY_EC:
		if(!(ec=EVP_PKEY_get1_EC_KEY(key)))goto err2;
		if((len=i2d_EC_PUBKEY(ec,NULL))>sizeof(bfr))goto err3;
		if(i2d_EC_PUBKEY(ec,&p)!=len)goto err3;
		break;

	default:goto err2;
	}
#endif

	if(out)sha256(bfr,len,out);
	r=OK;

err3:	if(rsa)RSA_free(rsa);
	if(ec)EC_KEY_free(ec);
	memclear(bfr,0,sizeof(bfr));
err2:	EVP_PKEY_free(key);
err1:	suspend_engine(e,&engbits);
	return r;
}
Exemple #2
0
void getPublicKeyRaw(ecc_key_t *pubkeyraw, char *inFile)
{
	EVP_PKEY* pkey;
	EC_KEY *key;
	const EC_GROUP *ecgrp;
	const EC_POINT *ecpoint;
	BIGNUM *pubkeyBN;
	unsigned char pubkeyData[1 + 2*EC_COORDBYTES];

	FILE *fp = fopen( inFile, "r");
	pkey = PEM_read_PrivateKey(fp, NULL, NULL, NULL);
	assert(pkey);

	key = EVP_PKEY_get1_EC_KEY(pkey);
	assert(key);
	ecgrp = EC_KEY_get0_group(key);
	assert(ecgrp);
	ecpoint = EC_KEY_get0_public_key(key);
	assert(ecpoint);
	pubkeyBN = EC_POINT_point2bn(ecgrp, ecpoint, POINT_CONVERSION_UNCOMPRESSED, NULL, NULL);
	BN_bn2bin(pubkeyBN, pubkeyData);

	if (debug)
		printBytes((char *)"pubkey (RAW) = ", &pubkeyData[1], sizeof(pubkeyData) - 1, 32);

	memcpy(*pubkeyraw, &pubkeyData[1], sizeof(ecc_key_t));

	EC_KEY_free(key);
	EVP_PKEY_free(pkey);
	fclose(fp);

	return;
}
Exemple #3
0
SEXP R_ecdsa_priv_decompose(SEXP input){
#ifndef OPENSSL_NO_EC
  BIO *mem = BIO_new_mem_buf(RAW(input), LENGTH(input));
  EVP_PKEY *pkey = d2i_PrivateKey_bio(mem, NULL);
  BIO_free(mem);
  bail(!!pkey);
  EC_KEY *ec = EVP_PKEY_get1_EC_KEY(pkey);
  const EC_POINT *pubkey = EC_KEY_get0_public_key(ec);
  const EC_GROUP *group = EC_KEY_get0_group(ec);
  int nid = EC_GROUP_get_curve_name(group);
  int keysize = nid_keysize(nid);
  BIGNUM *x = BN_new();
  BIGNUM *y = BN_new();
  BIGNUM *z = (BIGNUM*) EC_KEY_get0_private_key(ec);
  BN_CTX *ctx = BN_CTX_new();
  bail(EC_POINT_get_affine_coordinates_GFp(group, pubkey, x, y, ctx));
  BN_CTX_free(ctx);
  SEXP res = PROTECT(allocVector(VECSXP, 4));
  SET_VECTOR_ELT(res, 0, mkString(my_nid2nist(nid)));
  SET_VECTOR_ELT(res, 1, bignum_to_r_size(x, keysize));
  SET_VECTOR_ELT(res, 2, bignum_to_r_size(y, keysize));
  SET_VECTOR_ELT(res, 3, bignum_to_r_size(z, keysize));
  BN_free(x);
  BN_free(y);
  EVP_PKEY_free(pkey);
  UNPROTECT(1);
  return res;
#else //OPENSSL_NO_EC
  Rf_error("OpenSSL has been configured without EC support");
#endif //OPENSSL_NO_EC
}
static isc_result_t
opensslecdsa_todns(const dst_key_t *key, isc_buffer_t *data) {
	isc_result_t ret;
	EVP_PKEY *pkey;
	EC_KEY *eckey = NULL;
	isc_region_t r;
	int len;
	unsigned char *cp;
	unsigned char buf[DNS_KEY_ECDSA384SIZE + 1];

	REQUIRE(key->keydata.pkey != NULL);

	pkey = key->keydata.pkey;
	eckey = EVP_PKEY_get1_EC_KEY(pkey);
	if (eckey == NULL)
		return (dst__openssl_toresult(ISC_R_FAILURE));
	len = i2o_ECPublicKey(eckey, NULL);
	/* skip form */
	len--;

	isc_buffer_availableregion(data, &r);
	if (r.length < (unsigned int) len)
		DST_RET (ISC_R_NOSPACE);
	cp = buf;
	if (!i2o_ECPublicKey(eckey, &cp))
		DST_RET (dst__openssl_toresult(ISC_R_FAILURE));
	memmove(r.base, buf + 1, len);
	isc_buffer_add(data, len);
	ret = ISC_R_SUCCESS;

 err:
	if (eckey != NULL)
		EC_KEY_free(eckey);
	return (ret);
}
	EC_KEY* crypt_ec_helper::load_key_pair(std::string path)
	{
		BIO *in;
		int i;
		FILE* infile;
		EVP_PKEY *pkey = NULL;

		ERR_load_BIO_strings();
		ERR_load_crypto_strings();

		pkey = EVP_PKEY_new();

		EC_GROUP *ecgroup = EC_GROUP_new_by_curve_name(NID_secp256k1);

		infile = fopen(path.c_str(), "r");

		in = BIO_new(BIO_s_file());
		in = BIO_new_fp(infile, BIO_NOCLOSE);

		PEM_read_bio_PrivateKey(in, &pkey, NULL, NULL);

		fclose(infile);

		eckey = EVP_PKEY_get1_EC_KEY(pkey);

		EC_GROUP_free(ecgroup);
		EVP_PKEY_free(pkey);
		BIO_free_all(in);

		return eckey;
	}
Exemple #6
0
blob WSService::pubkey_from_cert(X509* x509) {
	std::runtime_error e("Certificate error");

	EC_GROUP* ec_group = EC_GROUP_new_by_curve_name(OBJ_sn2nid("prime256v1"));
	BN_CTX* bn_ctx = BN_CTX_new();

	std::vector<uint8_t> raw_public(33);

	try {
		if(ec_group == NULL || bn_ctx == NULL) throw e;

		EVP_PKEY* remote_pkey = X509_get_pubkey(x509);	if(remote_pkey == NULL) throw e;
		EC_KEY* remote_eckey = EVP_PKEY_get1_EC_KEY(remote_pkey);	if(remote_eckey == NULL) throw e;
		const EC_POINT* remote_pubkey = EC_KEY_get0_public_key(remote_eckey);	if(remote_pubkey == NULL) throw e;

		EC_POINT_point2oct(ec_group, remote_pubkey, POINT_CONVERSION_COMPRESSED, raw_public.data(), raw_public.size(), bn_ctx);
	}catch(...){
		BN_CTX_free(bn_ctx); EC_GROUP_free(ec_group);
		bn_ctx = NULL; ec_group = NULL;

		throw;
	}

	BN_CTX_free(bn_ctx); EC_GROUP_free(ec_group);

	return raw_public;
}
static int sign_ec(EVP_PKEY* pkey, keymaster_ec_sign_params_t* sign_params, const uint8_t* data,
                   const size_t dataLength, uint8_t** signedData, size_t* signedDataLength) {
    if (sign_params->digest_type != DIGEST_NONE) {
        ALOGW("Cannot handle digest type %d", sign_params->digest_type);
        return -1;
    }

    Unique_EC_KEY eckey(EVP_PKEY_get1_EC_KEY(pkey));
    if (eckey.get() == NULL) {
        logOpenSSLError("openssl_sign_ec");
        return -1;
    }

    unsigned int ecdsaSize = ECDSA_size(eckey.get());
    UniquePtr<uint8_t, Malloc_Free> signedDataPtr(reinterpret_cast<uint8_t*>(malloc(ecdsaSize)));
    if (signedDataPtr.get() == NULL) {
        logOpenSSLError("openssl_sign_ec");
        return -1;
    }

    unsigned char* tmp = reinterpret_cast<unsigned char*>(signedDataPtr.get());
    if (ECDSA_sign(0, data, dataLength, tmp, &ecdsaSize, eckey.get()) <= 0) {
        logOpenSSLError("openssl_sign_ec");
        return -1;
    }

    *signedDataLength = ecdsaSize;
    *signedData = signedDataPtr.release();

    return 0;
}
Exemple #8
0
unsigned char get_algorithm(EVP_PKEY *key) {
  int type = EVP_PKEY_type(key->type);
  switch(type) {
    case EVP_PKEY_RSA:
      {
        RSA *rsa = EVP_PKEY_get1_RSA(key);
        int size = RSA_size(rsa);
        if(size == 256) {
          return YKPIV_ALGO_RSA2048;
        } else if(size == 128) {
          return YKPIV_ALGO_RSA1024;
        } else {
          fprintf(stderr, "Unuseable key of %d bits, only 1024 and 2048 is supported.\n", size * 8);
          return 0;
        }
      }
    case EVP_PKEY_EC:
      {
        EC_KEY *ec = EVP_PKEY_get1_EC_KEY(key);
        const EC_GROUP *group = EC_KEY_get0_group(ec);
        int curve = EC_GROUP_get_curve_name(group);
        if(curve == NID_X9_62_prime256v1) {
          return YKPIV_ALGO_ECCP256;
        } else {
          fprintf(stderr, "Unknown EC curve %d\n", curve);
          return 0;
        }
      }
    default:
      fprintf(stderr, "Unknown algorithm %d.\n", type);
      return 0;
  }
}
static isc_result_t
ecdsa_check(EC_KEY *eckey, dst_key_t *pub)
{
	isc_result_t ret = ISC_R_FAILURE;
	EVP_PKEY *pkey;
	EC_KEY *pubeckey = NULL;
	const EC_POINT *pubkey;

	if (pub == NULL)
		return (ISC_R_SUCCESS);
	pkey = pub->keydata.pkey;
	if (pkey == NULL)
		return (ISC_R_SUCCESS);
	pubeckey = EVP_PKEY_get1_EC_KEY(pkey);
	if (pubeckey == NULL)
		return (ISC_R_SUCCESS);
	pubkey = EC_KEY_get0_public_key(pubeckey);
	if (pubkey == NULL)
		DST_RET (ISC_R_SUCCESS);
	if (EC_KEY_set_public_key(eckey, pubkey) != 1)
		DST_RET (ISC_R_SUCCESS);
	if (EC_KEY_check_key(eckey) == 1)
		DST_RET (ISC_R_SUCCESS);

 err:
	if (pubeckey != NULL)
		EC_KEY_free(pubeckey);
	return (ret);
}
Exemple #10
0
SEXP R_pubkey_bitsize(SEXP input){
  BIO *mem = BIO_new_mem_buf(RAW(input), LENGTH(input));
  EVP_PKEY *pkey = d2i_PUBKEY_bio(mem, NULL);
  BIO_free(mem);
  if(!pkey)
    return R_NilValue;
  int size = 0;
  const BIGNUM * val;
  switch(EVP_PKEY_base_id(pkey)){
  case EVP_PKEY_RSA:
    MY_RSA_get0_key(EVP_PKEY_get1_RSA(pkey), &val, NULL, NULL);
    size = BN_num_bits(val);
    break;
  case EVP_PKEY_DSA:
    MY_DSA_get0_pqg(EVP_PKEY_get1_DSA(pkey), &val, NULL, NULL);
    size = BN_num_bits(val);
    break;
#ifndef OPENSSL_NO_EC
  case EVP_PKEY_EC:
    size = ec_bitsize(EC_GROUP_get_curve_name(EC_KEY_get0_group(EVP_PKEY_get1_EC_KEY(pkey))));
    break;
#endif //OPENSSL_NO_EC
  default:
    Rf_error("Unsupported key type: %d", EVP_PKEY_base_id(pkey));
  }
  EVP_PKEY_free(pkey);
  return ScalarInteger(size);
}
Exemple #11
0
static EC_KEY *ecdh_auto_cb(SSL *ssl, int is_export, int keylength)
{
	static EC_KEY *ecdh;
	int last_nid;
	int nid = 0;
	EVP_PKEY *pk;
	EC_KEY *ec;

	/* pick curve from EC key */
	pk = SSL_get_privatekey(ssl);
	if (pk && pk->type == EVP_PKEY_EC) {
		ec = EVP_PKEY_get1_EC_KEY(pk);
		if (ec) {
			nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec));
			EC_KEY_free(ec);
		}
	}

	/* ssl->tlsext_ellipticcurvelist is empty, nothing else to do... */
	if (nid == 0)
		nid = NID_X9_62_prime256v1;

	if (ecdh) {
		last_nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(ecdh));
		if (last_nid == nid)
			return ecdh;
		EC_KEY_free(ecdh);
		ecdh = NULL;
	}

	ecdh = EC_KEY_new_by_curve_name(nid);
	return ecdh;
}
Exemple #12
0
int s2n_evp_pkey_to_ecdsa_private_key(s2n_ecdsa_private_key *ecdsa_key, EVP_PKEY *evp_private_key)
{
    EC_KEY *ec_key = EVP_PKEY_get1_EC_KEY(evp_private_key);
    S2N_ERROR_IF(ec_key == NULL, S2N_ERR_DECODE_PRIVATE_KEY);
    
    ecdsa_key->ec_key = ec_key;
    return 0;
}
Exemple #13
0
int s2n_evp_pkey_to_ecdsa_public_key(s2n_ecdsa_public_key *ecdsa_key, EVP_PKEY *evp_public_key)
{
    EC_KEY *ec_key = EVP_PKEY_get1_EC_KEY(evp_public_key);
    S2N_ERROR_IF(ec_key == NULL, S2N_ERR_DECODE_CERTIFICATE);
    
    ecdsa_key->ec_key = ec_key;
    return 0;
}
Exemple #14
0
BUF_MEM *
Comp(EVP_PKEY *key, const BUF_MEM *pub, BN_CTX *bn_ctx, EVP_MD_CTX *md_ctx)
{
    BUF_MEM *out = NULL;
    const EC_GROUP *group;
    EC_POINT *ecp = NULL;
    EC_KEY *ec = NULL;
    BIGNUM *x = NULL, *y = NULL;

    check((key && pub), "Invalid arguments");

    switch (EVP_PKEY_base_id(key)) {
        case EVP_PKEY_DH:
            out = hash(EVP_sha1(), md_ctx, NULL, pub);
            break;

        case EVP_PKEY_EC:
            ec = EVP_PKEY_get1_EC_KEY(key);
            if (!ec)
                goto err;

            group = EC_KEY_get0_group(ec);
            ecp = EC_POINT_new(group);
            x = BN_CTX_get(bn_ctx);
            y = BN_CTX_get(bn_ctx);

            if(!ecp || !x || !y
                    || !EC_POINT_oct2point(group, ecp,
                        (unsigned char *) pub->data, pub->length, bn_ctx)
                    || !EC_POINT_get_affine_coordinates_GF2m(group, ecp, x, y, bn_ctx))
                goto err;

            out = BUF_MEM_create(BN_num_bytes(x));
            if(!out || !BN_bn2bin(x, (unsigned char *) out->data))
                goto err;
            break;

        default:
            log_err("Unknown protocol");
            goto err;
    }

err:
    if (ecp)
        EC_POINT_free(ecp);
    /* Decrease the reference count, the key is still available in the EVP_PKEY
     * structure */
    if (ec)
        EC_KEY_free(ec);
    if (x)
        BN_free(x);
    if (y)
        BN_free(y);

    return out;
}
static isc_boolean_t
opensslecdsa_compare(const dst_key_t *key1, const dst_key_t *key2) {
	isc_boolean_t ret;
	int status;
	EVP_PKEY *pkey1 = key1->keydata.pkey;
	EVP_PKEY *pkey2 = key2->keydata.pkey;
	EC_KEY *eckey1 = NULL;
	EC_KEY *eckey2 = NULL;
	const BIGNUM *priv1, *priv2;

	if (pkey1 == NULL && pkey2 == NULL)
		return (ISC_TRUE);
	else if (pkey1 == NULL || pkey2 == NULL)
		return (ISC_FALSE);

	eckey1 = EVP_PKEY_get1_EC_KEY(pkey1);
	eckey2 = EVP_PKEY_get1_EC_KEY(pkey2);
	if (eckey1 == NULL && eckey2 == NULL) {
		DST_RET (ISC_TRUE);
	} else if (eckey1 == NULL || eckey2 == NULL)
		DST_RET (ISC_FALSE);

	status = EVP_PKEY_cmp(pkey1, pkey2);
	if (status != 1)
		DST_RET (ISC_FALSE);

	priv1 = EC_KEY_get0_private_key(eckey1);
	priv2 = EC_KEY_get0_private_key(eckey2);
	if (priv1 != NULL || priv2 != NULL) {
		if (priv1 == NULL || priv2 == NULL)
			DST_RET (ISC_FALSE);
		if (BN_cmp(priv1, priv2) != 0)
			DST_RET (ISC_FALSE);
	}
	ret = ISC_TRUE;

 err:
	if (eckey1 != NULL)
		EC_KEY_free(eckey1);
	if (eckey2 != NULL)
		EC_KEY_free(eckey2);
	return (ret);
}
static isc_boolean_t
opensslecdsa_isprivate(const dst_key_t *key) {
	isc_boolean_t ret;
	EVP_PKEY *pkey = key->keydata.pkey;
	EC_KEY *eckey = EVP_PKEY_get1_EC_KEY(pkey);

	ret = ISC_TF(eckey != NULL && EC_KEY_get0_private_key(eckey) != NULL);
	if (eckey != NULL)
		EC_KEY_free(eckey);
	return (ret);
}
Exemple #17
0
static void pkcs11_update_ex_data_ec(PKCS11_KEY *key)
{
	EVP_PKEY *evp = key->evp_key;
	EC_KEY *ec;
	if (evp == NULL)
		return;
	if (EVP_PKEY_base_id(evp) != EVP_PKEY_EC)
		return;

	ec = EVP_PKEY_get1_EC_KEY(evp);
	pkcs11_set_ex_data_ec(ec, key);
	EC_KEY_free(ec);
}
Exemple #18
0
static EC_KEY *pkey_get_eckey(EVP_PKEY *key, EC_KEY **eckey)
{
  EC_KEY *dtmp;
  if(!key) return NULL;
  dtmp = EVP_PKEY_get1_EC_KEY(key);
  EVP_PKEY_free(key);
  if(!dtmp) return NULL;
  if(eckey) 
  {
     EC_KEY_free(*eckey);
    *eckey = dtmp;
  }
  return dtmp;
}
Exemple #19
0
static isc_result_t
opensslecdsa_verify(dst_context_t *dctx, const isc_region_t *sig) {
	isc_result_t ret;
	dst_key_t *key = dctx->key;
	int status;
	unsigned char *cp = sig->base;
	ECDSA_SIG *ecdsasig = NULL;
	EVP_MD_CTX *evp_md_ctx = dctx->ctxdata.evp_md_ctx;
	EVP_PKEY *pkey = key->keydata.pkey;
	EC_KEY *eckey = EVP_PKEY_get1_EC_KEY(pkey);
	unsigned int dgstlen, siglen;
	unsigned char digest[EVP_MAX_MD_SIZE];

	REQUIRE(key->key_alg == DST_ALG_ECDSA256 ||
		key->key_alg == DST_ALG_ECDSA384);

	if (eckey == NULL)
		return (ISC_R_FAILURE);

	if (key->key_alg == DST_ALG_ECDSA256)
		siglen = DNS_SIG_ECDSA256SIZE;
	else
		siglen = DNS_SIG_ECDSA384SIZE;

	if (sig->length != siglen)
		return (DST_R_VERIFYFAILURE);

	if (!EVP_DigestFinal_ex(evp_md_ctx, digest, &dgstlen))
		DST_RET (ISC_R_FAILURE);

	ecdsasig = ECDSA_SIG_new();
	if (ecdsasig == NULL)
		DST_RET (ISC_R_NOMEMORY);
	ecdsasig->r = BN_bin2bn(cp, siglen / 2, NULL);
	cp += siglen / 2;
	ecdsasig->s = BN_bin2bn(cp, siglen / 2, NULL);
	/* cp += siglen / 2; */

	status = ECDSA_do_verify(digest, dgstlen, ecdsasig, eckey);
	if (status != 1)
		DST_RET (dst__openssl_toresult(DST_R_VERIFYFAILURE));
	ret = ISC_R_SUCCESS;

 err:
	if (ecdsasig != NULL)
		ECDSA_SIG_free(ecdsasig);
	if (eckey != NULL)
		EC_KEY_free(eckey);
	return (ret);
}
static isc_result_t
opensslecdsa_sign(dst_context_t *dctx, isc_buffer_t *sig) {
	isc_result_t ret;
	dst_key_t *key = dctx->key;
	isc_region_t r;
	ECDSA_SIG *ecdsasig;
	EVP_MD_CTX *evp_md_ctx = dctx->ctxdata.evp_md_ctx;
	EVP_PKEY *pkey = key->keydata.pkey;
	EC_KEY *eckey = EVP_PKEY_get1_EC_KEY(pkey);
	unsigned int dgstlen, siglen;
	unsigned char digest[EVP_MAX_MD_SIZE];

	REQUIRE(key->key_alg == DST_ALG_ECDSA256 ||
		key->key_alg == DST_ALG_ECDSA384);

	if (eckey == NULL)
		return (ISC_R_FAILURE);

	if (key->key_alg == DST_ALG_ECDSA256)
		siglen = DNS_SIG_ECDSA256SIZE;
	else
		siglen = DNS_SIG_ECDSA384SIZE;

	isc_buffer_availableregion(sig, &r);
	if (r.length < siglen)
		DST_RET(ISC_R_NOSPACE);

	if (!EVP_DigestFinal(evp_md_ctx, digest, &dgstlen))
		DST_RET(dst__openssl_toresult3(dctx->category,
					       "EVP_DigestFinal",
					       ISC_R_FAILURE));

	ecdsasig = ECDSA_do_sign(digest, dgstlen, eckey);
	if (ecdsasig == NULL)
		DST_RET(dst__openssl_toresult3(dctx->category,
					       "ECDSA_do_sign",
					       DST_R_SIGNFAILURE));
	BN_bn2bin_fixed(ecdsasig->r, r.base, siglen / 2);
	r.base += siglen / 2;
	BN_bn2bin_fixed(ecdsasig->s, r.base, siglen / 2);
	r.base += siglen / 2;
	ECDSA_SIG_free(ecdsasig);
	isc_buffer_add(sig, siglen);
	ret = ISC_R_SUCCESS;

 err:
	if (eckey != NULL)
		EC_KEY_free(eckey);
	return (ret);
}
Exemple #21
0
static void set_server_temporary_key_info(TLS_REC *tls, SSL *ssl)
{
#ifdef SSL_get_server_tmp_key
	/* Show ephemeral key information. */
	EVP_PKEY *ephemeral_key = NULL;

	/* OPENSSL_NO_EC is for solaris 11.3 (2016), github ticket #598 */
#ifndef OPENSSL_NO_EC
	EC_KEY *ec_key = NULL;
#endif
	char *ephemeral_key_algorithm = NULL;
	char *cname = NULL;
	int nid;

	g_return_if_fail(tls != NULL);
	g_return_if_fail(ssl != NULL);

	if (SSL_get_server_tmp_key(ssl, &ephemeral_key)) {
		switch (EVP_PKEY_id(ephemeral_key)) {
			case EVP_PKEY_DH:
				tls_rec_set_ephemeral_key_algorithm(tls, "DH");
				tls_rec_set_ephemeral_key_size(tls, EVP_PKEY_bits(ephemeral_key));
				break;

#ifndef OPENSSL_NO_EC
			case EVP_PKEY_EC:
				ec_key = EVP_PKEY_get1_EC_KEY(ephemeral_key);
				nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec_key));
				EC_KEY_free(ec_key);
				cname = (char *)OBJ_nid2sn(nid);
				ephemeral_key_algorithm = g_strdup_printf("ECDH: %s", cname);

				tls_rec_set_ephemeral_key_algorithm(tls, ephemeral_key_algorithm);
				tls_rec_set_ephemeral_key_size(tls, EVP_PKEY_bits(ephemeral_key));

				g_free_and_null(ephemeral_key_algorithm);
				break;
#endif

			default:
				tls_rec_set_ephemeral_key_algorithm(tls, "Unknown");
				tls_rec_set_ephemeral_key_size(tls, EVP_PKEY_bits(ephemeral_key));
				break;
		}

		EVP_PKEY_free(ephemeral_key);
	}
#endif /* SSL_get_server_tmp_key. */
}
TEST_F(KeymasterTest, SignData_EC_Success) {
    uint8_t* key_blob;
    size_t key_blob_length;

    UniqueReadOnlyBlob testKey(TEST_SIGN_EC_KEY_1, sizeof(TEST_SIGN_EC_KEY_1));
    ASSERT_TRUE(testKey.get() != NULL);

    ASSERT_EQ(0,
            sDevice->import_keypair(sDevice, testKey.get(), testKey.length(),
                    &key_blob, &key_blob_length))
            << "Should successfully import an EC key";
    UniqueKey key(&sDevice, key_blob, key_blob_length);

    keymaster_ec_sign_params_t params = {
            .digest_type = DIGEST_NONE,
    };

    uint8_t* sig;
    size_t sig_length;

    UniqueReadOnlyBlob testData(TEST_SIGN_DATA_1, sizeof(TEST_SIGN_DATA_1));
    ASSERT_TRUE(testData.get() != NULL);

    ASSERT_EQ(0,
            sDevice->sign_data(sDevice, &params, key_blob, key_blob_length,
                    testData.get(), testData.length(),
                    &sig, &sig_length))
            << "Should sign data successfully";
    UniqueBlob sig_blob(sig, sig_length);

    uint8_t* x509_data;
    size_t x509_data_length;
    ASSERT_EQ(0,
            sDevice->get_keypair_public(sDevice, key_blob, key_blob_length,
                    &x509_data, &x509_data_length))
            << "Should be able to retrieve RSA public key successfully";
    UniqueBlob x509_blob(x509_data, x509_data_length);

    const unsigned char *tmp = static_cast<const unsigned char*>(x509_blob.get());
    Unique_EVP_PKEY expected(d2i_PUBKEY((EVP_PKEY**) NULL, &tmp,
            static_cast<long>(x509_blob.length())));

    Unique_EC_KEY ecKey(EVP_PKEY_get1_EC_KEY(expected.get()));

    ASSERT_EQ(1, ECDSA_verify(0, testData.get(), testData.length(), sig_blob.get(), sig_blob.length(), ecKey.get()))
            << "Signature should verify";
}
Exemple #23
0
static int
lws_context_ssl_init_ecdh(struct lws_vhost *vhost)
{
#ifdef LWS_SSL_SERVER_WITH_ECDH_CERT
	EC_KEY *EC_key = NULL;
	EVP_PKEY *pkey;
	int KeyType;
	X509 *x;

	if (!lws_check_opt(vhost->context->options, LWS_SERVER_OPTION_SSL_ECDH))
		return 0;

	lwsl_notice(" Using ECDH certificate support\n");

	/* Get X509 certificate from ssl context */
	x = sk_X509_value(vhost->ssl_ctx->extra_certs, 0);
	if (!x) {
		lwsl_err("%s: x is NULL\n", __func__);
		return 1;
	}
	/* Get the public key from certificate */
	pkey = X509_get_pubkey(x);
	if (!pkey) {
		lwsl_err("%s: pkey is NULL\n", __func__);

		return 1;
	}
	/* Get the key type */
	KeyType = EVP_PKEY_type(pkey->type);

	if (EVP_PKEY_EC != KeyType) {
		lwsl_notice("Key type is not EC\n");
		return 0;
	}
	/* Get the key */
	EC_key = EVP_PKEY_get1_EC_KEY(pkey);
	/* Set ECDH parameter */
	if (!EC_key) {
		lwsl_err("%s: ECDH key is NULL \n", __func__);
		return 1;
	}
	SSL_CTX_set_tmp_ecdh(vhost->ssl_ctx, EC_key);
	EC_KEY_free(EC_key);
#endif
	return 0;
}
// Decode from PKCS#8 BER
bool OSSLECPrivateKey::PKCS8Decode(const ByteString& ber)
{
	int len = ber.size();
	if (len <= 0) return false;
	const unsigned char* priv = ber.const_byte_str();
	PKCS8_PRIV_KEY_INFO* p8 = d2i_PKCS8_PRIV_KEY_INFO(NULL, &priv, len);
	if (p8 == NULL) return false;
	EVP_PKEY* pkey = EVP_PKCS82PKEY(p8);
	PKCS8_PRIV_KEY_INFO_free(p8);
	if (pkey == NULL) return false;
	EC_KEY* key = EVP_PKEY_get1_EC_KEY(pkey);
	EVP_PKEY_free(pkey);
	if (key == NULL) return false;
	setFromOSSL(key);
	EC_KEY_free(key);
	return true;
}
Exemple #25
0
	std::string CreateFamilySignature (const std::string& family, const IdentHash& ident)
	{
		auto filename = i2p::fs::DataDirPath("family", (family + ".key"));
		std::string sig;
		SSL_CTX * ctx = SSL_CTX_new (TLS_method ());
		int ret = SSL_CTX_use_PrivateKey_file (ctx, filename.c_str (), SSL_FILETYPE_PEM);
		if (ret)
		{
			SSL * ssl = SSL_new (ctx);
			EVP_PKEY * pkey = SSL_get_privatekey (ssl);
			EC_KEY * ecKey = EVP_PKEY_get1_EC_KEY (pkey);
			if (ecKey)
			{
				auto group = EC_KEY_get0_group (ecKey);
				if (group)
				{
					int curve = EC_GROUP_get_curve_name (group);
					if (curve == NID_X9_62_prime256v1)
					{
						uint8_t signingPrivateKey[32], buf[50], signature[64];
						i2p::crypto::bn2buf (EC_KEY_get0_private_key (ecKey), signingPrivateKey, 32);
						i2p::crypto::ECDSAP256Signer signer (signingPrivateKey);
						size_t len = family.length ();
						memcpy (buf, family.c_str (), len);
						memcpy (buf + len, (const uint8_t *)ident, 32);
						len += 32;
						signer.Sign (buf, len, signature);
						len = Base64EncodingBufferSize (64);
						char * b64 = new char[len+1];
						len = ByteStreamToBase64 (signature, 64, b64, len);
						b64[len] = 0;
						sig = b64;
						delete[] b64;
					}
					else
						LogPrint (eLogWarning, "Family: elliptic curve ", curve, " is not supported");
				}
			}
			SSL_free (ssl);
		}
		else
			LogPrint (eLogError, "Family: Can't open keys file: ", filename);
		SSL_CTX_free (ctx);
		return sig;
	}
Exemple #26
0
u2fs_rc extract_EC_KEY_from_X509(const u2fs_X509_t * cert,
                                 u2fs_EC_KEY_t ** key)
{
  if (cert == NULL || key == NULL)
    return U2FS_MEMORY_ERROR;

  EVP_PKEY *pkey = X509_get_pubkey((X509 *) cert);

  if (pkey == NULL) {
    if (debug) {
      unsigned long err = 0;
      err = ERR_get_error();
      fprintf(stderr, "Error: %s, %s, %s\n",
              ERR_lib_error_string(err),
              ERR_func_error_string(err), ERR_reason_error_string(err));
    }
    return U2FS_CRYPTO_ERROR;
  }

  *key = (u2fs_EC_KEY_t *) EVP_PKEY_get1_EC_KEY(pkey);

  EVP_PKEY_free(pkey);
  pkey = NULL;

  if (*key == NULL) {
    if (debug) {
      unsigned long err = 0;
      err = ERR_get_error();
      fprintf(stderr, "Error: %s, %s, %s\n",
              ERR_lib_error_string(err),
              ERR_func_error_string(err), ERR_reason_error_string(err));
    }
    return U2FS_CRYPTO_ERROR;
  }

  EC_GROUP *ecg = EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1);

  EC_KEY_set_asn1_flag((EC_KEY *) * key, OPENSSL_EC_NAMED_CURVE);
  EC_KEY_set_group((EC_KEY *) * key, ecg);

  EC_GROUP_free(ecg);
  ecg = NULL;

  return U2FS_OK;
}
Exemple #27
0
EC_KEY *d2i_EC_PUBKEY(EC_KEY **a, const unsigned char **pp, long length)
	{
	EVP_PKEY *pkey;
	EC_KEY *key;
	const unsigned char *q;
	q = *pp;
	pkey = d2i_PUBKEY(NULL, &q, length);
	if (!pkey) return(NULL);
	key = EVP_PKEY_get1_EC_KEY(pkey);
	EVP_PKEY_free(pkey);
	if (!key)  return(NULL);
	*pp = q;
	if (a)
		{
		EC_KEY_free(*a);
		*a = key;
		}
	return(key);
	}
Exemple #28
0
int extract_and_print_eckey(EVP_PKEY* pubkey, int version) {
  assert(pubkey);

  EC_KEY* eckey = EVP_PKEY_get1_EC_KEY(pubkey);
  if (!eckey) {
    fprintf(stderr, "error: EVP_PKEY_get1_EC_KEY() failed.\n");
    return 2;
  }

  if (!EC_KEY_check_key(eckey)) {
    fprintf(stderr, "error: EC_KEY_check_key() failed.\n");
    EC_KEY_free(eckey);
    return 2;
  }
  
  int result = convert_eckey_to_x962_and_print(eckey, version);
  EC_KEY_free(eckey);
  return result;
}
static
PKCS11H_BOOL
__pkcs11h_openssl_session_setECDSA(
	IN const pkcs11h_openssl_session_t openssl_session,
	IN EVP_PKEY * evp
) {
	PKCS11H_BOOL ret = FALSE;
	EC_KEY *ec = NULL;

	_PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: __pkcs11h_openssl_session_setECDSA - entered openssl_session=%p, evp=%p",
		(void *)openssl_session,
		(void *)evp
	);

	if (
		(ec = EVP_PKEY_get1_EC_KEY (evp)) == NULL
	) {
		_PKCS11H_LOG (PKCS11H_LOG_WARN, "PKCS#11: Cannot get EC key");
		goto cleanup;
	}

	ECDSA_set_method (ec, __openssl_methods.ecdsa);
	ECDSA_set_ex_data (ec, __openssl_methods.ecdsa_index, openssl_session);

	ret = TRUE;

cleanup:

	if (ec != NULL) {
		EC_KEY_free (ec);
		ec = NULL;
	}

	_PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: __pkcs11h_openssl_session_setECDSA - return ret=%d",
		ret
	);

	return ret;
}
static isc_result_t
opensslecdsa_tofile(const dst_key_t *key, const char *directory) {
	isc_result_t ret;
	EVP_PKEY *pkey;
	EC_KEY *eckey = NULL;
	const BIGNUM *privkey;
	dst_private_t priv;
	unsigned char *buf = NULL;

	if (key->keydata.pkey == NULL)
		return (DST_R_NULLKEY);

	if (key->external) {
		priv.nelements = 0;
		return (dst__privstruct_writefile(key, &priv, directory));
	}

	pkey = key->keydata.pkey;
	eckey = EVP_PKEY_get1_EC_KEY(pkey);
	if (eckey == NULL)
		return (dst__openssl_toresult(DST_R_OPENSSLFAILURE));
	privkey = EC_KEY_get0_private_key(eckey);
	if (privkey == NULL)
		DST_RET (ISC_R_FAILURE);

	buf = isc_mem_get(key->mctx, BN_num_bytes(privkey));
	if (buf == NULL)
		DST_RET (ISC_R_NOMEMORY);

	priv.elements[0].tag = TAG_ECDSA_PRIVATEKEY;
	priv.elements[0].length = BN_num_bytes(privkey);
	BN_bn2bin(privkey, buf);
	priv.elements[0].data = buf;
	priv.nelements = 1;
	ret = dst__privstruct_writefile(key, &priv, directory);

 err:
	if (eckey != NULL)
		EC_KEY_free(eckey);
	if (buf != NULL)
		isc_mem_put(key->mctx, buf, BN_num_bytes(privkey));
	return (ret);
}