コード例 #1
0
ファイル: pki.c プロジェクト: gvsurenderreddy/DNDS
static EVP_PKEY *pki_generate_keyring()
{
	jlog(L_DEBUG, "pki_generate_keyring");

	EVP_PKEY *keyring;
	RSA *rsa_keys;

	// create a new keyring
	keyring = EVP_PKEY_new();

	// generate RSA type public and private keys
	rsa_keys = RSA_generate_key(2048, RSA_F4, NULL, NULL);

	// if the keys are not usable, give it another try
	if (RSA_check_key(rsa_keys) != 1) {

		RSA_free(rsa_keys);
		rsa_keys = RSA_generate_key(2048, RSA_F4, NULL, NULL);

		// we are in serious problem here
		if (RSA_check_key(rsa_keys) != 1) {
			RSA_free(rsa_keys);
			return NULL;
		}
	}

	// add the RSA keys into the keyring
	EVP_PKEY_set1_RSA(keyring, rsa_keys);
	RSA_free(rsa_keys);

	return keyring;
}
コード例 #2
0
ファイル: application.cpp プロジェクト: marsupial/rikiglue
bool
Application::setRSAKey( const std::string    &filePath,
                        int (*pcb) (char*, int, int, void*),
                        void                 *userData )
{
	BIO *bio = BIO_new( BIO_s_file_internal() );
	if ( bio == NULL )
		return ( false );

	if ( BIO_read_filename(bio, filePath.data()) <= 0 )
	{
		BIO_free(bio);
		return ( false );
	}

	RSA *newRSA = NULL;
	PEM_read_bio_RSAPrivateKey(bio, &newRSA, pcb ? pcb : passwordCB, userData);
	BIO_free(bio);

	if( newRSA == NULL || RSA_check_key(newRSA) <= 0 )
	{
if ( sRSA != NULL ) { RSA_free(sRSA); sRSA = NULL; }
		ERR_print_errors_fp(stdout);
		if ( newRSA )
			RSA_free(newRSA);
		return ( false );
	}
	if ( sRSA != NULL )
		RSA_free(sRSA);

	sRSA = newRSA;
	decryptLuts();
	return ( true );
}
コード例 #3
0
ファイル: rsa_test.c プロジェクト: project-zerus/boringssl
static int test_bad_key(void) {
  RSA *key = RSA_new();
  BIGNUM e;

  BN_init(&e);
  BN_set_word(&e, RSA_F4);

  if (!RSA_generate_key_ex(key, 512, &e, NULL)) {
    fprintf(stderr, "RSA_generate_key_ex failed.\n");
    ERR_print_errors_fp(stderr);
    return 0;
  }

  if (!BN_add(key->p, key->p, BN_value_one())) {
    fprintf(stderr, "BN error.\n");
    ERR_print_errors_fp(stderr);
    return 0;
  }

  if (RSA_check_key(key)) {
    fprintf(stderr, "RSA_check_key passed with invalid key!\n");
    return 0;
  }

  ERR_clear_error();
  BN_free(&e);
  RSA_free(key);
  return 1;
}
コード例 #4
0
ファイル: dnssec.c プロジェクト: stribika/curveprotect
/*!
 * \brief Create RSA private key from key parameters.
 *
 * \param params  Key parameters.
 * \param key     Output private key.
 *
 * \return Error code, KNOT_EOK if successful.
 */
static int rsa_create_pkey(const knot_key_params_t *params, EVP_PKEY *key)
{
	assert(key);

	RSA *rsa = RSA_new();
	if (rsa == NULL)
		return KNOT_ENOMEM;

	rsa->n    = knot_b64_to_bignum(params->modulus);
	rsa->e    = knot_b64_to_bignum(params->public_exponent);
	rsa->d    = knot_b64_to_bignum(params->private_exponent);
	rsa->p    = knot_b64_to_bignum(params->prime_one);
	rsa->q    = knot_b64_to_bignum(params->prime_two);
	rsa->dmp1 = knot_b64_to_bignum(params->exponent_one);
	rsa->dmq1 = knot_b64_to_bignum(params->exponent_two);
	rsa->iqmp = knot_b64_to_bignum(params->coefficient);

	if (RSA_check_key(rsa) != 1) {
		RSA_free(rsa);
		return KNOT_DNSSEC_EINVALID_KEY;
	}

	if (!EVP_PKEY_assign_RSA(key, rsa)) {
		RSA_free(rsa);
		return KNOT_DNSSEC_EASSIGN_KEY;
	}

	return KNOT_EOK;
}
コード例 #5
0
static int generate_rsa_keypair(EVP_PKEY* pkey, const keymaster_rsa_keygen_params_t* rsa_params) {
    Unique_BIGNUM bn(BN_new());
    if (bn.get() == NULL) {
        logOpenSSLError("generate_rsa_keypair");
        return -1;
    }

    if (BN_set_word(bn.get(), rsa_params->public_exponent) == 0) {
        logOpenSSLError("generate_rsa_keypair");
        return -1;
    }

    /* initialize RSA */
    Unique_RSA rsa(RSA_new());
    if (rsa.get() == NULL) {
        logOpenSSLError("generate_rsa_keypair");
        return -1;
    }

    if (!RSA_generate_key_ex(rsa.get(), rsa_params->modulus_size, bn.get(), NULL) ||
        RSA_check_key(rsa.get()) < 0) {
        logOpenSSLError("generate_rsa_keypair");
        return -1;
    }

    if (EVP_PKEY_assign_RSA(pkey, rsa.get()) == 0) {
        logOpenSSLError("generate_rsa_keypair");
        return -1;
    }
    release_because_ownership_transferred(rsa);

    return 0;
}
コード例 #6
0
ファイル: ssl.cpp プロジェクト: marsupial/rikiglue
static int
loadKey( const char    *file,
         bool          decrypt,
         RSA           **rsa )
{
	BIO *bio = BIO_new( BIO_s_file_internal() );
	if ( bio == NULL )
		return ( -1 );

	if ( BIO_read_filename(bio, file) <= 0 )
	{
		BIO_free(bio);
		return ( -1 );
	}

	*rsa = NULL; //RSA_new();

	if ( decrypt )
		PEM_read_bio_RSAPrivateKey(bio, rsa, passwordCB, NULL);
	else
		PEM_read_bio_RSA_PUBKEY(bio, rsa, passwordCB, NULL);

	ERR_print_errors_fp(stdout);

	BIO_free(bio);

	if( decrypt && RSA_check_key(*rsa) <= 0 )
	{
		RSA_free(*rsa);
		printf("The rsa key is not valid\n");
		return ( -1 );
	}

	return ( 0 );
}
コード例 #7
0
ファイル: CryptRsaExt.c プロジェクト: bhanug/virtualbox
/**
  Validates key components of RSA context.
  NOTE: This function performs integrity checks on all the RSA key material, so
        the RSA key structure must contain all the private key data.

  This function validates key compoents of RSA context in following aspects:
  - Whether p is a prime
  - Whether q is a prime
  - Whether n = p * q
  - Whether d*e = 1  mod lcm(p-1,q-1)

  If RsaContext is NULL, then return FALSE.

  @param[in]  RsaContext  Pointer to RSA context to check.

  @retval  TRUE   RSA key components are valid.
  @retval  FALSE  RSA key components are not valid.

**/
BOOLEAN
EFIAPI
RsaCheckKey (
  IN  VOID  *RsaContext
  )
{
  UINTN  Reason;

  //
  // Check input parameters.
  //
  if (RsaContext == NULL) {
    return FALSE;
  }

  if  (RSA_check_key ((RSA *) RsaContext) != 1) {
    Reason = ERR_GET_REASON (ERR_peek_last_error ());
    if (Reason == RSA_R_P_NOT_PRIME ||
        Reason == RSA_R_Q_NOT_PRIME ||
        Reason == RSA_R_N_DOES_NOT_EQUAL_P_Q ||
        Reason == RSA_R_D_E_NOT_CONGRUENT_TO_1) {
      return FALSE;
    }
  }

  return TRUE;
}
コード例 #8
0
ファイル: osppeer.c プロジェクト: caiboyang/CS
EVP_PKEY* create_rsa_key(void)
{
    RSA *pRSA      = NULL;
    EVP_PKEY* pKey = NULL;
    pRSA = RSA_generate_key(2048,RSA_3,gen_callback,NULL);
    pKey = EVP_PKEY_new();
    if(pRSA && pKey && EVP_PKEY_assign_RSA(pKey,pRSA))
    {
        /* pKey owns pRSA from now */
        if(RSA_check_key(pRSA) <= 0)
        {
            fprintf(stderr,"RSA_check_key failed.\n");
            handle_openssl_error();
            EVP_PKEY_free(pKey);
            pKey = NULL;
        }
    }
    else
    {
        handle_openssl_error();
        if(pRSA)
        {
            RSA_free(pRSA);
            pRSA = NULL;
        }
        if(pKey)
        {
            EVP_PKEY_free(pKey);
            pKey = NULL;
        }
    }
    return pKey;
}
コード例 #9
0
ファイル: openssl_crypto.c プロジェクト: agl/OpenPGP-SDK
/**
   \ingroup Core_Crypto
   \brief Signs data with RSA
   \param out Where to write signature
   \param in Data to sign
   \param length Length of data
   \param srsa RSA secret key
   \param rsa RSA public key
   \return number of bytes decrypted
*/
int ops_rsa_private_encrypt(unsigned char *out,const unsigned char *in,
			    size_t length,const ops_rsa_secret_key_t *srsa,
			    const ops_rsa_public_key_t *rsa)
    {
    RSA *orsa;
    int n;

    orsa=RSA_new();
    orsa->n=rsa->n;	// XXX: do we need n?
    orsa->d=srsa->d;
    orsa->p=srsa->q;
    orsa->q=srsa->p;

    /* debug */
    orsa->e=rsa->e;
    // If this isn't set, it's very likely that the programmer hasn't
    // decrypted the secret key. RSA_check_key segfaults in that case.
    // Use ops_decrypt_secret_key_from_data() to do that.
    assert(orsa->d);
    assert(RSA_check_key(orsa) == 1);
    orsa->e=NULL;
    /* end debug */

    n=RSA_private_encrypt(length,in,out,orsa,RSA_NO_PADDING);

    orsa->n=orsa->d=orsa->p=orsa->q=NULL;
    RSA_free(orsa);

    return n;
    }
コード例 #10
0
ファイル: tops.c プロジェクト: daveharris/uni-work
static void writeKeys(char *hostname) {
  
  /* Create a private and public key and save it to disk */
  struct stat dir_stat; 
  stat("data", &dir_stat);
    
  if (!(S_ISDIR(dir_stat.st_mode))) { 
    mkdir("data",S_IXUSR|S_IRUSR|S_IWUSR);
  }
  RSA *priv_key;
  priv_key = RSA_new();
  priv_key = RSA_generate_key(512,656537,NULL,NULL);
  RSA_check_key(priv_key);

  FILE *fp;
  char filename[256];
  sprintf(filename,"data/%s%s",hostname,"-pr-key.txt");
  fp = fopen(filename,"w");
  PEM_write_RSAPrivateKey(fp, priv_key, NULL, NULL, 0 ,0, NULL);
  fclose(fp);

  char filename2[256];
  sprintf(filename2,"data/%s%s",hostname,"-pub-key.txt");
  FILE *fp3;
  fp3 = fopen(filename2,"w");
  PEM_write_RSAPublicKey(fp3, priv_key);
  fclose(fp3);
}
コード例 #11
0
ファイル: kssl_private_key.c プロジェクト: InfoHunter/keyless
// add_key_from_bio: adds an RSA key from a BIO pointer, returns
// KSSL_ERROR_NONE if successful, or a KSSL_ERROR_* if a problem
// occurs. Adds the private key to the list if successful.
static kssl_error_code add_key_from_bio(BIO *key_bp,     // BIO Key value in PEM format
                                        pk_list list) {  // Array of private keys 
  RSA *local_key;

  local_key = PEM_read_bio_RSAPrivateKey(key_bp, 0, 0, 0);
  if (local_key == NULL) {
    ssl_error();
  }

  if (list->current >= list->allocated) {
    write_log(1, "Private key list maximum reached");
    return KSSL_ERROR_INTERNAL;
  }

  if (RSA_check_key(local_key) != 1) {
    return KSSL_ERROR_INTERNAL;
  }

  list->privates[list->current].key = local_key;
  digest_public_modulus(local_key, list->privates[list->current].digest);

  list->current++;

  return KSSL_ERROR_NONE;
}
コード例 #12
0
static int
test_multi_prime_key(int nprimes, const char* pem, unsigned pem_size, const unsigned char* enc, unsigned enc_size) {
	unsigned char out[256];
	int len;

	BIO* bio = BIO_new_mem_buf((void*)pem, pem_size);
	RSA* rsa = PEM_read_bio_RSAPrivateKey(bio, NULL, NULL, NULL);
	if (!RSA_check_key(rsa))
		{
		printf("%d-prime key failed to parse.\n", nprimes);
		return -1;
		}
	BIO_free(bio);

	memset(out, 0, sizeof(out));
	len = RSA_private_decrypt(enc_size, enc, out, rsa, RSA_PKCS1_PADDING);
	if (len != 11 || memcmp(out, "hello world", 11) != 0)
		{
		printf("%d-prime key failed to decrypt.\n", nprimes);
		return -1;
		}

	RSA_free(rsa);
	return 0;
}
コード例 #13
0
ファイル: shairport.c プロジェクト: flyingtime/boxee
RSA *loadKey()
{
  BIO *tBio = BIO_new_mem_buf(AIRPORT_PRIVATE_KEY, -1);
  RSA *rsa = PEM_read_bio_RSAPrivateKey(tBio, NULL, NULL, NULL); //NULL, NULL, NULL);
  BIO_free(tBio);
  slog(RSA_LOG_LEVEL, "RSA Key: %d\n", RSA_check_key(rsa));
  return rsa;
}
コード例 #14
0
static int openssl_generate_keypair(const keymaster_device_t* dev,
        const keymaster_keypair_t key_type, const void* key_params,
        uint8_t** keyBlob, size_t* keyBlobLength) {
    ssize_t privateLen, publicLen;

    if (key_type != TYPE_RSA) {
        ALOGW("Unsupported key type %d", key_type);
        return -1;
    } else if (key_params == NULL) {
        ALOGW("key_params == null");
        return -1;
    }

    keymaster_rsa_keygen_params_t* rsa_params = (keymaster_rsa_keygen_params_t*) key_params;

    Unique_BIGNUM bn(BN_new());
    if (bn.get() == NULL) {
        logOpenSSLError("openssl_generate_keypair");
        return -1;
    }

    if (BN_set_word(bn.get(), rsa_params->public_exponent) == 0) {
        logOpenSSLError("openssl_generate_keypair");
        return -1;
    }

    /* initialize RSA */
    Unique_RSA rsa(RSA_new());
    if (rsa.get() == NULL) {
        logOpenSSLError("openssl_generate_keypair");
        return -1;
    }

    if (!RSA_generate_key_ex(rsa.get(), rsa_params->modulus_size, bn.get(), NULL)
            || RSA_check_key(rsa.get()) < 0) {
        logOpenSSLError("openssl_generate_keypair");
        return -1;
    }

    /* assign to EVP */
    Unique_EVP_PKEY pkey(EVP_PKEY_new());
    if (pkey.get() == NULL) {
        logOpenSSLError("openssl_generate_keypair");
        return -1;
    }

    if (EVP_PKEY_assign_RSA(pkey.get(), rsa.get()) == 0) {
        logOpenSSLError("openssl_generate_keypair");
        return -1;
    }
    OWNERSHIP_TRANSFERRED(rsa);

    if (wrap_key(pkey.get(), EVP_PKEY_RSA, keyBlob, keyBlobLength)) {
        return -1;
    }

    return 0;
}
コード例 #15
0
ファイル: TcpSocket.cpp プロジェクト: JuannyWang/learn
RSA_Helper::RSA_Helper(){
	RAND_seed(rnd_seed, sizeof rnd_seed);

	key =  RSA_generate_key(512, 3, NULL, NULL);

	while(RSA_check_key(key) != 1){
		RSA_free(key);
		key = RSA_generate_key(512, 3, NULL, NULL);
	}
}
コード例 #16
0
ファイル: sgx-tor.c プロジェクト: johnjohnsp1/opensgx
/** Return true iff <b>env</b> has a valid key.
 */
int crypto_pk_check_key(crypto_pk_t *env)
{
    int r;
//    assert(env);

    r = RSA_check_key(env->key);
    if (r <= 0)
        sgx_puts("Error in checking RSA key");
//        err(1,"checking RSA key");
    return r;
}
コード例 #17
0
ファイル: pki_evp.cpp プロジェクト: J-Javan/xca
int pki_evp::verify()
{
	bool veri = false;
	return true;
	if (key->type == EVP_PKEY_RSA && isPrivKey()) {
		if (RSA_check_key(key->pkey.rsa) == 1)
			veri = true;
	}
	if (isPrivKey())
		veri = true;
	pki_openssl_error();
	return veri;
}
コード例 #18
0
ファイル: openssl_crypto.c プロジェクト: agl/OpenPGP-SDK
void test_secret_key(const ops_secret_key_t *skey)
    {
    RSA* test=RSA_new();

    test->n=BN_dup(skey->public_key.key.rsa.n);
    test->e=BN_dup(skey->public_key.key.rsa.e);

    test->d=BN_dup(skey->key.rsa.d);
    test->p=BN_dup(skey->key.rsa.p);
    test->q=BN_dup(skey->key.rsa.q);

    assert(RSA_check_key(test)==1);
    RSA_free(test);
    }
コード例 #19
0
ファイル: hcrypt_rsa_lib.c プロジェクト: sara62/hcrypt
rsa_prvkey_t *rsa_prvkey_new_from_str(const char *str)
{
	RSA *rsa = NULL;
	char n_buf[1024];
	char e_buf[1024];
	char d_buf[1024];

	OPENSSL_assert(str);

	if (strlen(str) > sizeof(n_buf)) {
		fprintf(stderr, "invalid data\n");
		return NULL;
	}

	if (sscanf(str, "%s %s %s", n_buf, e_buf, d_buf) != 3) {
		fprintf(stderr, "invalid data\n");
		return NULL;
	}
	
	if (!(rsa = RSA_new())) {
		ERR_print_errors_fp(stderr);
		return NULL;
	}

	if (!BN_hex2bn(&rsa->n, n_buf)) {
		ERR_print_errors_fp(stderr);
		RSA_free(rsa);
		return NULL;
	}
	
	if (!BN_hex2bn(&rsa->e, e_buf)) {
		ERR_print_errors_fp(stderr);
		RSA_free(rsa);
		return NULL;
	}

	if (!BN_hex2bn(&rsa->d, d_buf)) {
		ERR_print_errors_fp(stderr);
		RSA_free(rsa);
		return NULL;
	}
	
	if (!RSA_check_key(rsa)) {
		ERR_print_errors_fp(stderr);
		RSA_free(rsa);
		return NULL;
	}
		
	return rsa;	
}
コード例 #20
0
EVP_PKEY* CreateRsaKey(const_RsaDevice d)
{
  BN_CTX* ctx = IntegerGroup_GetCtx(RsaParams_GetGroup(d->params));
  // phi(n) = (p-1)(q-1)
  BIGNUM *phi_n, *pm, *qm;
  phi_n = BN_new();
  CHECK_CALL(phi_n);
  CHECK_CALL(pm = BN_dup(d->p));
  CHECK_CALL(qm = BN_dup(d->q));
  CHECK_CALL(BN_sub_word(pm, 1));
  CHECK_CALL(BN_sub_word(qm, 1));
  CHECK_CALL(BN_mul(phi_n, pm, qm, ctx));

  EVP_PKEY *evp = EVP_PKEY_new();
  RSA *rsa = RSA_new();
  CHECK_CALL(evp);
  CHECK_CALL(rsa);

  CHECK_CALL(rsa->n = BN_dup(d->n)); // public modulus
  CHECK_CALL(rsa->e = BN_new()); // public exponent
  BN_set_word(rsa->e, RsaEncryptionExponent);

  rsa->d = BN_new();              // private exponent
  CHECK_CALL(rsa->d);
  CHECK_CALL(BN_mod_inverse(rsa->d, rsa->e, phi_n, ctx));

  CHECK_CALL(rsa->p = BN_dup(d->p)); // secret prime factor
  CHECK_CALL(rsa->q = BN_dup(d->q)); // secret prime factor
  rsa->dmp1 = BN_new();           // d mod (p-1)
  CHECK_CALL(rsa->dmp1);
  CHECK_CALL(BN_mod(rsa->dmp1, rsa->d, pm, ctx));

  rsa->dmq1 = BN_new();           // d mod (q-1)
  CHECK_CALL(rsa->dmq1);
  CHECK_CALL(BN_mod(rsa->dmq1, rsa->d, qm, ctx));

  rsa->iqmp = BN_new();           // q^-1 mod p
  CHECK_CALL(rsa->iqmp);
  CHECK_CALL(BN_mod_inverse(rsa->iqmp, rsa->q, rsa->p, ctx));

  CHECK_CALL(EVP_PKEY_set1_RSA(evp, rsa));
  ASSERT(RSA_check_key(rsa));

  BN_clear_free(phi_n);
  BN_clear_free(pm);
  BN_clear_free(qm);

  return evp;
}
コード例 #21
0
ファイル: openssh.c プロジェクト: cran/openssl
SEXP R_rsa_key_build(SEXP e, SEXP n, SEXP p, SEXP q, SEXP d, SEXP dp, SEXP dq, SEXP qi){
  RSA *rsa = RSA_new();
  MY_RSA_set0_key(rsa, new_bignum_from_r(n), new_bignum_from_r(e), new_bignum_from_r(d));
  MY_RSA_set0_factors(rsa, new_bignum_from_r(p), new_bignum_from_r(q));
  MY_RSA_set0_crt_params(rsa, new_bignum_from_r(dp), new_bignum_from_r(dq), new_bignum_from_r(qi));
  bail(RSA_check_key(rsa));
  unsigned char *buf = NULL;
  int len = i2d_RSAPrivateKey(rsa, &buf);
  bail(len);
  RSA_free(rsa);
  SEXP res = allocVector(RAWSXP, len);
  memcpy(RAW(res), buf, len);
  OPENSSL_free(buf);
  return res;
}
コード例 #22
0
ファイル: rsa_test.c プロジェクト: project-zerus/boringssl
static int test_only_d_given(void) {
  RSA *key = RSA_new();
  uint8_t buf[64];
  unsigned buf_len = sizeof(buf);
  const uint8_t kDummyHash[16] = {0};
  int ret = 0;

  if (!BN_hex2bn(&key->n,
                 "00e77bbf3889d4ef36a9a25d4d69f3f632eb4362214c74517da6d6aeaa9bd"
                 "09ac42b26621cd88f3a6eb013772fc3bf9f83914b6467231c630202c35b3e"
                 "5808c659") ||
      !BN_hex2bn(&key->e, "010001") ||
      !BN_hex2bn(&key->d,
                 "0365db9eb6d73b53b015c40cd8db4de7dd7035c68b5ac1bf786d7a4ee2cea"
                 "316eaeca21a73ac365e58713195f2ae9849348525ca855386b6d028e437a9"
                 "495a01") ||
      RSA_size(key) > sizeof(buf)) {
    goto err;
  }

  if (!RSA_check_key(key)) {
    fprintf(stderr, "RSA_check_key failed with only d given.\n");
    ERR_print_errors_fp(stderr);
    goto err;
  }

  if (!RSA_sign(NID_sha256, kDummyHash, sizeof(kDummyHash), buf, &buf_len,
                key)) {
    fprintf(stderr, "RSA_sign failed with only d given.\n");
    ERR_print_errors_fp(stderr);
    goto err;
  }

  if (!RSA_verify(NID_sha256, kDummyHash, sizeof(kDummyHash), buf, buf_len,
                  key)) {
    fprintf(stderr, "RSA_verify failed with only d given.\n");
    ERR_print_errors_fp(stderr);
    goto err;
  }

  ret = 1;

err:
  RSA_free(key);
  return ret;
}
コード例 #23
0
RSA *
openssl_gen_key()
{
	RSA *rsa;
	int rc, counter = 0;
	char buf[32];

	token_specific_rng((CK_BYTE *)buf, 32);
	RAND_seed(buf, 32);

regen_rsa_key:
	rsa = RSA_generate_key(2048, 65537, NULL, NULL);
	if (rsa == NULL) {
		fprintf(stderr, "Error generating user's RSA key\n");
		ERR_load_crypto_strings();
		ERR_print_errors_fp(stderr);
		return NULL;
	}

	rc = RSA_check_key(rsa);
	switch (rc) {
		case 0:
			/* rsa is not a valid RSA key */
			RSA_free(rsa);
			counter++;
			if (counter == KEYGEN_RETRY) {
				TRACE_DEVEL("Tried %d times to generate a "
					    "valid RSA key, failed.\n",
					    KEYGEN_RETRY);
				return NULL;
			}
			goto regen_rsa_key;
			break;
		case 1:
			/* success case, rsa is a valid key */
			break;
		case -1:
			/* fall through */
		default:
			DEBUG_openssl_print_errors();
			break;
	}

	return rsa;
}
コード例 #24
0
ファイル: s2n_rsa.c プロジェクト: raycoll/s2n
int s2n_asn1der_to_rsa_private_key(struct s2n_rsa_private_key *key, struct s2n_blob *asn1der)
{
    uint8_t *original_ptr = asn1der->data;

    key->rsa = d2i_RSAPrivateKey(NULL, (const unsigned char **)(void *)&asn1der->data, asn1der->size);
    if (key->rsa == NULL) {
        S2N_ERROR(S2N_ERR_DECODE_PRIVATE_KEY);
    }
    if (asn1der->data - original_ptr != asn1der->size) {
        S2N_ERROR(S2N_ERR_DECODE_PRIVATE_KEY);
    }

    if (!RSA_check_key(key->rsa)) {
        S2N_ERROR(S2N_ERR_PRIVATE_KEY_CHECK);
    }

    return 0;
}
コード例 #25
0
ファイル: openssl_crypto.c プロジェクト: Mynigma/MCryptoLib
static void 
test_seckey(const __ops_seckey_t *seckey)
{
	RSA            *test = RSA_new();

	test->n = BN_dup(seckey->pubkey.key.rsa.n);
	test->e = BN_dup(seckey->pubkey.key.rsa.e);

	test->d = BN_dup(seckey->key.rsa.d);
	test->p = BN_dup(seckey->key.rsa.p);
	test->q = BN_dup(seckey->key.rsa.q);

	if (RSA_check_key(test) != 1) {
		(void) fprintf(stderr,
			"test_seckey: RSA_check_key failed\n");
	}
	RSA_free(test);
}
コード例 #26
0
ファイル: openssl_crypto.c プロジェクト: Mynigma/MCryptoLib
/**
\ingroup Core_Crypto
\brief Decrypts RSA-encrypted data
\param out Where to write the plaintext
\param in Encrypted data
\param length Length of encrypted data
\param seckey RSA secret key
\param pubkey RSA public key
\return size of recovered plaintext
*/
int 
__ops_rsa_private_decrypt(uint8_t *out,
			const uint8_t *in,
			size_t length,
			const __ops_rsa_seckey_t *seckey,
			const __ops_rsa_pubkey_t *pubkey)
{
	RSA            *keypair;
	int             n;
	char            errbuf[1024];

	keypair = RSA_new();
	keypair->n = pubkey->n;	/* XXX: do we need n? */
	keypair->d = seckey->d;
	keypair->p = seckey->q;
	keypair->q = seckey->p;

	/* debug */
	keypair->e = pubkey->e;
	if (RSA_check_key(keypair) != 1) {
		(void) fprintf(stderr, "RSA_check_key is not set\n");
		return 0;
	}
	/* end debug */

	n = RSA_private_decrypt((int)length, in, out, keypair, RSA_NO_PADDING);

	if (__ops_get_debug_level(__FILE__)) {
		printf("__ops_rsa_private_decrypt: n=%d\n",n);
	}

	errbuf[0] = '\0';
	if (n == -1) {
		unsigned long   err = ERR_get_error();

		ERR_error_string(err, &errbuf[0]);
		(void) fprintf(stderr, "openssl error : %s\n", errbuf);
	}
	keypair->n = keypair->d = keypair->p = keypair->q = NULL;
	RSA_free(keypair);

	return n;
}
コード例 #27
0
ファイル: crypt.c プロジェクト: Ektoplasma/frontale
int RSA_chiffrement ( unsigned char* input, unsigned char* output, int mode )
{
    // Initialisation
    int flen = RSA_size ( client_key ) - PADDING_FLEN ;

    // On commence par vérifier l'intégrité de notre paire de clés
    if ( RSA_check_key ( client_key ) != 1 )
    {
        perror ( "Erreur_RSA_chiffrement : invalid RSA keys " ) ;
        fprintf ( stderr, "Code erreur OpenSSL : %lu \n ", ERR_get_error () ) ;
        return 0 ;
    }

    if ( mode == CHIFFRE )
    {
        if ( ( RSA_public_encrypt ( flen , input, output, client_key, RSA_PKCS1_PADDING ) ) <= 0 )
        {
            perror ( "Erreur_RSA_chiffrement : error chiffrement " ) ;
            fprintf ( stderr, "Code erreur OpenSSL : %lu \n ", ERR_get_error () ) ;
            return 0 ;
        }
    }
    else if ( mode == DECHIFFRE )
    {
        if ( ( RSA_private_decrypt ( flen + PADDING_FLEN, input, output, client_key, RSA_PKCS1_PADDING) ) <= 0 )
        {
            perror ( "Erreur_RSA_dechiffrement : error déchiffrement " ) ;
            fprintf ( stderr, "Code erreur OpenSSL : %lu \n ", ERR_get_error () ) ;
            return 0 ;
        }
    }
    else
    {
        perror ( "Erreur_RSA_chiffrement : bad mode " ) ;
        return 0 ;
    }

    // On indique que tout s'est bien déroulé
    printf("je retourne ici\n");
    aes_key[AES_KEY_LENGTH] = '\0';
    return 1 ;
}
コード例 #28
0
ファイル: crypt.c プロジェクト: Ektoplasma/frontale
int RSA_chiffrement ( unsigned char* input, unsigned char* output, int mode )
{
    // initialisation
    int flen = RSA_size ( bdd_key ) - PADDING_FLEN ;  // because RSA_PKCS1_PADDING : see doc

    // On commence par vérifier l'intégrité de notre paire de clés
    if ( RSA_check_key ( bdd_key ) != 1 )
    {
        perror ( "Erreur_RSA_chiffrement : invalid RSA keys " ) ;
        fprintf ( stderr, "Code erreur OpenSSL : %lu \n ", ERR_get_error () ) ;
        return ERRNO ;
    }

    if ( mode == CHIFFREMENT )
    {
        // On chiffre, toujours avec la clé publique
        if ( ( RSA_public_encrypt ( flen , input, output, bdd_key, RSA_PKCS1_PADDING ) ) <= 0 )
        {
            perror ( "Erreur_RSA_chiffrement : error chiffrement " ) ;
            fprintf ( stderr, "Code erreur OpenSSL : %lu \n ", ERR_get_error () ) ;
            return ERRNO ;
        }
    }
    else if ( mode == DECHIFFREMENT )
    {
        // On déchiffre, toujours avec la clé privée
        if ( ( RSA_private_decrypt ( flen + PADDING_FLEN, input, output, bdd_key, RSA_PKCS1_PADDING) ) <= 0 )
        {
            perror ( "Erreur_RSA_dechiffrement : error déchiffrement " ) ;
            fprintf ( stderr, "Code erreur OpenSSL : %lu \n ", ERR_get_error () ) ;
            return ERRNO ;
        }
    }
    else
    {
        perror ( "Erreur_RSA_chiffrement : bad mode " ) ;
        return ERRNO ;
    }

    // On indique que tout s'est bien déroulé
    return TRUE ;
}
コード例 #29
0
ファイル: math.c プロジェクト: ZerooCool/Shallot
uint8_t sane_key(RSA *rsa) { // checks sanity of a RSA key (PKCS#1 v2.1)
    uint8_t sane = 1;

    BN_CTX *ctx = BN_CTX_new();
    BN_CTX_start(ctx);
    BIGNUM *p1     = BN_CTX_get(ctx), // p - 1
            *q1     = BN_CTX_get(ctx), // q - 1
             *chk    = BN_CTX_get(ctx), // storage to run checks with
              *gcd    = BN_CTX_get(ctx), // GCD(p - 1, q - 1)
               *lambda = BN_CTX_get(ctx); // LCM(p - 1, q - 1)

    BN_sub(p1, rsa->p, BN_value_one()); // p - 1
    BN_sub(q1, rsa->q, BN_value_one()); // q - 1
    BN_gcd(gcd, p1, q1, ctx);           // gcd(p - 1, q - 1)
    BN_lcm(lambda, p1, q1, gcd, ctx);   // lambda(n)

    BN_gcd(chk, lambda, rsa->e, ctx); // check if e is coprime to lambda(n)
    if(!BN_is_one(chk))
        sane = 0;

    // check if public exponent e is less than n - 1
    BN_sub(chk, rsa->e, rsa->n); // subtract n from e to avoid checking BN_is_zero
    if(!chk->neg)
        sane = 0;

    BN_mod_inverse(rsa->d, rsa->e, lambda, ctx);    // d
    BN_mod(rsa->dmp1, rsa->d, p1, ctx);             // d mod (p - 1)
    BN_mod(rsa->dmq1, rsa->d, q1, ctx);             // d mod (q - 1)
    BN_mod_inverse(rsa->iqmp, rsa->q, rsa->p, ctx); // q ^ -1 mod p
    BN_CTX_end(ctx);
    BN_CTX_free(ctx);

    // this is excessive but you're better off safe than (very) sorry
    // in theory this should never be true unless I made a mistake ;)
    if((RSA_check_key(rsa) != 1) && sane) {
        fprintf(stderr, "WARNING: Key looked okay, but OpenSSL says otherwise!\n");
        sane = 0;
    }

    return sane;
}
コード例 #30
0
ファイル: hcrypt_rsa_lib.c プロジェクト: sara62/hcrypt
rsa_pubkey_t *rsa_pubkey_new_from_str(const char *str)
{
	RSA *rsa = NULL;	
	char n_buf[1024];
	char e_buf[1024];

	if (strlen(str) > sizeof(n_buf)) {
		fprintf(stderr, "rsa: input stirng to long\n");
		return NULL;
	}

	if (sscanf(str, "%s %s", n_buf, e_buf) != 2) {
		fprintf(stderr, "rsa: input invalid\n");
		return NULL;
	}

	if (!(rsa = RSA_new())) {
		ERR_print_errors_fp(stderr);
		return NULL;
	}

	if (!BN_hex2bn(&rsa->n, n_buf)) {
		ERR_print_errors_fp(stderr);
		RSA_free(rsa);
		return NULL;
	}

	if (!BN_hex2bn(&rsa->e, e_buf)) {
		ERR_print_errors_fp(stderr);
		RSA_free(rsa);
		return NULL;
	}

	if (!RSA_check_key(rsa)) {
		ERR_print_errors_fp(stderr);
		RSA_free(rsa);
		return NULL;
	}
	
	return rsa;
}