Esempio n. 1
0
static int
generate_RSA_keypair(unsigned char** private_key_der, size_t *private_key_len,
		unsigned char** public_key_der, size_t *public_key_len)
{
	RSA *private_key;
	private_key = RSA_generate_key(1024, 65537, NULL, NULL);
	unsigned char *priv, *pub;
	//DER encode / pkcs#1
	*private_key_len = i2d_RSAPrivateKey(private_key, 0);
	*public_key_len = i2d_RSAPublicKey(private_key, 0);
	*private_key_der = priv = (unsigned char*) calloc(*private_key_len, 1);
	*public_key_der = pub = (unsigned char*) calloc(*public_key_len, 1);
	i2d_RSAPrivateKey(private_key, &priv);
	i2d_RSAPublicKey(private_key, &pub);
	RSA_free(private_key);

	/*
	   // Check that all is well, DER decode
	   fprintf(stderr, "decoded:\n");
	   RSA *public_key_rsa, *private_key_rsa;
	   public_key_rsa = d2i_RSAPublicKey(0, (const unsigned char**) &public_key_der, public_key_len);
	   private_key_rsa = d2i_RSAPrivateKey(0, (const unsigned char**) &private_key_der, private_key_len);
	PEM_write_RSAPrivateKey(stderr, private_key_rsa, NULL, NULL, 0, NULL, NULL);
	PEM_write_RSAPublicKey(stderr, private_key_rsa);
	 */
	return(0);
}
Esempio n. 2
0
int
get_ASN_public_key(unsigned char** public_key_der, int* public_key_der_len, struct ccn_pkey* private_key)
{
	unsigned char *pub;
	//DER encode / pkcs#1
	RSA* private_key_rsa = EVP_PKEY_get1_RSA((EVP_PKEY*) private_key);
	*public_key_der_len = i2d_RSAPublicKey(private_key_rsa, 0);
	*public_key_der = pub = (unsigned char*) calloc(*public_key_der_len, 1);
	i2d_RSAPublicKey(private_key_rsa, &pub);
	return 0;
}
Esempio n. 3
0
// wraps RSA key generation, DER encoding, and initial SHA-1 hashing
RSA *easygen(uint16_t num, uint8_t len, uint8_t *der, uint8_t edl,
             SHA_CTX *ctx) {
    uint8_t der_len;
    RSA *rsa;

    for(;;) { // ugly, I know, but better than using goto IMHO
        rsa = RSA_generate_key(num, 3, NULL, NULL);

        if(!rsa) // if key generation fails (no [P]RNG seed?)
            return rsa;

        // encode RSA key in X.690 DER format
        uint8_t *tmp = der;
        der_len = i2d_RSAPublicKey(rsa, &tmp);

        if(der_len == edl - len + 1)
            break; // encoded key was the correct size, keep going

        RSA_free(rsa); // encoded key was the wrong size, try again
    }

    // adjust for the actual size of e
    der[RSA_ADD_DER_OFF] += len - 1;
    der[der_len - 2]     += len - 1;

    // and prepare our hash context
    SHA1_Init(ctx);
    SHA1_Update(ctx, der, der_len - 1);

    return rsa;
}
Esempio n. 4
0
        void RSAKey::cache()
        {
            unsigned char buffer[8192];
            unsigned char* buf = buffer;

            int len = i2d_RSAPublicKey(d_rsa.get(), &buf);

            EXCEPTION_ASSERT_WITH_LOG(len >= 0, OpenSSLException, "Invalid RSA context: cannot retrieve public key");

            d_public_key.clear();
            d_public_key.insert(d_public_key.end(), buffer, buffer + len);

            if (hasPrivateCompound())
            {
                buf = buffer;
                len = i2d_RSAPrivateKey(d_rsa.get(), &buf);

                EXCEPTION_ASSERT_WITH_LOG(len >= 0, OpenSSLException, "Invalid RSA context: cannot retrieve private key");

                d_private_key.clear();
                d_private_key.insert(d_private_key.end(), buffer, buffer + len);
            }
            else
            {
                d_private_key.clear();
            }
        }
/*============================================================================
 * OpcUa_P_OpenSSL_RSA_GenerateKeys
 *===========================================================================*/
OpcUa_StatusCode OpcUa_P_OpenSSL_RSA_GenerateKeys(
    OpcUa_CryptoProvider*   a_pProvider,
    OpcUa_UInt32            a_bits,
    OpcUa_Key*              a_pPublicKey,
    OpcUa_Key*              a_pPrivateKey)
{
    RSA*            pRsa;
    unsigned char*  pData;

    OpcUa_InitializeStatus(OpcUa_Module_P_OpenSSL, "RSA_GenerateKeys");

    OpcUa_ReturnErrorIfArgumentNull(a_pProvider);
    OpcUa_ReturnErrorIfArgumentNull(a_pPublicKey);
    OpcUa_ReturnErrorIfArgumentNull(a_pPrivateKey);

    OpcUa_ReferenceParameter(a_pProvider);

    /* Just 1024 or 2048 bits should be allowed for compatibility reasons */
    if ((a_bits != 1024) && (a_bits != 2048) && (a_bits != 3072) && (a_bits != 4096))
    {
        uStatus = OpcUa_BadInvalidArgument;
        OpcUa_GotoErrorIfBad(uStatus);
    }

    if(a_pPublicKey->Key.Data == OpcUa_Null)
    {
       a_pPublicKey->Key.Length = a_bits;
       OpcUa_ReturnStatusCode;
    }

    if(a_pPrivateKey->Key.Data == OpcUa_Null)
    {
       a_pPrivateKey->Key.Length = a_bits;
       OpcUa_ReturnStatusCode;
    }

    pRsa = RSA_generate_key(a_bits, RSA_F4, NULL, OpcUa_Null);

    pData = a_pPublicKey->Key.Data;
    a_pPublicKey->Key.Length = i2d_RSAPublicKey(pRsa, &pData);

    pData = a_pPrivateKey->Key.Data;
    a_pPrivateKey->Key.Length = i2d_RSAPrivateKey(pRsa, &pData);

    /* clean up */
    if(pRsa != OpcUa_Null)
    {
       RSA_free(pRsa);
    }

    a_pPublicKey->Type = OpcUa_Crypto_Rsa_Alg_Id;
    a_pPrivateKey->Type = OpcUa_Crypto_Rsa_Alg_Id;

OpcUa_ReturnStatusCode;
OpcUa_BeginErrorHandling;

OpcUa_FinishErrorHandling;
}
Esempio n. 6
0
  int AdbEndpoint::on_adb_message(const AdbMessage& msg) 
  {
    wxLogDebug("IN : %s %04x %04x %d bytes",
      token_name(msg.cmd),
      msg.arg0, msg.arg1,
      msg.payload_len);

    switch (msg.cmd) {
      case A_AUTH:
        if (msg.arg0 == 1) {  // token
          // msg.payload_len is a random token that the recipient can sign 
          // with a private key
          if (!_key) {
            if (!generate_key()) {
              wxLogError("GenerateKey failed.");
            }
          }

          // this is a key unknown to the device, let's
          // send the (new) public key over. token type=3

          if (0 == _auth_attempt) {
            // sign with the key we have.
            unsigned char* buf1;
            unsigned char* buf2;
            int len = i2d_RSAPublicKey(_key, 0);
            buf1 = buf2 = (unsigned char *)malloc(len + 1);
            memset(buf1, 0, len+1);
            i2d_RSAPublicKey(_key, (unsigned char **)&buf2);

            send_adb_message(A_AUTH, 3, 0, buf1, len);
            
            free (buf1);

            _auth_attempt ++ ;
          }



        }
        break;
    }
    return 0;
  }
Esempio n. 7
0
int
ca_pubkey_serialize(EVP_PKEY *key, struct iked_id *id)
{
	RSA		*rsa = NULL;
	uint8_t		*d;
	int		 len = 0;
	int		 ret = -1;

	switch (key->type) {
	case EVP_PKEY_RSA:
		id->id_type = 0;
		id->id_offset = 0;
		ibuf_release(id->id_buf);

		if ((rsa = EVP_PKEY_get1_RSA(key)) == NULL)
			goto done;
		if ((len = i2d_RSAPublicKey(rsa, NULL)) <= 0)
			goto done;
		if ((id->id_buf = ibuf_new(NULL, len)) == NULL)
			goto done;

		d = ibuf_data(id->id_buf);
		if (i2d_RSAPublicKey(rsa, &d) != len) {
			ibuf_release(id->id_buf);
			goto done;
		}

		id->id_type = IKEV2_CERT_RSA_KEY;
		break;
	default:
		log_debug("%s: unsupported key type %d", __func__, key->type);
		return (-1);
	}

	log_debug("%s: type %s length %d", __func__,
	    print_map(id->id_type, ikev2_cert_map), len);

	ret = 0;
 done:
	if (rsa != NULL)
		RSA_free(rsa);
	return (ret);
}
Esempio n. 8
0
sqbind::CSqBinary COsslKey::getPublicKeyRaw()
{_STT();

	if ( !m_pkey )
		return sqbind::CSqBinary();
		
	// How big is the key?
	int nSize = i2d_RSAPublicKey( m_pkey->pkey.rsa, oexNULL );
	if ( 0 >= nSize )
		return sqbind::CSqBinary();

	// Allocate space
	sqbind::CSqBinary bin;
	if ( !bin.Allocate( nSize ) )
		return bin;

	// Get the key data
	unsigned char *p = (unsigned char*)bin._Ptr();
	bin.setUsed( i2d_RSAPublicKey( m_pkey->pkey.rsa, &p ) );

	return bin;
}
Esempio n. 9
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;
  }
}
Esempio n. 10
0
// A job that does work, with output we care about (pub/priv key)
void sample_job_outputs_stuff(lsq_job_args *args)
{
    unsigned char * output = (unsigned char *) args->output_buffer.memory;
    int encoded_len = 0;
    RSA * rsa_key = RSA_generate_key(2048, 65537, NULL, NULL);

    memset(args->output_buffer.memory, 0, args->output_buffer.size);
    if(rsa_key)
    {
        // Make sure it'll fit...
        encoded_len = i2d_RSAPublicKey(rsa_key, NULL);
        //encoded_len += i2d_RSAPrivateKey(rsa_key, NULL);

        memcpy(output, &encoded_len, 4);
        output += 4;

        if(encoded_len <= args->output_buffer.size)
        {
            i2d_RSAPublicKey(rsa_key, &output);
            //i2d_RSAPrivateKey(rsa_key, &output);
        }
    }
}
Esempio n. 11
0
static int rsa_pub_encode(X509_PUBKEY *pk, const EVP_PKEY *pkey)
{
    unsigned char *penc = NULL;
    int penclen;
    penclen = i2d_RSAPublicKey(pkey->pkey.rsa, &penc);
    if (penclen <= 0)
        return 0;
    if (X509_PUBKEY_set0_param(pk, OBJ_nid2obj(EVP_PKEY_RSA),
                               V_ASN1_NULL, NULL, penc, penclen))
        return 1;

    OPENSSL_free(penc);
    return 0;
}
Esempio n. 12
0
/** Given a private or public key <b>pk</b>, put a SHA1 hash of the
 * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
 * Return 0 on success, -1 on failure.
 */
int crypto_pk_get_digest(crypto_pk_t *pk, char *digest_out)
{
    unsigned char *buf = NULL;
    int len;

    len = i2d_RSAPublicKey(pk->key, &buf);
    if (len < 0 || buf == NULL)
        return -1;
    if (crypto_digest(digest_out, (char*)buf, len) < 0) {
        OPENSSL_free(buf);
        return -1;
    }
    OPENSSL_free(buf);
    return 0;
}
Esempio n. 13
0
//rsa密钥对产生
bool CRsaDesManager::GenRsaKeypairs(void)
{
	RSA *rsa = NULL;
	FILE *fKeyFile = NULL;
	fKeyFile = fopen("raskeys.key", "wb");
	if(fKeyFile == NULL)
	{
		return false;
	}

	int i = 0;
	//把密钥对写入文件,以后从文件里读取
	unsigned char ucPubKey[RSA_KEY_LEN] = {0}, ucPriKey[RSA_KEY_LEN] = {0};
	for(i = 0; i < RSA_KEY_PAIR_NUM; ++i)
	{
		//生成RSA密钥对:
		rsa = RSA_new();
		rsa = RSA_generate_key(RSA_KEY_LEN, RSA_F4, NULL, NULL);

		unsigned char* pt = ucPubKey;
		ui32 len = i2d_RSAPublicKey(rsa, &pt);
		if(!GetPubKey(ucPubKey, len, &m_pPubRSA[i]))
			break;
		fwrite((unsigned char*)&len, 1, sizeof(ui32), fKeyFile);
		fwrite(ucPubKey, 1, len, fKeyFile);
		m_strPubKeys[i].clear();
		m_strPubKeys[i].append((char*)ucPubKey, len);

		unsigned char* pt2 = ucPriKey;
		len = i2d_RSAPrivateKey(rsa,&pt2);
		if(!GetPriKey(ucPriKey, len, &m_pPriRSA[i]))
			break;
		fwrite((unsigned char*)&len, 1, sizeof(ui32), fKeyFile);
		fwrite(ucPriKey, 1, len, fKeyFile);

		if(rsa != NULL)
		{
			RSA_free(rsa);
			rsa = NULL;
		}
	}
	fclose(fKeyFile);
	if(i < RSA_KEY_PAIR_NUM)
		return false;
	return true;
}
Esempio n. 14
0
static int rsa_pub_encode(X509_PUBKEY *pk, const EVP_PKEY *pkey) {
  uint8_t *encoded = NULL;
  int len;
  len = i2d_RSAPublicKey(pkey->pkey.rsa, &encoded);

  if (len <= 0) {
    return 0;
  }

  if (!X509_PUBKEY_set0_param(pk, OBJ_nid2obj(EVP_PKEY_RSA), V_ASN1_NULL, NULL,
                              encoded, len)) {
    OPENSSL_free(encoded);
    return 0;
  }

  return 1;
}
Esempio n. 15
0
static int rsa_pub_encode(X509_PUBKEY *pk, const EVP_PKEY *pkey)
{
    unsigned char *penc = NULL;
    int penclen;
    ASN1_STRING *str;
    int strtype;

    if (!rsa_param_encode(pkey, &str, &strtype))
        return 0;
    penclen = i2d_RSAPublicKey(pkey->pkey.rsa, &penc);
    if (penclen <= 0)
        return 0;
    if (X509_PUBKEY_set0_param(pk, OBJ_nid2obj(pkey->ameth->pkey_id),
                               strtype, str, penc, penclen))
        return 1;

    OPENSSL_free(penc);
    return 0;
}
Esempio n. 16
0
int lnp_id_initialize() {
	FILE *public_key_file;
	FILE *private_key_file;
	u_char *pointer;
	
	hash = util_get_hash("sha1");
	
	if (hash == NULL) {
		return LNP_ERROR;
	}
	
	if ((public_key_file = fopen(lnp_get_public_key_file(), "r")) == NULL) {
		return LNP_ERROR;
	}
	
	if ((private_key_file = fopen(lnp_get_private_key_file(), "r")) == NULL) {
		fclose(public_key_file);
		return LNP_ERROR;
	}

	my_key_pair = RSA_new();

	d2i_RSAPublicKey_fp(public_key_file, &my_key_pair);
	d2i_RSAPrivateKey_fp(private_key_file, &my_key_pair);
	
	my_public_key[MPINT_SIGNAL_OFFSET] = 0;
	*((int *)my_public_key) = htonl(LNP_PUBLIC_KEY_LENGTH -
			MPINT_SIGNAL_LENGTH - MPINT_SIZE_LENGTH);
	pointer = &my_public_key[MPINT_BEGINNING_OFFSET];
	i2d_RSAPublicKey(my_key_pair, &pointer);

	hash->function(my_id, &my_public_key[MPINT_BEGINNING_OFFSET],
			LNP_PUBLIC_KEY_LENGTH - MPINT_SIGNAL_LENGTH - MPINT_SIZE_LENGTH);

	liblog_debug(LAYER_NET, "ID %02X%02X%02X%02X%02X...\n",
			my_id[0], my_id[1], my_id[2], my_id[3], my_id[4]);
	
	fclose(private_key_file);
	fclose(public_key_file);
	
	return LNP_OK;
}
Esempio n. 17
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);
    }
}
Esempio n. 18
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;
    }
}
Esempio n. 19
0
static bool rsa_to_onion(RSA *r, char *o) {
  if (!r || !o)
    return false;
  unsigned char *bin = NULL;
  int i = i2d_RSAPublicKey(r, &bin);
  if (!bin)
    return false;
  if (i < 0)
    goto fail;
  unsigned char d[20] = {0};
  SHA1(bin, i, d);
  OPENSSL_free(bin);
  onion_encode(&o[0], &d[0]);
  o[16] = 0;
  return true;
fail:
  if (bin) {
    OPENSSL_free(bin);
  }
  return false;
}
Esempio n. 20
0
wi_data_t * wi_rsa_public_key(wi_rsa_t *rsa) {
	unsigned char	*buffer;
	int				length;

	if(!rsa->public_key) {
		buffer = NULL;
		length = i2d_RSAPublicKey(rsa->rsa, &buffer);
		
		if(length <= 0) {
			wi_error_set_openssl_error();
			
			return NULL;
		}
		
		rsa->public_key = wi_data_init_with_bytes(wi_data_alloc(), buffer, length);

		OPENSSL_free(buffer);
	}
	
	return rsa->public_key;
}
Esempio n. 21
0
/*
 * genrsa: generates a new rsa key pair and returns the private key in the RSA
 * format. If `pub' is not null, it stores in it the pointer to a newly
 * allocated dump of the public key that is `*pub_len' bytes. The same is for
 * `priv' and `priv_len'.
 * On error null is returned.
 */
RSA *genrsa(int key_bits, u_char **pub, u_int *pub_len, u_char **priv, u_int *priv_len)
{
	RSA *rsa=0;
	int len;
	
	rsa=RSA_generate_key(key_bits, RSA_F4, NULL, NULL);
	if (!rsa) {
		debug(DBG_SOFT, "RSA key generation failed"); 
		goto error;
	}

	if(priv) {
		*priv=0;
		len=i2d_RSAPrivateKey(rsa, priv);
		if(priv_len)
			*priv_len=len;
		if(len <= 0) {
			debug(DBG_SOFT, "Cannot dump RSA public key: %s", ssl_strerr());
			goto error;
		}
	}

	if(pub) {
		*pub=0;
		len=i2d_RSAPublicKey(rsa, pub);
		if(pub_len)
			*pub_len=len;
		if(len <= 0) {
			debug(DBG_SOFT, "Cannot dump RSA public key: %s", ssl_strerr());
			goto error;
		}
	}
	
	return rsa;
error:
	if(rsa)
		RSA_free(rsa);	
	return 0;
}
Esempio n. 22
0
QSslKey SafetPKCS12::keyFromEVP( EVP_PKEY * evp )
{
    EVP_PKEY *key = (EVP_PKEY*)evp;
    unsigned char *data = NULL;
    int len = 0;
    QSsl::KeyAlgorithm alg;
    QSsl::KeyType type;

    switch( EVP_PKEY_type( key->type ) )
    {
        case EVP_PKEY_RSA:
        {
            RSA *rsa = EVP_PKEY_get1_RSA( key );
            alg = QSsl::Rsa;
            type = rsa->d ? QSsl::PrivateKey : QSsl::PublicKey;
            len = rsa->d ? i2d_RSAPrivateKey( rsa, &data ) : i2d_RSAPublicKey( rsa, &data );
            RSA_free( rsa );
            break;
        }
        case EVP_PKEY_DSA:
        {
            DSA *dsa = EVP_PKEY_get1_DSA( key );
            alg = QSsl::Dsa;
            type = dsa->priv_key ? QSsl::PrivateKey : QSsl::PublicKey;
            len = dsa->priv_key ? i2d_DSAPrivateKey( dsa, &data ) : i2d_DSAPublicKey( dsa, &data );
            DSA_free( dsa );
            break;
        }
        default: break;
    }

    QSslKey k;
    if( len > 0 )
        k = QSslKey( QByteArray( (char*)data, len ), alg, QSsl::Der, type );
    OPENSSL_free( data );

    return k;
}
Esempio n. 23
0
main(){
	
	RSA *rsa;
	int i,len,en_len;
	unsigned char buf[2048],*p,*key_p;

	rsa=RSA_generate_key(1024,RSA_F4,NULL,NULL);

	p=buf;
	
	len=i2d_RSAPublicKey(rsa,&p);	
	len+=i2d_RSAPrivateKey(rsa,&p);

	RSA_free(rsa);
	
	key_p = (unsigned char*)malloc(len);
	memcpy(key_p,buf,len);			
	
	p = buf;
	base64_encode(key_p,len,p,&en_len);
	printf("%s\n",buf);	
	
	free(key_p);
}
Esempio n. 24
0
/*============================================================================
 * OpcUa_P_OpenSSL_X509_GetPublicKey
 *===========================================================================*/
OpcUa_StatusCode OpcUa_P_OpenSSL_X509_GetPublicKey(
    OpcUa_CryptoProvider*       a_pProvider,
    OpcUa_ByteString*           a_pCertificate,
    OpcUa_StringA               a_password,             /* this could be optional */
    OpcUa_Key*                  a_pPublicKey)
{
    EVP_PKEY*           pPublicKey      = OpcUa_Null;
    RSA*                pRsaPublicKey   = OpcUa_Null;
    X509*               pCertificate    = OpcUa_Null;
    OpcUa_Byte*         pBuffer         = OpcUa_Null;
    BIO*                bi;

    OpcUa_InitializeStatus(OpcUa_Module_P_OpenSSL, "X509_GetPublicKey");

    OpcUa_ReferenceParameter(a_password);

    OpcUa_ReturnErrorIfArgumentNull(a_pProvider);
    OpcUa_ReturnErrorIfArgumentNull(a_pCertificate);
    OpcUa_ReturnErrorIfArgumentNull(a_pCertificate->Data);
    OpcUa_ReturnErrorIfArgumentNull(a_pPublicKey);

    bi = BIO_new(BIO_s_mem());
    BIO_write(bi, a_pCertificate->Data, a_pCertificate->Length);

    pCertificate = d2i_X509_bio(bi, NULL);

    BIO_free(bi);

    if(pCertificate == OpcUa_Null)
    {
        return OpcUa_BadCertificateInvalid;
    }

    /* get EVP_PKEY from X509 certificate */
    pPublicKey = X509_get_pubkey(pCertificate);
    if(pPublicKey == OpcUa_Null)
    {
        X509_free(pCertificate);
        return OpcUa_BadCertificateInvalid;
    }

    /* free X509 certificate, since not needed anymore */
    X509_free(pCertificate);

    switch(EVP_PKEY_type(pPublicKey->type))
    {
    case EVP_PKEY_RSA:

        /* allocate memory for RSA key */

        /* get RSA public key from EVP_PKEY */
        pRsaPublicKey = EVP_PKEY_get1_RSA(pPublicKey);

        /* allocate memory for DER encoded bytestring */
        a_pPublicKey->Key.Length = i2d_RSAPublicKey(pRsaPublicKey, OpcUa_Null);

        if(a_pPublicKey->Key.Data == OpcUa_Null)
        {
            RSA_free(pRsaPublicKey);
            pRsaPublicKey = OpcUa_Null;

            EVP_PKEY_free(pPublicKey);
            pPublicKey = OpcUa_Null;

            OpcUa_ReturnStatusCode;
        }

        /* convert RSA key to DER encoded bytestring */
        pBuffer = a_pPublicKey->Key.Data;
        a_pPublicKey->Key.Length = i2d_RSAPublicKey(pRsaPublicKey, &pBuffer);
        a_pPublicKey->Type = OpcUa_Crypto_KeyType_Rsa_Public;

        /* free memory for RSA key */
        RSA_free(pRsaPublicKey);
        pRsaPublicKey = OpcUa_Null;

        break;

    case EVP_PKEY_EC:
    case EVP_PKEY_DSA:
    case EVP_PKEY_DH:
    default:
        OpcUa_GotoErrorWithStatus(OpcUa_BadNotSupported);
    }

    /*** clean up ***/
    EVP_PKEY_free(pPublicKey);
    pPublicKey = OpcUa_Null;

OpcUa_ReturnStatusCode;
OpcUa_BeginErrorHandling;

    EVP_PKEY_free(pPublicKey);
    pPublicKey = OpcUa_Null;

OpcUa_FinishErrorHandling;
}
Esempio n. 25
0
void keyGenerator(int fileIndex, int keyLength)
{
	int err=0;
	int size = 0;
	char * buffer = 0;
	char * buffer2 = 0;

	FILE * publicKeyFile = NULL;
	FILE * privateKeyFile = NULL;

	char fileName[256];
	char publicKeyFileName[512];
	char privateKeyFileName[512];

	for(int i = 0; i< 1000; i++)
   	{
		if( i < 10)
		{
			sprintf(publicKeyFileName, "%d00%d-PublicKey", fileIndex, i);
			sprintf(privateKeyFileName, "%d00%d-PrivateKey", fileIndex,i);
		} 
		else if(i >= 10 && i < 100)
		{
			sprintf(publicKeyFileName, "%d0%d-PublicKey", fileIndex, i);
			sprintf(privateKeyFileName, "%d0%d-PrivateKey", fileIndex,i);
		}
		else
		{
			sprintf(publicKeyFileName, "%d%d-PublicKey", fileIndex, i);
			sprintf(privateKeyFileName, "%d%d-PrivateKey", fileIndex,i);
		}

		RSA * rsa;
		rsa = RSA_generate_key(keyLength, RSA_F4, NULL, (char*)stdout);
		
		int lenE = 0; 
		unsigned char * tmp = new unsigned char[keyLength];
		unsigned char *p;
		
		//public key
		p = tmp;
		lenE=i2d_RSAPublicKey(rsa,&p);
		
		buffer = new char[lenE];
		memcpy(buffer, tmp, lenE);
		publicKeyFile = fopen(publicKeyFileName, "wb");
		if (publicKeyFile == NULL)
			perror("publicKey");
		fwrite(buffer, sizeof(char), lenE, publicKeyFile);
		fclose(publicKeyFile);
		
		//private key
		p = tmp;
		int lenD=i2d_RSAPrivateKey(rsa,&p);
		
		buffer2 = new char[lenD];
		memcpy(buffer2, tmp, lenD);
		privateKeyFile = fopen(privateKeyFileName, "wb");
		if (privateKeyFile == NULL)
			perror("PrivateKey");
		fwrite(buffer2, sizeof(char), lenD, privateKeyFile);
		fclose(privateKeyFile);
		
		RSA_free(rsa);
		delete [] buffer;
		delete [] buffer2;
		delete [] tmp;
	}
}
Esempio n. 26
0
/*
 * ASCII-encode a key.
 */
char *
kn_encode_key(struct keynote_deckey *dc, int iencoding,
	      int encoding, int keytype)
{
    char *foo, *ptr;
    DSA *dsa;
    RSA *rsa;
    int i;
    struct keynote_binary *bn;
    char *s;

    keynote_errno = 0;
    if (dc == NULL || dc->dec_key == NULL)
    {
	keynote_errno = ERROR_NOTFOUND;
	return NULL;
    }

    /* DSA keys */
    if ((dc->dec_algorithm == KEYNOTE_ALGORITHM_DSA) &&
	(iencoding == INTERNAL_ENC_ASN1) &&
	((encoding == ENCODING_HEX) || (encoding == ENCODING_BASE64)))
    {
	dsa = (DSA *) dc->dec_key;
	if (keytype == KEYNOTE_PUBLIC_KEY)
	  i = i2d_DSAPublicKey(dsa, NULL);
	else
	  i = i2d_DSAPrivateKey(dsa, NULL);

	if (i <= 0)
	{
	    keynote_errno = ERROR_SYNTAX;
	    return NULL;
	}

 	ptr = foo = calloc(i, sizeof(char));
	if (foo == NULL)
	{
	    keynote_errno = ERROR_MEMORY;
	    return NULL;
	}

	dsa->write_params = 1;
	if (keytype == KEYNOTE_PUBLIC_KEY)
	  i2d_DSAPublicKey(dsa, (unsigned char **) &foo);
	else
	  i2d_DSAPrivateKey(dsa, (unsigned char **) &foo);

	if (encoding == ENCODING_HEX)
	{
	    if (kn_encode_hex(ptr, &s, i) != 0)
	    {
		free(ptr);
		return NULL;
	    }

	    free(ptr);
	    return s;
	}
	else
	  if (encoding == ENCODING_BASE64)
	  {
	      s = calloc(2 * i, sizeof(char));
	      if (s == NULL)
	      {
		  free(ptr);
		  keynote_errno = ERROR_MEMORY;
		  return NULL;
	      }

	      if (kn_encode_base64(ptr, i, s, 2 * i) == -1)
	      {
		  free(s);
		  free(ptr);
		  return NULL;
	      }

	      free(ptr);
	      return s;
	  }
    }

    /* RSA keys */
    if ((dc->dec_algorithm == KEYNOTE_ALGORITHM_RSA) &&
	(iencoding == INTERNAL_ENC_PKCS1) &&
	((encoding == ENCODING_HEX) || (encoding == ENCODING_BASE64)))
    {
	rsa = (RSA *) dc->dec_key;
	if (keytype == KEYNOTE_PUBLIC_KEY)
	  i = i2d_RSAPublicKey(rsa, NULL);
	else
	  i = i2d_RSAPrivateKey(rsa, NULL);

	if (i <= 0)
	{
	    keynote_errno = ERROR_SYNTAX;
	    return NULL;
	}

	ptr = foo = calloc(i, sizeof(char));
	if (foo == NULL)
	{
	    keynote_errno = ERROR_MEMORY;
	    return NULL;
	}

	if (keytype == KEYNOTE_PUBLIC_KEY)
	  i2d_RSAPublicKey(rsa, (unsigned char **) &foo);
	else
	  i2d_RSAPrivateKey(rsa, (unsigned char **) &foo);

	if (encoding == ENCODING_HEX)
	{
	    if (kn_encode_hex(ptr, &s, i) != 0)
	    {
		free(ptr);
		return NULL;
	    }

	    free(ptr);
	    return s;
	}
	else
	  if (encoding == ENCODING_BASE64)
	  {
	      s = calloc(2 * i, sizeof(char));
	      if (s == NULL)
	      {
		  free(ptr);
		  keynote_errno = ERROR_MEMORY;
		  return NULL;
	      }

	      if (kn_encode_base64(ptr, i, s, 2 * i) == -1)
	      {
		  free(s);
		  free(ptr);
		  return NULL;
	      }

	      free(ptr);
	      return s;
	  }
    }

    /* BINARY keys */
    if ((dc->dec_algorithm == KEYNOTE_ALGORITHM_BINARY) &&
	(iencoding == INTERNAL_ENC_NONE) &&
	((encoding == ENCODING_HEX) || (encoding == ENCODING_BASE64)))
    {
	bn = (struct keynote_binary *) dc->dec_key;

	if (encoding == ENCODING_HEX)
	{
	    if (kn_encode_hex(bn->bn_key, &s, bn->bn_len) != 0)
	      return NULL;

	    return s;
	}
	else
	  if (encoding == ENCODING_BASE64)
	  {
	      s = calloc(2 * bn->bn_len, sizeof(char));
	      if (s == NULL)
	      {
		  keynote_errno = ERROR_MEMORY;
		  return NULL;
	      }

	      if (kn_encode_base64(bn->bn_key, bn->bn_len, s,
				   2 * bn->bn_len) == -1)
	      {
		  free(s);
		  return NULL;
	      }

	      return s;
	  }
    }

    keynote_errno = ERROR_NOTFOUND;
    return NULL;
}
Esempio n. 27
0
uint32_t AMAuthInstallCryptoRegisterKeysFromPEMBuffer(CFDictionaryRef dict, CFStringRef key, CFTypeRef value, void* context) {
    LODWORD(r14) = LODWORD(rcx);
    r12 = rdx;
    rbx = rsi;
    r13 = rdi;
    uint32_t result = AMAuthInstallCryptoGetKeyIdType(key);
    if ((result & 0x8) == 0x0) {
    	// loc_428fc;
		if ((result & 0x4) == 0x0) {
			// loc_4291d;
		    CFStringRef pub_key_name = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@.public"), key);
		    LODWORD(r15) = 0x2;
		    if (!pub_key_name) {
				// loc_42cf2;
			    LODWORD(r13) = 0x0;
			    LODWORD(rbx) = 0x0;
			    var_24 = 0x0;
			    LODWORD(r14) = 0x0;
			    LODWORD(r12) = 0x0;
				// loc_42c0d;
				// goto exit
			}
			
			// loc_4295c;
			CFStringRef private_key_name = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@.private"), key);
			if (!private_key_name) {
				// loc_42d0d;
			    LODWORD(r13) = 0x0;
			    var_24 = 0x0;
				
				// loc_42bc9:
			    LODWORD(r14) = 0x0;
			    LODWORD(r12) = 0x0;
			    rbx = var_40;
			    
				// loc_42c0d;
				// goto exit
			}
			
			// loc_4298e;
		    LOBYTE(r15) = 0x1;
		    var_16 = 0x1;
		}
		else {
			// loc_42900;
		    var_40 = CFRetain(rbx);
		    LOBYTE(r15) = 0x0;
		    var_16 = 0x1;
		    LODWORD(rax) = 0x0;
		    // loc_42998;
		}
    }
	else {
		// loc_428da;
	    rax = CFRetain(rbx);
	    LOBYTE(r15) = 0x1;
	    var_16 = 0x0;
	    var_40 = 0x0;
	}
	
	// loc_42998;
	var_8 = r13;
	var_24 = rax;
	rbx = BIO_new_mem_buf(r12, LODWORD(r14));
	if (rbx == 0x0) {
		// loc_42be7;
		var_32 = 0x0;
		LODWORD(r13) = 0x0;
		LODWORD(r14) = 0x0;
		
		// loc_42bf8:
		LODWORD(r12) = 0x0;
		
		// loc_42c00:
		rbx = var_40;
		LODWORD(r15) = 0x2;
		// loc_42c0d;
		// goto exit
	}
	
	// loc_429bd;
	rdi = rbx;
	if (LOBYTE(r15) != 0x0) {
		rax = PEM_read_bio_RSAPrivateKey(rdi, 0x0, 0x0, 0x0);
	}
	else {
		rax = PEM_read_bio_RSA_PUBKEY(rdi, 0x0, 0x0, 0x0);
	}
	r13 = rax;
	var_32 = rbx;
	if (r13 == 0x0) {
		// loc_42b77;
	    rax = ERR_get_error();
	    rbx = &var_64;
	    ERR_error_string(rax, rbx);
	    if (LOBYTE(r15) != 0x0) {
	    }
	    _AMAuthInstallLog(0x3, "AMAuthInstallCryptoRegisterKeysFromPEMBuffer", "PEM_read_bio_RSA%sKey() failed: %s");
	    LODWORD(r15) = 0x6;
	    LODWORD(r13) = 0x0;
	    // loc_42bc9;
	    LODWORD(r14) = 0x0;
	    LODWORD(r12) = 0x0;
	    rbx = var_40;
	    // loc_42c0d;
		// goto exit
	}
	else {
		// loc_429ea;
	    LODWORD(r14) = 0x0;
	    uint32_t private_key_length = i2d_RSAPrivateKey(r13, NULL);
	    CFDataRef private_key = CFDataCreateMutable(kCFAllocatorDefault, private_key_length);
	    if (private_key) {
			// loc_42a2c;
		    CFDataSetLength(private_key, private_key_length);
		    UInt8 *data_ptr = CFDataGetMutableBytePtr(private_key);
		    i2d_RSAPrivateKey(r13, data_ptr);
		    CFDictionarySetValue(*(r15 + 0x140), private_key_name, private_key);
		    // loc_42a6b;
		}
	    if (LOBYTE(r15) == 0x0 || private_key) {
			// loc_42a6b;
		    if (var_16 == 0x0) {
				// loc_42bd8;
			    LODWORD(r12) = 0x0;
			    LODWORD(r15) = 0x0;
			    rbx = var_40;
			    // loc_42c0d;
				// goto exit
			}
			else {
				// loc_42a78;
			    uint32_t pub_key_length = i2d_RSAPublicKey(r13, NULL);
			    CFDataRef pub_key = CFDataCreateMutable(kCFAllocatorDefault, pub_key_length);
			    if (pub_key == 0x0) {
					// loc_42bf8;
				    LODWORD(r12) = 0x0;
					
					// loc_42c00:
				    rbx = var_40;
				    LODWORD(r15) = 0x2;
				    // loc_42c0d;
					// goto exit
				}
			    var_0 = r14;
			    CFDataSetLength(pub_key, pub_key_length);
			    UInt8 *pub_key_ptr = CFDataGetMutableBytePtr(pub_key);
			    i2d_RSAPublicKey(r13, pub_key_ptr);
			    CFDictionarySetValue(dict, pub_key_name, pub_key);
			    Pointer digest = NULL;
			    LODWORD(r15) = AMAuthInstallCryptoCreateDigestForKey(dict, pub_key_name, &digest));
			    if (LODWORD(r15) == 0x0) {
					var_16 = r13;
					if (var_64 != 0x0) {
						CFDictionarySetValue(install->ivars.digests, var_64, rbx);
						LODWORD(r13) = 0x0;
					}
					else {
						_AMAuthInstallLog(0x3, "_AMAuthInstallCryptoRegisterKeyHash", "keyHashData is NULL");
						LODWORD(r13) = 0x0;
						LODWORD(r15) = 0x0;
					}
			    }
			    else {
					var_16 = r13;
					AMAuthInstallLog(0x3, "_AMAuthInstallCryptoRegisterKeyHash", "AMAuthInstallCryptoCreateDigestForKey(%@) failed", rbx);
					LODWORD(r13) = LODWORD(r15);
					r15 = var_64;
			    }
			    _SafeRelease(r15);
			    LODWORD(r15) = LODWORD(r13);
			    r14 = var_0;
			    if (LODWORD(r13) == 0x0) {
					LODWORD(r15) = 0x0;
			    }
			    else {
					AMAuthInstallLog(0x3, "AMAuthInstallCryptoRegisterKeysFromPEMBuffer", "AMAuthInstallCryptoRegisterKeyHash(%@) failed", rbx);
			    }
			    r13 = var_16;
			    // loc_42c0d;
				// goto exit
			}
		}
	}
	
	
	// loc_42c0d:
	_SafeRelease(rbx);
	_SafeRelease(var_24);
	_SafeRelease(r14);
	_SafeRelease(r12);
	if (r13 != 0x0) {
		RSA_free(r13);
	}
	rdi = var_32;
	if (rdi != 0x0) {
		BIO_free(rdi);
	}
	return result;
}
Esempio n. 28
0
void RSAKeypairGenerator::generateKeypair() {

    RSA* keyPair = RSA_new();
    BIGNUM* exponent = BN_new();

    const unsigned long RSA_KEY_EXPONENT = 65537;
    BN_set_word(exponent, RSA_KEY_EXPONENT);

    // seed the random number generator before we call RSA_generate_key_ex
    srand(time(NULL));

    const int RSA_KEY_BITS = 2048;

    if (!RSA_generate_key_ex(keyPair, RSA_KEY_BITS, exponent, NULL)) {
        qDebug() << "Error generating 2048-bit RSA Keypair -" << ERR_get_error();

        emit errorGeneratingKeypair();

        // we're going to bust out of here but first we cleanup the BIGNUM
        BN_free(exponent);
        return;
    }

    // we don't need the BIGNUM anymore so clean that up
    BN_free(exponent);

    // grab the public key and private key from the file
    unsigned char* publicKeyDER = NULL;
    int publicKeyLength = i2d_RSAPublicKey(keyPair, &publicKeyDER);

    unsigned char* privateKeyDER = NULL;
    int privateKeyLength = i2d_RSAPrivateKey(keyPair, &privateKeyDER);

    if (publicKeyLength <= 0 || privateKeyLength <= 0) {
        qDebug() << "Error getting DER public or private key from RSA struct -" << ERR_get_error();

        emit errorGeneratingKeypair();

        // cleanup the RSA struct
        RSA_free(keyPair);

        // cleanup the public and private key DER data, if required
        if (publicKeyLength > 0) {
            OPENSSL_free(publicKeyDER);
        }

        if (privateKeyLength > 0) {
            OPENSSL_free(privateKeyDER);
        }

        return;
    }

    // we have the public key and private key in memory
    // we can cleanup the RSA struct before we continue on
    RSA_free(keyPair);

    QByteArray publicKeyArray(reinterpret_cast<char*>(publicKeyDER), publicKeyLength);
    QByteArray privateKeyArray(reinterpret_cast<char*>(privateKeyDER), privateKeyLength);

    // cleanup the publicKeyDER and publicKeyDER data
    OPENSSL_free(publicKeyDER);
    OPENSSL_free(privateKeyDER);

    emit generatedKeypair(publicKeyArray, privateKeyArray);
}
Esempio n. 29
0
//	ssl使用
int main()
{
	// 1. 产生RSA密钥对
	// 产生512字节公钥指数为RSA_F4的密钥对,公钥指数有RSA_F4和RSA_3两种
	// 我不清楚它们的区别,就随便选定RSA_F4
	// 可以使用RSA_print_fp()看看RSA里面的东西
	RSA *ClientRsa = RSA_generate_key(512, RSA_F4, NULL, NULL);

	// ---------
	// 2. 从RSA结构中提取公钥到BUFF,以便将它传输给对方
	// 512位的RSA其公钥提出出来长度是74字节,而私钥提取出来有超过300字节
	// 为保险起见,建议给它们预留一个512字节的空间
	unsigned char PublicKey[512];
	unsigned char *PKey = PublicKey; // 注意这个指针不是多余,是特意要这样做的,
	int PublicKeyLen = i2d_RSAPublicKey(ClientRsa, &PKey);

	// 不能采用下面的方法,因为i2d_RSAPublicKey()会修改PublicKey的值
	// 所以要引入PKey,让它作为替死鬼
	// unsigned char *PublicKey = (unsigned char *)malloc(512);
	// int PublicKeyLen = i2d_RSAPublicKey(ClientRsa, &PublicKey);

	// 逐个字节打印PublicKey信息
	printf("PublicKeyBuff, Len=%d\n", PublicKeyLen);
	for (int i=0; i<PublicKeyLen; i++)
	{
		printf("0x%02x, ", *(PublicKey+i));
	}
	printf("\n");


	// ---------
	// 3. 跟据上面提出的公钥信息PublicKey构造一个新RSA密钥(这个密钥结构只有公钥信息)
	PKey = PublicKey;
	RSA *EncryptRsa = d2i_RSAPublicKey(NULL, (const unsigned char**)&PKey, PublicKeyLen);

	// ---------
	// 4. 使用EncryptRsa加密数据,再使用ClientRsa解密数据
	// 注意, RSA加密/解密的数据长度是有限制,例如512位的RSA就只能最多能加密解密64字节的数据
	// 如果采用RSA_NO_PADDING加密方式,512位的RSA就只能加密长度等于64的数据
	// 这个长度可以使用RSA_size()来获得
	unsigned char InBuff[64], OutBuff[64];

	strcpy((char *)InBuff, "1234567890abcdefghiklmnopqrstuvwxyz.");
	RSA_public_encrypt(64, (const unsigned char*)InBuff, OutBuff, EncryptRsa, RSA_NO_PADDING); // 加密

	memset(InBuff, 0, sizeof(InBuff));
	RSA_private_decrypt(64, (const unsigned char*)OutBuff, InBuff, ClientRsa, RSA_NO_PADDING); // 解密
	printf("RSADecrypt OK: %s \n", InBuff);


	// ----------
	// 5. 利用随机32字节Seed来产生256位的AES密钥对
	unsigned char Seed[32]; // 可以采用Rand()等方法来构造随机信息
	AES_KEY AESEncryptKey, AESDecryptKey;
	AES_set_encrypt_key(Seed, 256, &AESEncryptKey);
	AES_set_decrypt_key(Seed, 256, &AESDecryptKey);

	// ----------
	// 6. 使用AES密钥对来加密/解密数据
	// 注意,256位的AES密钥只能加密/解密16字节长的数据
	strcpy((char *)InBuff, "a1b2c3d4e5f6g7h8?");
	AES_encrypt(InBuff, OutBuff, &AESEncryptKey);

	memset(InBuff, 0, sizeof(InBuff));
	AES_decrypt(OutBuff, InBuff, &AESDecryptKey);
	printf("AESDecrypt OK: %s \n", InBuff);


	// ----------
	// 7. 谨记要释放RSA结构
	RSA_free(ClientRsa);
	RSA_free(EncryptRsa);

	return(0);
}