Exemplo n.º 1
0
static int eckey_pub_encode(X509_PUBKEY *pk, const EVP_PKEY *pkey)
	{
	EC_KEY *ec_key = pkey->pkey.ec;
	void *pval = NULL;
	int ptype;
	unsigned char *penc = NULL, *p;
	int penclen;

	if (!eckey_param2type(&ptype, &pval, ec_key))
		{
		ECerr(EC_F_ECKEY_PUB_ENCODE, ERR_R_EC_LIB);
		return 0;
		}
	penclen = i2o_ECPublicKey(ec_key, NULL);
	if (penclen <= 0)
		goto err;
	penc = OPENSSL_malloc(penclen);
	if (!penc)
		goto err;
	p = penc;
	penclen = i2o_ECPublicKey(ec_key, &p);
	if (penclen <= 0)
		goto err;
	if (X509_PUBKEY_set0_param(pk, OBJ_nid2obj(EVP_PKEY_EC),
				ptype, pval, penc, penclen))
		return 1;
	err:
	if (ptype == V_ASN1_OBJECT)
		ASN1_OBJECT_free(pval);
	else
		ASN1_STRING_free(pval);
	if (penc)
		OPENSSL_free(penc);
	return 0;
	}
Exemplo n.º 2
0
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);
}
Exemplo n.º 3
0
CPubKey CKey::GetPubKey() const
{
    int nSize = i2o_ECPublicKey(pkey, NULL);
    if (!nSize)
        throw key_error("CKey::GetPubKey() : i2o_ECPublicKey failed");
    std::vector<unsigned char> vchPubKey(nSize, 0);
    unsigned char* pbegin = &vchPubKey[0];
    if (i2o_ECPublicKey(pkey, &pbegin) != nSize)
        throw key_error("CKey::GetPubKey() : i2o_ECPublicKey returned unexpected size");
    return CPubKey(vchPubKey);
}
Exemplo n.º 4
0
void CECKey::GetPubKey(CPubKey &pubkey, bool fCompressed) {
    EC_KEY_set_conv_form(pkey, fCompressed ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED);
    int nSize = i2o_ECPublicKey(pkey, NULL);
    assert(nSize);
    assert(nSize <= 65);
    unsigned char c[65];
    unsigned char *pbegin = c;
    int nSize2 = i2o_ECPublicKey(pkey, &pbegin);
    assert(nSize == nSize2);
    pubkey.Set(&c[0], &c[nSize]);
}
Exemplo n.º 5
0
void CECKey::GetPubKey(std::vector<unsigned char> &pubkey, bool fCompressed) {
    EC_KEY_set_conv_form(pkey, fCompressed ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED);
    int nSize = i2o_ECPublicKey(pkey, NULL);
    assert(nSize);
    assert(nSize <= 65);
    pubkey.clear();
    pubkey.resize(nSize);
    unsigned char *pbegin(begin_ptr(pubkey));
    int nSize2 = i2o_ECPublicKey(pkey, &pbegin);
    assert(nSize == nSize2);
}
		data_chunk elliptic_curve_key::public_key() const
		{
			// same as get_private_key
			int length = i2o_ECPublicKey(key_, NULL);
			if (!length)
				return data_chunk();
			data_chunk pubkey(length, 0);
			uint8_t* pubkey_begin = pubkey.data();
			if (i2o_ECPublicKey(key_, &pubkey_begin) != length)
				return data_chunk();
			return pubkey;
		}
Exemplo n.º 7
0
bool bp_pubkey_get(struct bp_key *key, void **pubkey, size_t *pk_len)
{
	if (!EC_KEY_check_key(key->k))
		return false;

	size_t sz = i2o_ECPublicKey(key->k, 0);
	unsigned char *orig_mem, *mem = malloc(sz);
	orig_mem = mem;
	i2o_ECPublicKey(key->k, &mem);

	*pubkey = orig_mem;
	*pk_len = sz;

	return true;
}
 public_key_point_data public_key::serialize_ecc_point()const
 {
   public_key_point_data dat;
   if( !my->_key ) return dat;
   EC_KEY_set_conv_form( my->_key, POINT_CONVERSION_UNCOMPRESSED );
   char* front = &dat.data[0];
   i2o_ECPublicKey( my->_key, (unsigned char**)&front ); // FIXME: questionable memory handling
   return dat;
 }
Exemplo n.º 9
0
Arquivo: main.c Projeto: aszrul/atheme
int
main(int argc, const char **argv)
{
	if (! libathemecore_early_init())
		return EXIT_FAILURE;

	BIO *out;
	EC_KEY *prv;
	unsigned char *workbuf, *workbuf_p;
	char encbuf[BUFSIZE];
	size_t len;

	memset(encbuf, '\0', sizeof encbuf);

	prv = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);

	EC_KEY_set_conv_form(prv, POINT_CONVERSION_COMPRESSED);
	EC_KEY_generate_key(prv);

	len = i2o_ECPublicKey(prv, NULL);
	workbuf = mowgli_alloc(len);
	workbuf_p = workbuf;
	i2o_ECPublicKey(prv, &workbuf_p);
	workbuf_p = workbuf;

	if (base64_encode(workbuf_p, len, encbuf, sizeof encbuf) == (size_t) -1)
	{
		fprintf(stderr, "Failed to encode public key!\n");
		return EXIT_FAILURE;
	}

	printf("Keypair:\n");
	EC_KEY_print_fp(stdout, prv, 4);

	printf("Private key:\n");
	out = BIO_new_fp(stdout, 0);
	PEM_write_bio_ECPrivateKey(out, prv, NULL, NULL, 0, NULL, NULL);

	printf("Public key (atheme format):\n");
	printf("%s\n", encbuf);

	return EXIT_SUCCESS;
}
Exemplo n.º 10
0
static bool key_get_pubkey_int(struct key *k, uint8 **pub, size_t *len) {
  uint8 *data;

  ASSERT(pub);
  *pub = NULL;
  *len = 0;

  if (!EC_KEY_check_key(k->key)) {
    NOT_TESTED();
    return 0;
  }

  *len = i2o_ECPublicKey(k->key, 0);
  ASSERT(*len <= 65);
  data = safe_malloc(*len);
  *pub = data;
  i2o_ECPublicKey(k->key, &data);

  return 1;
}
Exemplo n.º 11
0
STDMETHODIMP CBECC::get_PublicKey(VARIANT *pVal)
{
	if (m_pECC == NULL)
		return E_NOTIMPL;

	if (!EC_KEY_check_key((EC_KEY*)m_pECC))
		return E_NOTIMPL;

	int nSize;

	if((nSize = i2o_ECPublicKey((EC_KEY*)m_pECC, NULL)) < 0)
		return E_NOTIMPL;

	CBVarPtr varPtr;
	varPtr.Create(nSize);

	if (!i2o_ECPublicKey((EC_KEY*)m_pECC, (unsigned char **)&varPtr.m_pData))
		return E_INVALIDARG;

	return varPtr.GetVariant(pVal);
}
Exemplo n.º 12
0
static int eckey_pub_encode(X509_PUBKEY *pk, const EVP_PKEY *pkey) {
  EC_KEY *ec_key = pkey->pkey.ec;
  void *pval = NULL;
  int ptype;
  uint8_t *penc = NULL, *p;
  int penclen;

  if (!eckey_param2type(&ptype, &pval, ec_key)) {
    OPENSSL_PUT_ERROR(EVP, ERR_R_EC_LIB);
    return 0;
  }
  penclen = i2o_ECPublicKey(ec_key, NULL);
  if (penclen <= 0) {
    goto err;
  }
  penc = OPENSSL_malloc(penclen);
  if (!penc) {
    goto err;
  }
  p = penc;
  penclen = i2o_ECPublicKey(ec_key, &p);
  if (penclen <= 0) {
    goto err;
  }
  if (X509_PUBKEY_set0_param(pk, OBJ_nid2obj(EVP_PKEY_EC), ptype, pval, penc,
                             penclen)) {
    return 1;
  }

err:
  if (ptype == V_ASN1_OBJECT) {
    ASN1_OBJECT_free(pval);
  } else {
    ASN1_STRING_free(pval);
  }
  if (penc) {
    OPENSSL_free(penc);
  }
  return 0;
}
Exemplo n.º 13
0
int i2d_PublicKey(EVP_PKEY *key, uint8_t **outp) {
  switch (key->type) {
    case EVP_PKEY_RSA:
      return i2d_RSAPublicKey(key->pkey.rsa, outp);
    case EVP_PKEY_DSA:
      return i2d_DSAPublicKey(key->pkey.dsa, outp);
    case EVP_PKEY_EC:
      return i2o_ECPublicKey(key->pkey.ec, outp);
    default:
      OPENSSL_PUT_ERROR(EVP, EVP_R_UNSUPPORTED_PUBLIC_KEY_TYPE);
      return -1;
  }
}
Exemplo n.º 14
0
void serialize_ec_point (ec_point const& point, std::uint8_t* ptr)
{
    ec_key key = ec_key_new_secp256k1_compressed();

    if (EC_KEY_set_public_key((EC_KEY*) key.get(), point.get()) <= 0)
    {
        throw std::runtime_error ("EC_KEY_set_public_key() failed");
    }

    int const size = i2o_ECPublicKey ((EC_KEY*) key.get(), &ptr);

    assert (size <= 33);
    (void) size;
}
Exemplo n.º 15
0
ERL_NIF_TERM ucrypto_ec_get_public_key_nif(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[])
{
    int length;
    struct ec_key_handle *handle = NULL;
    ErlNifBinary public_key;

    if (! enif_get_resource(env, argv[0], ec_key_resource, (void **)&handle))
        return enif_make_badarg(env);

    if (! handle->key)
        return enif_make_tuple2(env, ATOM_ERROR, ATOM_UNINITIALIZED_KEY);

    length = i2o_ECPublicKey(handle->key, NULL);

    if (! length)
        return ATOM_ERROR;

    enif_alloc_binary(length, &public_key);

    if (i2o_ECPublicKey(handle->key, &public_key.data) != length)
        return ATOM_ERROR;

    return enif_make_binary(env, &public_key);
}
Exemplo n.º 16
0
 public_key_data public_key::serialize()const
 {
   public_key_data dat;
   if( !my->_key ) return dat;
   EC_KEY_set_conv_form( my->_key, POINT_CONVERSION_COMPRESSED );
   /*size_t nbytes = i2o_ECPublicKey( my->_key, nullptr ); */
   /*assert( nbytes == 33 )*/
   char* front = &dat.data[0];
   i2o_ECPublicKey( my->_key, (unsigned char**)&front ); // FIXME: questionable memory handling
   return dat;
   /*
    EC_POINT* pub   = EC_KEY_get0_public_key( my->_key );
    EC_GROUP* group = EC_KEY_get0_group( my->_key );
    EC_POINT_get_affine_coordinates_GFp( group, pub, self.my->_pub_x.get(), self.my->_pub_y.get(), nullptr );
    */
 }
Exemplo n.º 17
0
Arquivo: mpkgen.c Projeto: 9cat/misc
int main(int argc, char **argv)
{
	unsigned char ecprot[128];
	unsigned char pbuf[1024];
	EC_KEY *pkey;
	EC_POINT *ptnew, *ptmpk, *ptz;
	BIGNUM z;
	unsigned char *pend = (unsigned char *) pbuf, *px;
	unsigned char hash1[32], hashz[32];
	int n, zlen;
	
	if(argc < 3) {
		printf("Usage: %s <mpk> <seq>\n", argv[0]);
		exit(1);
		}

	OpenSSL_add_all_algorithms();
	
	strcpy(pbuf, argv[2]);
	strcat(pbuf, ":0:");
	zlen = strlen(pbuf);
	px = pbuf + zlen;
	for(n=0; n < 64; n++)
		px[n] = hex(argv[1][n*2])*16 + hex(argv[1][n*2+1]);
	SHA256(pbuf, zlen+64, hash1);
	SHA256(hash1, sizeof(hash1), hashz);
	BN_init(&z);
	BN_bin2bn(hashz, 32, &z);
	
	pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
	ptmpk = EC_POINT_new(EC_KEY_get0_group(pkey));
	pbuf[zlen-1] = 0x04;
	EC_POINT_oct2point(EC_KEY_get0_group(pkey), ptmpk, pbuf+zlen-1, 65, NULL);
	ptz = EC_POINT_new(EC_KEY_get0_group(pkey));
	EC_POINT_mul(EC_KEY_get0_group(pkey), ptz, NULL, EC_GROUP_get0_generator(EC_KEY_get0_group(pkey)), &z, NULL);
	ptnew = EC_POINT_new(EC_KEY_get0_group(pkey));
	EC_POINT_add(EC_KEY_get0_group(pkey), ptnew, ptmpk, ptz, NULL);
	EC_KEY_set_public_key(pkey, ptnew);
	i2o_ECPublicKey(pkey, &pend);
	b58encode_address(EC_KEY_get0_public_key(pkey), EC_KEY_get0_group(pkey), 0, ecprot);
	printf("%s\n", ecprot);

}
Exemplo n.º 18
0
int i2d_PublicKey(EVP_PKEY *a, unsigned char **pp)
{
    switch (a->type) {
#ifndef OPENSSL_NO_RSA
    case EVP_PKEY_RSA:
        return (i2d_RSAPublicKey(a->pkey.rsa, pp));
#endif
#ifndef OPENSSL_NO_DSA
    case EVP_PKEY_DSA:
        return (i2d_DSAPublicKey(a->pkey.dsa, pp));
#endif
#ifndef OPENSSL_NO_EC
    case EVP_PKEY_EC:
        return (i2o_ECPublicKey(a->pkey.ec, pp));
#endif
    default:
        ASN1err(ASN1_F_I2D_PUBLICKEY, ASN1_R_UNSUPPORTED_PUBLIC_KEY_TYPE);
        return (-1);
    }
}
Exemplo n.º 19
0
int i2d_PublicKey(const EVP_PKEY *a, unsigned char **pp)
{
    switch (EVP_PKEY_id(a)) {
#ifndef OPENSSL_NO_RSA
    case EVP_PKEY_RSA:
        return i2d_RSAPublicKey(EVP_PKEY_get0_RSA(a), pp);
#endif
#ifndef OPENSSL_NO_DSA
    case EVP_PKEY_DSA:
        return i2d_DSAPublicKey(EVP_PKEY_get0_DSA(a), pp);
#endif
#ifndef OPENSSL_NO_EC
    case EVP_PKEY_EC:
        return i2o_ECPublicKey(EVP_PKEY_get0_EC_KEY(a), pp);
#endif
    default:
        ASN1err(ASN1_F_I2D_PUBLICKEY, ASN1_R_UNSUPPORTED_PUBLIC_KEY_TYPE);
        return -1;
    }
}
Exemplo n.º 20
0
BitcoinResult Bitcoin_MakePublicKeyFromPrivateKey(
	struct BitcoinPublicKey *public_key,
	const struct BitcoinPrivateKey *private_key
)
{
	BN_CTX *ctx = NULL;
	EC_KEY *key = NULL;
	EC_POINT *ec_public = NULL;
	unsigned char *public_key_ptr = public_key->data;
	BIGNUM *private_key_bn;
	const EC_GROUP *group = NULL;
	int size, size2;
	unsigned compression = private_key->public_key_compression;
	size_t expected_public_key_size = 0;
	enum BitcoinPublicKeyCompression public_key_compression;

	switch (compression) {
		case BITCOIN_PUBLIC_KEY_COMPRESSED :
		case BITCOIN_PUBLIC_KEY_UNCOMPRESSED :
			break;
		default :
			applog(APPLOG_ERROR, __func__,
				"public key compression is not specified, please set using"
				" --public-key-compression compressed/uncompressed"
			);
			EC_KEY_free(key);
			return BITCOIN_ERROR_PRIVATE_KEY_INVALID_FORMAT;
			break;
	}

	key = EC_KEY_new_by_curve_name_NID_secp256k1();
	if (!key) {
		applog(APPLOG_ERROR, __func__,
			"EC_KEY_new_by_curve_name failed: %s",
			ERR_error_string(ERR_get_error(), NULL)
		);
		return BITCOIN_ERROR_LIBRARY_FAILURE;
	}

	group = EC_KEY_get0_group(key);
	if (!group) {
		applog(APPLOG_ERROR, __func__,
			"EC_KEY_get0_group failed: %s",
			ERR_error_string(ERR_get_error(), NULL)
		);
		EC_KEY_free(key);
		return BITCOIN_ERROR_LIBRARY_FAILURE;
	}

	private_key_bn = BN_new();
	BN_bin2bn(private_key->data, BITCOIN_PRIVATE_KEY_SIZE, private_key_bn);
	ec_public = EC_POINT_new(group);

	ctx = BN_CTX_new();
	if (!ctx) {
		applog(APPLOG_ERROR, __func__,
			"BN_CTX_new failed: %s",
			ERR_error_string(ERR_get_error(), NULL)
		);
		EC_KEY_free(key);
		return BITCOIN_ERROR_LIBRARY_FAILURE;
	}

	if (!EC_POINT_mul(group, ec_public, private_key_bn, NULL, NULL, ctx)) {
		applog(APPLOG_ERROR, __func__,
			"EC_POINT_mul failed: %s",
			ERR_error_string(ERR_get_error(), NULL)
		);
		EC_KEY_free(key);
		return BITCOIN_ERROR_LIBRARY_FAILURE;
	}

	EC_KEY_set_private_key(key, private_key_bn);
	EC_KEY_set_public_key(key, ec_public);

	if (compression == BITCOIN_PUBLIC_KEY_COMPRESSED) {
		EC_KEY_set_conv_form(key, POINT_CONVERSION_COMPRESSED);
		expected_public_key_size = BITCOIN_PUBLIC_KEY_COMPRESSED_SIZE;
		public_key_compression = BITCOIN_PUBLIC_KEY_COMPRESSED;
	} else {
		EC_KEY_set_conv_form(key, POINT_CONVERSION_UNCOMPRESSED);
		expected_public_key_size = BITCOIN_PUBLIC_KEY_UNCOMPRESSED_SIZE;
		public_key_compression = BITCOIN_PUBLIC_KEY_UNCOMPRESSED;
	}

	size = i2o_ECPublicKey(key, NULL);

	if (size != expected_public_key_size) {
		fprintf(stderr, "%s: invalid public key size (%u), should be %u\n",
			__func__,
			(unsigned)size,
			(unsigned)expected_public_key_size
		);
		BN_free(private_key_bn);
		EC_KEY_free(key);
		return BITCOIN_ERROR_PUBLIC_KEY_INVALID_FORMAT;
	}

	size2 = i2o_ECPublicKey(key, &public_key_ptr);
	if (size2 != expected_public_key_size) {
		fprintf(stderr, "%s: invalid public key size (%u), should be %u\n",
			__func__,
			(unsigned)size,
			(unsigned)expected_public_key_size
		);
		BN_free(private_key_bn);
		EC_KEY_free(key);
		return BITCOIN_ERROR_PUBLIC_KEY_INVALID_FORMAT;
	}

	/* public key appears to be valid by now, set the compression type */
	public_key->compression = public_key_compression;
	public_key->network_type = private_key->network_type;

	/* free resources */
	EC_POINT_clear_free(ec_public);
	BN_free(private_key_bn);
	BN_CTX_free(ctx);
	EC_KEY_free(key);

	return BITCOIN_SUCCESS;
}
Exemplo n.º 21
0
void
vg_output_match_console(vg_context_t *vcp, EC_KEY *pkey, const char *pattern)
{
	unsigned char key_buf[512], *pend;
	char addr_buf[64], addr2_buf[64];
	char privkey_buf[VG_PROTKEY_MAX_B58];
	const char *keytype = "Privkey";
	int len;
	int isscript = (vcp->vc_format == VCF_SCRIPT);

	EC_POINT *ppnt;
	int free_ppnt = 0;
	if (vcp->vc_pubkey_base) {
		ppnt = EC_POINT_new(EC_KEY_get0_group(pkey));
		EC_POINT_copy(ppnt, EC_KEY_get0_public_key(pkey));
		EC_POINT_add(EC_KEY_get0_group(pkey),
			     ppnt,
			     ppnt,
			     vcp->vc_pubkey_base,
			     NULL);
		free_ppnt = 1;
		keytype = "PrivkeyPart";
	} else {
		ppnt = (EC_POINT *) EC_KEY_get0_public_key(pkey);
	}

	assert(EC_KEY_check_key(pkey));
	vg_encode_address(ppnt,
			  EC_KEY_get0_group(pkey),
			  vcp->vc_pubkeytype, addr_buf);
	if (isscript)
		vg_encode_script_address(ppnt,
					 EC_KEY_get0_group(pkey),
					 vcp->vc_addrtype, addr2_buf);

	if (vcp->vc_key_protect_pass) {
		len = vg_protect_encode_privkey(privkey_buf,
						pkey, vcp->vc_privtype,
						VG_PROTKEY_DEFAULT,
						vcp->vc_key_protect_pass);
		if (len) {
			keytype = "Protkey";
		} else {
			fprintf(stderr,
				"ERROR: could not password-protect key\n");
			vcp->vc_key_protect_pass = NULL;
		}
	}
	if (!vcp->vc_key_protect_pass) {
		vg_encode_privkey(pkey, vcp->vc_privtype, privkey_buf);
	}

	if (!vcp->vc_result_file || (vcp->vc_verbose > 0)) {
		printf("\r%79s\r\nPattern: %s\n", "", pattern);
	}

	if (vcp->vc_verbose > 0) {
		if (vcp->vc_verbose > 1) {
			pend = key_buf;
			len = i2o_ECPublicKey(pkey, &pend);
			printf("Pubkey (hex): ");
			dumphex(key_buf, len);
			printf("Privkey (hex): ");
			dumpbn(EC_KEY_get0_private_key(pkey));
			pend = key_buf;
			len = i2d_ECPrivateKey(pkey, &pend);
			printf("Privkey (ASN1): ");
			dumphex(key_buf, len);
		}

	}

	if (!vcp->vc_result_file || (vcp->vc_verbose > 0)) {
		if (isscript)
			printf("P2SHAddress: %s\n", addr2_buf);
		printf("Address: %s\n"
		       "%s: %s\n",
		       addr_buf, keytype, privkey_buf);
	}

	if (vcp->vc_result_file) {
		FILE *fp = fopen(vcp->vc_result_file, "a");
		if (!fp) {
			fprintf(stderr,
				"ERROR: could not open result file: %s\n",
				strerror(errno));
		} else {
			fprintf(fp,
				"Pattern: %s\n"
				, pattern);
			if (isscript)
				fprintf(fp, "P2SHAddress: %s\n", addr2_buf);
			fprintf(fp,
				"Address: %s\n"
				"%s: %s\n",
				addr_buf, keytype, privkey_buf);
			fclose(fp);
		}
	}
	if (free_ppnt)
		EC_POINT_free(ppnt);
}
Exemplo n.º 22
0
static int ecdh_cms_encrypt(CMS_RecipientInfo *ri)
{
    EVP_PKEY_CTX *pctx;
    EVP_PKEY *pkey;
    EVP_CIPHER_CTX *ctx;
    int keylen;
    X509_ALGOR *talg, *wrap_alg = NULL;
    ASN1_OBJECT *aoid;
    ASN1_BIT_STRING *pubkey;
    ASN1_STRING *wrap_str;
    ASN1_OCTET_STRING *ukm;
    unsigned char *penc = NULL;
    int penclen;
    int rv = 0;
    int ecdh_nid, kdf_type, kdf_nid, wrap_nid;
    const EVP_MD *kdf_md;
    pctx = CMS_RecipientInfo_get0_pkey_ctx(ri);
    if (!pctx)
        return 0;
    /* Get ephemeral key */
    pkey = EVP_PKEY_CTX_get0_pkey(pctx);
    if (!CMS_RecipientInfo_kari_get0_orig_id(ri, &talg, &pubkey,
                                             NULL, NULL, NULL))
        goto err;
    X509_ALGOR_get0(&aoid, NULL, NULL, talg);
    /* Is everything uninitialised? */
    if (aoid == OBJ_nid2obj(NID_undef)) {

        EC_KEY *eckey = pkey->pkey.ec;
        /* Set the key */
        unsigned char *p;

        penclen = i2o_ECPublicKey(eckey, NULL);
        if (penclen <= 0)
            goto err;
        penc = OPENSSL_malloc(penclen);
        if (!penc)
            goto err;
        p = penc;
        penclen = i2o_ECPublicKey(eckey, &p);
        if (penclen <= 0)
            goto err;
        ASN1_STRING_set0(pubkey, penc, penclen);
        pubkey->flags &= ~(ASN1_STRING_FLAG_BITS_LEFT | 0x07);
        pubkey->flags |= ASN1_STRING_FLAG_BITS_LEFT;

        penc = NULL;
        X509_ALGOR_set0(talg, OBJ_nid2obj(NID_X9_62_id_ecPublicKey),
                        V_ASN1_UNDEF, NULL);
    }

    /* See if custom paraneters set */
    kdf_type = EVP_PKEY_CTX_get_ecdh_kdf_type(pctx);
    if (kdf_type <= 0)
        goto err;
    if (!EVP_PKEY_CTX_get_ecdh_kdf_md(pctx, &kdf_md))
        goto err;
    ecdh_nid = EVP_PKEY_CTX_get_ecdh_cofactor_mode(pctx);
    if (ecdh_nid < 0)
        goto err;
    else if (ecdh_nid == 0)
        ecdh_nid = NID_dh_std_kdf;
    else if (ecdh_nid == 1)
        ecdh_nid = NID_dh_cofactor_kdf;

    if (kdf_type == EVP_PKEY_ECDH_KDF_NONE) {
        kdf_type = EVP_PKEY_ECDH_KDF_X9_62;
        if (EVP_PKEY_CTX_set_ecdh_kdf_type(pctx, kdf_type) <= 0)
            goto err;
    } else
        /* Uknown KDF */
        goto err;
    if (kdf_md == NULL) {
        /* Fixme later for better MD */
        kdf_md = EVP_sha1();
        if (EVP_PKEY_CTX_set_ecdh_kdf_md(pctx, kdf_md) <= 0)
            goto err;
    }

    if (!CMS_RecipientInfo_kari_get0_alg(ri, &talg, &ukm))
        goto err;

    /* Lookup NID for KDF+cofactor+digest */

    if (!OBJ_find_sigid_by_algs(&kdf_nid, EVP_MD_type(kdf_md), ecdh_nid))
        goto err;
    /* Get wrap NID */
    ctx = CMS_RecipientInfo_kari_get0_ctx(ri);
    wrap_nid = EVP_CIPHER_CTX_type(ctx);
    keylen = EVP_CIPHER_CTX_key_length(ctx);

    /* Package wrap algorithm in an AlgorithmIdentifier */

    wrap_alg = X509_ALGOR_new();
    if (!wrap_alg)
        goto err;
    wrap_alg->algorithm = OBJ_nid2obj(wrap_nid);
    wrap_alg->parameter = ASN1_TYPE_new();
    if (!wrap_alg->parameter)
        goto err;
    if (EVP_CIPHER_param_to_asn1(ctx, wrap_alg->parameter) <= 0)
        goto err;
    if (ASN1_TYPE_get(wrap_alg->parameter) == NID_undef) {
        ASN1_TYPE_free(wrap_alg->parameter);
        wrap_alg->parameter = NULL;
    }

    if (EVP_PKEY_CTX_set_ecdh_kdf_outlen(pctx, keylen) <= 0)
        goto err;

    penclen = CMS_SharedInfo_encode(&penc, wrap_alg, ukm, keylen);

    if (!penclen)
        goto err;

    if (EVP_PKEY_CTX_set0_ecdh_kdf_ukm(pctx, penc, penclen) <= 0)
        goto err;
    penc = NULL;

    /*
     * Now need to wrap encoding of wrap AlgorithmIdentifier into parameter
     * of another AlgorithmIdentifier.
     */
    penclen = i2d_X509_ALGOR(wrap_alg, &penc);
    if (!penc || !penclen)
        goto err;
    wrap_str = ASN1_STRING_new();
    if (!wrap_str)
        goto err;
    ASN1_STRING_set0(wrap_str, penc, penclen);
    penc = NULL;
    X509_ALGOR_set0(talg, OBJ_nid2obj(kdf_nid), V_ASN1_SEQUENCE, wrap_str);

    rv = 1;

 err:
    OPENSSL_free(penc);
    X509_ALGOR_free(wrap_alg);
    return rv;
}
Exemplo n.º 23
0
char * getRealBitcoinAddress() {

	printf("OpenSSL version: %s\n", OPENSSL_VERSION_TEXT);
	/*printf("Enter the number of keys: ");
	fflush(stdout);
	*/
	char stringMatch[31];
	/*getLine1(stringMatch);
	unsigned long int i = strtol(stringMatch, NULL, 0);*/
	printf("Please enter a string of text for the key (30 max): ");
	fflush(stdout);
	getLine1(stringMatch);
	printf("Waiting for entropy... Move the cursor around...\n");
	fflush(stdout);
	char entropy[32];
	FILE * f = fopen("/dev/random", "r");

	if (fread(entropy, 32, 1, f) != 1) {

		printf("FAILURING GETTING ENTROPY!");
		return 1;
	}

	RAND_add(entropy, 32, 32);
	fclose(f);
	printf("Making your addresses for \"%s\"\n\n", stringMatch);
	EC_KEY * key = EC_KEY_new_by_curve_name(NID_secp256k1);
	uint8_t * pubKey = NULL;
	int pubSize = 0;
	uint8_t * privKey = NULL;
	int privSize = 0;
	uint8_t * shaHash = malloc(32);
	uint8_t * ripemdHash = malloc(20);
	unsigned int x;

	if (!EC_KEY_generate_key(key)) {

		printf("GENERATE KEY FAIL\n");
		exit(1);
	}

	int pubSizeNew = i2o_ECPublicKey(key, NULL);

	if (!pubSizeNew) {

		printf("PUB KEY TO DATA ZERO\n");
		exit(1);
	}

	if (pubSizeNew != pubSize) {

		pubSize = pubSizeNew;
		pubKey = realloc(pubKey, pubSize);
	}
	uint8_t * pubKey2 = pubKey;

	if (i2o_ECPublicKey(key, &pubKey2) != pubSize) {

		printf("PUB KEY TO DATA FAIL\n");
		exit(1);
	}

	SHA256(pubKey, pubSize, shaHash);
	RIPEMD160(shaHash, 32, ripemdHash);
	Address * address = createNewAddressFromRIPEMD160Hash(ripemdHash, 0, 0,
			err8);
	ByteArray * string = getStringForVersionChecksumBytes(
			getVersionChecksumBytes(address));
	decrementReferenceCount(address);
	uint8_t offset = 1;
	size_t matchSize = strlen(stringMatch);
	uint8_t y;
	/* Get private key*/
	const BIGNUM * privKeyNum = EC_KEY_get0_private_key(key);

	if (!privKeyNum) {
		printf("PRIV KEY TO BN FAIL\n");
	}

	int privSizeNew = BN_num_bytes(privKeyNum);

	if (privSizeNew != privSize) {
		privSize = privSizeNew;
		privKey = realloc(privKey, privSize);
	}

	int res = BN_bn2bin(privKeyNum, privKey);

	if (res != privSize) {
		printf("PRIV KEY TO DATA FAIL\n");
	}

	/* Print data to stdout*/
	printf("Private key (hex): ");
	int i;

	for (i = 0; i < privSize; i++) {
		printf(" %.2X", privKey[i]);
	}

	printf("\nPublic key (hex): ");
	int j;

	for (j = 0; j < pubSize; j++) {
		printf(" %.2X", pubKey[j]);
	}
	printf("\n");

	char *realBitcoinAddress = getByteArrayData(string);

	/*printf("\nAddress (base-58): %s\n\n", realBitcoinAddress);*/
	x++; /*Move to next*/

	decrementReferenceCount(string);


	free(shaHash);
	free(ripemdHash);
	EC_KEY_free(key);
	return realBitcoinAddress;
}
Exemplo n.º 24
0
int main(){
	printf("OpenSSL version: %s\n", OPENSSL_VERSION_TEXT);
	printf("Enter the number of keys: ");
	fflush(stdout);
	char stringMatch[31];
	getLine(stringMatch);
	unsigned long int i = strtol(stringMatch, NULL, 0);
	printf("Enter a string of text for the key (30 max): ");
	fflush(stdout);
	getLine(stringMatch);
	printf("Waiting for entropy... Move the cursor around...\n");
	fflush(stdout);
	char entropy[32];
	FILE * f = fopen("/dev/random", "r");
	if (fread(entropy, 32, 1, f) != 1){
		printf("FAILURING GETTING ENTROPY!");
		return 1;
	}
	RAND_add(entropy, 32, 32);
	fclose(f);
	printf("Making %lu addresses for \"%s\"\n\n", i, stringMatch);
	EC_KEY * key = EC_KEY_new_by_curve_name(NID_secp256k1);
	uint8_t * pubKey = NULL;
	int pubSize = 0;
	uint8_t * privKey = NULL;
	int privSize = 0;
	uint8_t * shaHash = malloc(32);
	uint8_t * ripemdHash = malloc(20);
	for (unsigned int x = 0; x < i;) {
		if(! EC_KEY_generate_key(key)){
			printf("GENERATE KEY FAIL\n"); 
			return 1;
		}
		int pubSizeNew = i2o_ECPublicKey(key, NULL);
		if(! pubSizeNew){
			printf("PUB KEY TO DATA ZERO\n"); 
			return 1;
		}
		if (pubSizeNew != pubSize) {
			pubSize = pubSizeNew;
			pubKey = realloc(pubKey, pubSize);
		}
		uint8_t * pubKey2 = pubKey;
		if(i2o_ECPublicKey(key, &pubKey2) != pubSize){
			printf("PUB KEY TO DATA FAIL\n");
			return 1;
		}
		SHA256(pubKey, pubSize, shaHash);
		RIPEMD160(shaHash, 32, ripemdHash);
		CBAddress * address = CBNewAddressFromRIPEMD160Hash(ripemdHash, CB_PRODUCTION_NETWORK_BYTE, false, err);
		CBByteArray * string = CBChecksumBytesGetString(CBGetChecksumBytes(address));
		CBReleaseObject(address);
		bool match = true;
		uint8_t offset = 1;
		size_t matchSize = strlen(stringMatch);
		for (uint8_t y = 0; y < matchSize;) {
			char other = islower(stringMatch[y]) ? toupper(stringMatch[y]) : (isupper(stringMatch[y])? tolower(stringMatch[y]) : '\0');
			if (CBByteArrayGetByte(string, y+offset) != stringMatch[y] && CBByteArrayGetByte(string, y+offset) != other) {
				offset++;
				y = 0;
				if (string->length < matchSize + offset) {
					match = false;
					break;
				}
			}else y++;
		}
		if (match) {
			// Get private key
			const BIGNUM * privKeyNum = EC_KEY_get0_private_key(key);
			if (! privKeyNum) {
				printf("PRIV KEY TO BN FAIL\n");
			}
			int privSizeNew = BN_num_bytes(privKeyNum);
			if (privSizeNew != privSize) {
				privSize = privSizeNew;
				privKey = realloc(privKey, privSize);
			}
			int res = BN_bn2bin(privKeyNum, privKey);
			if (res != privSize) {
				printf("PRIV KEY TO DATA FAIL\n");
			}
			// Print data to stdout
			printf("Private key (hex): ");
			for (int x = 0; x < privSize; x++) {
				printf(" %.2X", privKey[x]);
			}
			printf("\nPublic key (hex): ");
			for (int x = 0; x < pubSize; x++) {
				printf(" %.2X", pubKey[x]);
			}
			printf("\nAddress (base-58): %s\n\n", CBByteArrayGetData(string));
			x++; // Move to next
		}
		CBReleaseObject(string);
	}
	free(shaHash);
	free(ripemdHash);
	EC_KEY_free(key);
	return 0;
}