Ejemplo n.º 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;
}
Ejemplo n.º 2
0
PyObject *
get_key_der_public(struct ccn_pkey *public_key_ccn)
{
	PyObject *result;
	RSA *public_key_rsa;
	unsigned long err;
	unsigned char *public_key_der = NULL;
	int der_len;

	public_key_rsa = EVP_PKEY_get1_RSA((EVP_PKEY *) public_key_ccn);
	JUMP_IF_NULL(public_key_rsa, openssl_error);

	//i2d_RSAPublicKey() is also valid, but openssl doesn't
	//seem to understand it
	der_len = i2d_RSA_PUBKEY(public_key_rsa, &public_key_der);
	JUMP_IF_NEG(der_len, openssl_error);

	result = PyBytes_FromStringAndSize((char *) public_key_der, der_len);
	RSA_free(public_key_rsa);
	public_key_rsa = NULL;
	JUMP_IF_NULL(result, error);

	return result;

openssl_error:
	err = ERR_get_error();
	PyErr_Format(g_PyExc_CCNKeyError, "Unable to write Public Key: %s",
			ERR_reason_error_string(err));
error:
	RSA_free(public_key_rsa);
	return NULL;
}
Ejemplo n.º 3
0
SEXP PKI_extract_key(SEXP sKey, SEXP sPriv) {
    SEXP res;
    EVP_PKEY *key;
    RSA *rsa;
    int get_priv = asInteger(sPriv), len;
    if (!inherits(sKey, "public.key") && !inherits(sKey, "private.key"))
	Rf_error("invalid key object");
    if (get_priv == NA_INTEGER)
	get_priv = inherits(sKey, "private.key");
    if (get_priv && !inherits(sKey, "private.key"))
	return R_NilValue;
    key = (EVP_PKEY*) R_ExternalPtrAddr(sKey);
    if (!key)
	Rf_error("NULL key");
    PKI_init();
    if (EVP_PKEY_type(key->type) != EVP_PKEY_RSA)
	Rf_error("Sorry only RSA keys are supported at this point");
    rsa = EVP_PKEY_get1_RSA(key);
    if (get_priv) {
	unsigned char *ptr;
	len = i2d_RSAPrivateKey(rsa, 0);
	if (len < 1)
	    Rf_error("%s", ERR_error_string(ERR_get_error(), NULL));
	res = allocVector(RAWSXP, len);
	ptr = (unsigned char*) RAW(res);
	len = i2d_RSAPrivateKey(rsa, &ptr);
	if (len < 1)
	    Rf_error("%s", ERR_error_string(ERR_get_error(), NULL));
	PROTECT(res);
	setAttrib(res, R_ClassSymbol, mkString("private.key.DER"));
	UNPROTECT(1);
    } else {
	unsigned char *ptr;
	len = i2d_RSA_PUBKEY(rsa, 0);
	if (len < 1)
	    Rf_error("%s", ERR_error_string(ERR_get_error(), NULL));
	res = allocVector(RAWSXP, len);
	ptr = (unsigned char*) RAW(res);
	len = i2d_RSA_PUBKEY(rsa, &ptr);
	if (len < 1)
	    Rf_error("%s", ERR_error_string(ERR_get_error(), NULL));
	PROTECT(res);
	setAttrib(res, R_ClassSymbol, mkString("public.key.DER"));
	UNPROTECT(1);
    }
    return res;
}
Ejemplo n.º 4
0
ndn_Error
ndn_RsaPrivateKey_encodePublicKey
  (const struct ndn_RsaPrivateKey *self, uint8_t *encoding,
   size_t *encodingLength)
{
  int result = i2d_RSA_PUBKEY(self->privateKey, encoding ? &encoding : 0);
  if (result < 0)
    return NDN_ERROR_Error_encoding_key;

  *encodingLength = result;
  return NDN_ERROR_success;
}
Ejemplo n.º 5
0
/* Manuall compose public keys from bignum values */
SEXP R_rsa_pubkey_build(SEXP expdata, SEXP moddata){
  RSA *rsa = RSA_new();
  MY_RSA_set0_key(rsa, new_bignum_from_r(moddata), new_bignum_from_r(expdata), NULL);
  unsigned char *buf = NULL;
  int len = i2d_RSA_PUBKEY(rsa, &buf);
  bail(len);
  RSA_free(rsa);
  SEXP res = allocVector(RAWSXP, len);
  memcpy(RAW(res), buf, len);
  OPENSSL_free(buf);
  return res;
}
Ejemplo n.º 6
0
static int certfingerprint(char *file,void *out)
{
	int r=FILEFAIL;
	int len;
	BIO *cert;
	X509 *x509;
	EVP_PKEY *key;
	RSA *rsa=NULL;
	EC_KEY *ec=NULL;
	unsigned char bfr[2048];
	unsigned char *p=bfr;

	if(!(cert=BIO_new(BIO_s_file())))goto err1;
	if(BIO_read_filename(cert,file)<=0)goto err2;

	r=CRYPTOFAIL;
	if(!(x509=PEM_read_bio_X509_AUX(cert,NULL,NULL,NULL)))goto err2;
	if(!(key=X509_get_pubkey(x509)))goto err3;

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

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

	default:goto err4;
	}
#endif

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

err5:	if(rsa)RSA_free(rsa);
	if(ec)EC_KEY_free(ec);
err4:	EVP_PKEY_free(key);
err3:	X509_free(x509);
err2:	BIO_free(cert);
err1:	return r;
}
Ejemplo n.º 7
0
void
FilePrivateKeyStorage::generateKeyPair
  (const Name& keyName, const KeyParams& params)
{
  if (doesKeyExist(keyName, KEY_CLASS_PUBLIC))
    throw SecurityException("Public Key already exists");
  if (doesKeyExist(keyName, KEY_CLASS_PRIVATE))
    throw SecurityException("Private Key already exists");

  Blob publicKeyDer;
  Blob privateKeyDer;

  if (params.getKeyType() == KEY_TYPE_RSA) {
    const RsaKeyParams& rsaParams = static_cast<const RsaKeyParams&>(params);

    BIGNUM* exponent = 0;
    RSA* rsa = 0;

    exponent = BN_new();
    if (BN_set_word(exponent, RSA_F4) == 1) {
      rsa = RSA_new();
      if (RSA_generate_key_ex(rsa, rsaParams.getKeySize(), exponent, NULL) == 1) {
        // Encode the public key.
        int length = i2d_RSA_PUBKEY(rsa, NULL);
        publicKeyDer = Blob(ptr_lib::make_shared<vector<uint8_t> >(length), false);
        uint8_t* derPointer = const_cast<uint8_t*>(publicKeyDer.buf());
        i2d_RSA_PUBKEY(rsa, &derPointer);

        // Encode the private key.
        length = i2d_RSAPrivateKey(rsa, NULL);
        vector<uint8_t> pkcs1PrivateKeyDer(length);
        derPointer = &pkcs1PrivateKeyDer[0];
        i2d_RSAPrivateKey(rsa, &derPointer);
        privateKeyDer = encodePkcs8PrivateKey
          (pkcs1PrivateKeyDer, OID(RSA_ENCRYPTION_OID),
           ptr_lib::make_shared<DerNode::DerNull>());
      }
    }

    BN_free(exponent);
    RSA_free(rsa);
  }
  else if (params.getKeyType() == KEY_TYPE_ECDSA) {
    const EcdsaKeyParams& ecdsaParams = static_cast<const EcdsaKeyParams&>(params);

    OID parametersOid;
    int curveId = -1;

    // Find the entry in EC_KEY_INFO.
    for (size_t i = 0 ; i < sizeof(EC_KEY_INFO) / sizeof(EC_KEY_INFO[0]); ++i) {
      if (EC_KEY_INFO[i].keySize == ecdsaParams.getKeySize()) {
        curveId = EC_KEY_INFO[i].curveId;
        parametersOid.setIntegerList
          (EC_KEY_INFO[i].oidIntegerList, EC_KEY_INFO[i].oidIntegerListLength);

        break;
      }
    }
    if (curveId == -1)
      throw SecurityException("Unsupported keySize for KEY_TYPE_ECDSA");

    EC_KEY* ecKey = EC_KEY_new_by_curve_name(curveId);
    if (ecKey != NULL) {
      if (EC_KEY_generate_key(ecKey) == 1) {
        // Encode the public key.
        int length = i2d_EC_PUBKEY(ecKey, NULL);
        vector<uint8_t> opensslPublicKeyDer(length);
        uint8_t* derPointer = &opensslPublicKeyDer[0];
        i2d_EC_PUBKEY(ecKey, &derPointer);
        // Convert the openssl style to ndn-cxx which has the simple AlgorithmIdentifier.
        // Find the bit string which is the second child.
        ptr_lib::shared_ptr<DerNode> parsedNode = DerNode::parse
          (&opensslPublicKeyDer[0], 0);
        const std::vector<ptr_lib::shared_ptr<DerNode> >& children =
          parsedNode->getChildren();
        publicKeyDer = encodeSubjectPublicKeyInfo
          (OID(EC_ENCRYPTION_OID),
           ptr_lib::make_shared<DerNode::DerOid>(parametersOid), children[1]);

        // Encode the private key.
        EC_KEY_set_enc_flags(ecKey, EC_PKEY_NO_PARAMETERS | EC_PKEY_NO_PUBKEY);
        length = i2d_ECPrivateKey(ecKey, NULL);
        vector<uint8_t> pkcs1PrivateKeyDer(length);
        derPointer = &pkcs1PrivateKeyDer[0];
        i2d_ECPrivateKey(ecKey, &derPointer);
        privateKeyDer = encodePkcs8PrivateKey
          (pkcs1PrivateKeyDer, OID(EC_ENCRYPTION_OID),
           ptr_lib::make_shared<DerNode::DerOid>(parametersOid));
      }
    }

    EC_KEY_free(ecKey);
  }
  else
    throw SecurityException("Unsupported key type");

  string keyUri = keyName.toUri();
  string publicKeyFilePath = nameTransform(keyUri, ".pub");
  string privateKeyFilePath = nameTransform(keyUri, ".pri");

  ofstream publicKeyFile(publicKeyFilePath.c_str());
  publicKeyFile << toBase64(publicKeyDer.buf(), publicKeyDer.size(), true);
  ofstream privateKeyFile(privateKeyFilePath.c_str());
  privateKeyFile << toBase64(privateKeyDer.buf(), privateKeyDer.size(), true);

  ::chmod(publicKeyFilePath.c_str(),  S_IRUSR | S_IRGRP | S_IROTH);
  ::chmod(privateKeyFilePath.c_str(), S_IRUSR);
}
Ejemplo n.º 8
0
bool avjackif::async_register_new_user(std::string user_name, boost::asio::yield_context yield_context)
{
	// 先发 client_hello
	if( m_shared_key.empty())
		async_client_hello(yield_context);

	auto digest = EVP_sha1();

	// 先生成 RSA 密钥
	_rsa.reset(RSA_generate_key(2048, 65537, 0, 0), RSA_free);

	// 然后生成 CSR
	boost::shared_ptr<X509_REQ> csr(X509_REQ_new(), X509_REQ_free);

	boost::shared_ptr<EVP_PKEY> pkey(EVP_PKEY_new(), EVP_PKEY_free);
	EVP_PKEY_set1_RSA(pkey.get(), _rsa.get());

	// 添加证书申请信息

	auto subj =X509_REQ_get_subject_name(csr.get());
/*	X509_NAME_add_entry_by_NID(subj, NID_countryName, "CN");
	X509_NAME_add_entry_by_NID(subj, NID_stateOrProvinceName, "Shanghai");
	X509_NAME_add_entry_by_NID(subj, NID_localityName, "Shanghai");
	X509_NAME_add_entry_by_NID(subj, NID_organizationName, "avplayer");
	X509_NAME_add_entry_by_NID(subj, NID_organizationalUnitName, "sales");
*/	X509_NAME_add_entry_by_NID(subj, NID_commonName, user_name);
//	X509_NAME_add_entry_by_NID(subj, NID_pkcs9_emailAddress, "test-client");

	X509_REQ_set_pubkey(csr.get(), pkey.get());

	// 签出 CSR
	X509_REQ_sign(csr.get(), pkey.get(), digest);

	unsigned char * out = NULL;
	auto csr_out_len = i2d_X509_REQ(csr.get(), &out);

	std::string csrout((char*)out, csr_out_len);

	OPENSSL_free(out);
	out = NULL;
	auto rsa_key_out_len = i2d_RSA_PUBKEY(_rsa.get(), &out);

	std::string rsa_key((char*)out, rsa_key_out_len);
	OPENSSL_free(out);

	PEM_write_X509_REQ(stderr, csr.get());

	// 然后发送 注册信息
	proto::user_register user_register;

	user_register.set_user_name(user_name);
	user_register.set_rsa_pubkey(rsa_key);
	user_register.set_csr(csrout);

	boost::asio::async_write(*m_sock, boost::asio::buffer(av_router::encode(user_register)), yield_context);

	// 读取应答
	std::unique_ptr<proto::user_register_result> user_register_result((proto::user_register_result*)async_read_protobuf_message(*m_sock, yield_context));

	return user_register_result->result() == proto::user_register_result::REGISTER_SUCCEED;
}
Ejemplo n.º 9
0
int main( void ){
    // int i2d_RSAPublicKey(RSA *a, unsigned char **pp);
    // int i2d_RSA_PUBKEY(RSA *a, unsigned char **pp);
    const char* keyStr =
        "-----BEGIN PUBLIC KEY-----\n"
        "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAws5ZlcsFQv8oh+f5YDE/\n"
        "Dqro+tyQxcRpw8Ykjo/Vxq/x7rFgCZch7IUWfImTXEiYbePVApgcCFS/yMBJpaG9\n"
        "mWYbYDmpQEMrYEAdo7dB0A6NS/DFvdlTmhUxe2YBqeP7U+s5pZ1nekhVD1vCkJro\n"
        "P8Z8pwOZ4kDo1pWDcguL8j0c0a5JeO24sBtBxak3lDOlTdIrc6ulJ/cNrhzIhbmu\n"
        "QUTwImsmOH/SYHHKhMctPAU26CRai8NmhIucNx+0LYhikaJXgfdyHD/a7RdSqMHy\n"
        "QWqRjvEyk7DJOEojSEF8OlES24qoyMTNRUIndrQc2u96oQToQh9sjg6S0g8TlWc0\n"
        "BwIDAQAB\n"
        "-----END PUBLIC KEY-----"
    ;
    EVP_PKEY* evpKey = readPublicKey( keyStr );
    RSA* rsaKey = EVP_PKEY_get1_RSA( evpKey );

    unsigned char keyBinaryBuffer[ 10240 ] = { 0 };
    unsigned char* keyBinaryBufferPointer = keyBinaryBuffer;
    int keyLength = i2d_RSA_PUBKEY( rsaKey, (unsigned char**)&keyBinaryBufferPointer );

    std::cout << "DER Format (" << keyLength << "):" << std::hex << std::setfill( '0' ) << std::endl;
    for( int i = 0; i < keyLength; ++i ){
        if( i && (i % 10 == 0) ){
            std::cout << std::endl;
        }
        std::cout << "0x" << std::setw( 2 ) << (int)keyBinaryBuffer[ i ] << ", ";
    }
    std::cout << std::endl;

    const unsigned char keyBinary[] = {
        0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86,
        0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03,
        0x82, 0x01, 0x0f, 0x00, 0x30, 0x82, 0x01, 0x0a, 0x02, 0x82,
        0x01, 0x01, 0x00, 0xc2, 0xce, 0x59, 0x95, 0xcb, 0x05, 0x42,
        0xff, 0x28, 0x87, 0xe7, 0xf9, 0x60, 0x31, 0x3f, 0x0e, 0xaa,
        0xe8, 0xfa, 0xdc, 0x90, 0xc5, 0xc4, 0x69, 0xc3, 0xc6, 0x24,
        0x8e, 0x8f, 0xd5, 0xc6, 0xaf, 0xf1, 0xee, 0xb1, 0x60, 0x09,
        0x97, 0x21, 0xec, 0x85, 0x16, 0x7c, 0x89, 0x93, 0x5c, 0x48,
        0x98, 0x6d, 0xe3, 0xd5, 0x02, 0x98, 0x1c, 0x08, 0x54, 0xbf,
        0xc8, 0xc0, 0x49, 0xa5, 0xa1, 0xbd, 0x99, 0x66, 0x1b, 0x60,
        0x39, 0xa9, 0x40, 0x43, 0x2b, 0x60, 0x40, 0x1d, 0xa3, 0xb7,
        0x41, 0xd0, 0x0e, 0x8d, 0x4b, 0xf0, 0xc5, 0xbd, 0xd9, 0x53,
        0x9a, 0x15, 0x31, 0x7b, 0x66, 0x01, 0xa9, 0xe3, 0xfb, 0x53,
        0xeb, 0x39, 0xa5, 0x9d, 0x67, 0x7a, 0x48, 0x55, 0x0f, 0x5b,
        0xc2, 0x90, 0x9a, 0xe8, 0x3f, 0xc6, 0x7c, 0xa7, 0x03, 0x99,
        0xe2, 0x40, 0xe8, 0xd6, 0x95, 0x83, 0x72, 0x0b, 0x8b, 0xf2,
        0x3d, 0x1c, 0xd1, 0xae, 0x49, 0x78, 0xed, 0xb8, 0xb0, 0x1b,
        0x41, 0xc5, 0xa9, 0x37, 0x94, 0x33, 0xa5, 0x4d, 0xd2, 0x2b,
        0x73, 0xab, 0xa5, 0x27, 0xf7, 0x0d, 0xae, 0x1c, 0xc8, 0x85,
        0xb9, 0xae, 0x41, 0x44, 0xf0, 0x22, 0x6b, 0x26, 0x38, 0x7f,
        0xd2, 0x60, 0x71, 0xca, 0x84, 0xc7, 0x2d, 0x3c, 0x05, 0x36,
        0xe8, 0x24, 0x5a, 0x8b, 0xc3, 0x66, 0x84, 0x8b, 0x9c, 0x37,
        0x1f, 0xb4, 0x2d, 0x88, 0x62, 0x91, 0xa2, 0x57, 0x81, 0xf7,
        0x72, 0x1c, 0x3f, 0xda, 0xed, 0x17, 0x52, 0xa8, 0xc1, 0xf2,
        0x41, 0x6a, 0x91, 0x8e, 0xf1, 0x32, 0x93, 0xb0, 0xc9, 0x38,
        0x4a, 0x23, 0x48, 0x41, 0x7c, 0x3a, 0x51, 0x12, 0xdb, 0x8a,
        0xa8, 0xc8, 0xc4, 0xcd, 0x45, 0x42, 0x27, 0x76, 0xb4, 0x1c,
        0xda, 0xef, 0x7a, 0xa1, 0x04, 0xe8, 0x42, 0x1f, 0x6c, 0x8e,
        0x0e, 0x92, 0xd2, 0x0f, 0x13, 0x95, 0x67, 0x34, 0x07, 0x02,
        0x03, 0x01, 0x00, 0x01
    };
    const unsigned char* keyBinaryPointer = keyBinary;

    RSA* reloadedKey = nullptr;
    d2i_RSA_PUBKEY( &reloadedKey, &keyBinaryPointer, (long)sizeof( keyBinary ) );
    EVP_PKEY* reloadedEVPKey = EVP_PKEY_new();
    EVP_PKEY_assign_RSA( reloadedEVPKey, reloadedKey );
    char keyStrBuffer[ 10240 ] = { 0 };
    writePublicKey( reloadedEVPKey, keyStrBuffer, 10240 );
    std::cout << "PEM Format:" << std::endl;
    std::cout << keyStrBuffer << std::endl;
}