Пример #1
0
uint8_t *
rsa_genkey (void)
{
  int r;
  uint8_t index = 0;
  uint8_t *p_q_modulus = (uint8_t *)malloc (KEY_CONTENT_LEN*2);
  uint8_t *p = p_q_modulus;
  uint8_t *q = p_q_modulus + KEY_CONTENT_LEN/2;
  uint8_t *modulus = p_q_modulus + KEY_CONTENT_LEN;

  if (p_q_modulus == NULL)
    return NULL;

  rsa_init (&rsa_ctx, RSA_PKCS_V15, 0);
  r = rsa_gen_key (&rsa_ctx, random_byte, &index,
		   KEY_CONTENT_LEN * 8, RSA_EXPONENT);
  if (r < 0)
    {
      free (p_q_modulus);
      rsa_free (&rsa_ctx);
      return NULL;
    }

  mpi_write_binary (&rsa_ctx.P, p, KEY_CONTENT_LEN/2);
  mpi_write_binary (&rsa_ctx.Q, q, KEY_CONTENT_LEN/2);
  mpi_write_binary (&rsa_ctx.N, modulus, KEY_CONTENT_LEN);
  rsa_free (&rsa_ctx);
  return p_q_modulus;
}
Пример #2
0
int _vcrypt_load_keys(VCRYPT_CTX *ctx, const char *file, char *checksum)
{
	FILE *f = fopen(file, "rb");
	if (f == NULL ) {
		ctx->has_valid_keys_locally = 0;
		return -ERR_FILE_READ;
	}

	uint8_t keydata[4096];
	int keylen = fread(keydata, 1, sizeof keydata, f);
	if (keylen <= 0) {
		fclose(f);
		return -ERR_FILE_READ;
	}

	fclose(f);

	ctx->has_valid_keys_locally = 0; // the next will invalidate them
	rsa_free(&ctx->ssl_req.rsa);

	int ret = x509parse_key(&ctx->ssl_req.rsa, keydata, keylen, NULL, 0);

	if (ret == 0)
		vcrypt_get_key_fingerprint_ctx(ctx, checksum);

	ctx->has_valid_keys_locally = 1;

	return ret == 0 ? 0 : -ERR_RSA_ERROR_LOADING_KEYS;
}
Пример #3
0
int main(int argc, char **argv) {
  int ret;
  rsa_t rsa;
  uint32_t mc, vf;
  datum_t em, m;
  uint8_t EM[256];

  mlockall(MCL_CURRENT|MCL_FUTURE);

  rsa_init(&rsa);
  mc = vf = 0;
  em.data = (uint8_t *)EM;
  em.size = (uint32_t)sizeof(EM);

/*
generate these with gentests.pl
NOTE: in some cases, the RSA signing operation will produce a signature which
is 1 or more bytes less in length than N.  In these cases, it must be padded
on the left with zeros.
*/
#include "tests.c"

  rsa_free(&rsa);

  munlockall();

  printf("\nTest run completed with %d miscompares and %d verification failures.\n\n", mc, vf);

  return 0;
}
Пример #4
0
/*
	rsa oaep encryption
*/
unsigned char *rsacrypt(pk_context *pkctx,const unsigned char *plaintext,const unsigned int plaintextsize){
	entropy_context entropy = {0};
	ctr_drbg_context ctr_drbg = {0};	
	rsa_context rsactx = {0};
	int pkresult = 0;
	unsigned char *encryptedoutput = NULL;
	unsigned int encryptedoutputsize = 0;
	char pers[33] = "3s:!2OXI(FX%#Q($[CEjiGRIk\\-)4e&?";
	int ret = 0;
	
	entropy_init( &entropy );
	if((ret = ctr_drbg_init(&ctr_drbg, entropy_func, &entropy, (unsigned char *)&pers[0],strlen(pers))) != 0 ){
		outputerror(DBG_ERROR,"%s\n","rsacrypt::failed to initialize random generator");
		return NULL;
	}


	encryptedoutputsize = pk_get_len(pkctx);
	outputerror(DBG_INFO,"%s %Iu\n","rsacrypt::buffer size for rsa encrypted output ",encryptedoutputsize);
	encryptedoutput = (unsigned char *)malloc(encryptedoutputsize);
	SecureZeroMemory(encryptedoutput,encryptedoutputsize);		
	rsa_copy(&rsactx,pkctx->pk_ctx);
	rsactx.padding = RSA_PKCS_V21;
	rsactx.hash_id = POLARSSL_MD_SHA1;	
	pkresult = 0;		
	pkresult = rsa_rsaes_oaep_encrypt(&rsactx,ctr_drbg_random,&ctr_drbg,RSA_PUBLIC,"cryptoshot",strlen("cryptoshot"),plaintextsize,plaintext,encryptedoutput);
	if(pkresult != 0){
		outputerror(DBG_ERROR,"%s %i\n","rsacrypt::failed to encrypt data",pkresult);
		return NULL;
	}

	entropy_free(&entropy);	
	rsa_free(&rsactx);
	return encryptedoutput;
}
Пример #5
0
/**
  Import RSA key from raw numbers

  @param N       RSA's N
  @param Nlen    RSA's N's length
  @param e       RSA's e
  @param elen    RSA's e's length
  @param d       RSA's d  (only private key, NULL for public key)
  @param dlen    RSA's d's length
  @param key     [out] the destination for the imported key
  @return CRYPT_OK if successful
*/
int rsa_set_key(const unsigned char *N,  unsigned long Nlen,
                const unsigned char *e,  unsigned long elen,
                const unsigned char *d,  unsigned long dlen,
                rsa_key *key)
{
   int err;

   LTC_ARGCHK(key         != NULL);
   LTC_ARGCHK(N           != NULL);
   LTC_ARGCHK(e           != NULL);
   LTC_ARGCHK(ltc_mp.name != NULL);

   err = mp_init_multi(&key->e, &key->d, &key->N, &key->dQ, &key->dP, &key->qP, &key->p, &key->q, NULL);
   if (err != CRYPT_OK) return err;

   if ((err = mp_read_unsigned_bin(key->N , (unsigned char *)N , Nlen)) != CRYPT_OK)    { goto LBL_ERR; }
   if ((err = mp_read_unsigned_bin(key->e , (unsigned char *)e , elen)) != CRYPT_OK)    { goto LBL_ERR; }
   if (d && dlen) {
      if ((err = mp_read_unsigned_bin(key->d , (unsigned char *)d , dlen)) != CRYPT_OK) { goto LBL_ERR; }
      key->type = PK_PRIVATE;
   }
   else {
      key->type = PK_PUBLIC;
   }
   return CRYPT_OK;

LBL_ERR:
   rsa_free(key);
   return err;
}
Пример #6
0
int
rsa_verify (const uint8_t *pubkey, const uint8_t *hash, const uint8_t *sig)
{
  int r;

  rsa_init (&rsa_ctx, RSA_PKCS_V15, 0);
  rsa_ctx.len = KEY_CONTENT_LEN;
  mpi_lset (&rsa_ctx.E, 0x10001);
  mpi_read_binary (&rsa_ctx.N, pubkey, KEY_CONTENT_LEN);

  DEBUG_INFO ("RSA verify...");

  r = rsa_pkcs1_verify (&rsa_ctx, RSA_PUBLIC, SIG_RSA_SHA256, 32, hash, sig);

  rsa_free (&rsa_ctx);
  if (r < 0)
    {
      DEBUG_INFO ("fail:");
      DEBUG_SHORT (r);
      return r;
    }
  else
    {
      DEBUG_INFO ("verified.\r\n");
      return 0;
    }
}
Пример #7
0
bool
rsa_test(unsigned bits, mt64_context *rand_ctx)
{
    mt64_init_u64(rand_ctx, 1234567890U);

    rsa_ctx rsa;
    if (!rsa_init_keygen(&rsa, bits, rand_ctx))
	return false;
    ASSERT(rsa.n != NULL);
    ASSERT(rsa.phi != NULL);
    ASSERT(rsa.e != NULL);
    ASSERT(rsa.d != NULL);

    mpi_t m = MPI_INITIALIZER;
    mpi_mul(rsa.e, rsa.d, m);
    mpi_mod(m, rsa.phi, m);
    bool result = true;
    if (!mpi_is_one(m)) {
	printf("N: "), mpi_print_dec(rsa.n), printf("\n");
	printf("E: "), mpi_print_dec(rsa.e), printf("\n");
	printf("D: "), mpi_print_dec(rsa.d), printf("\n");
	printf("Φ: "), mpi_print_dec(rsa.phi), printf("\n");
	printf("E * D mod Φ: "), mpi_print_dec(m), printf("\n");
	result = false;
    }
    mpi_free(m);
    rsa_free(&rsa);
    return result;
}
Пример #8
0
/*
 * Copy the components of an RSA key
 */
int rsa_copy( rsa_context *dst, const rsa_context *src )
{
    int ret;

    dst->ver = src->ver;
    dst->len = src->len;

    MPI_CHK( mpi_copy( &dst->N, &src->N ) );
    MPI_CHK( mpi_copy( &dst->E, &src->E ) );

    MPI_CHK( mpi_copy( &dst->D, &src->D ) );
    MPI_CHK( mpi_copy( &dst->P, &src->P ) );
    MPI_CHK( mpi_copy( &dst->Q, &src->Q ) );
    MPI_CHK( mpi_copy( &dst->DP, &src->DP ) );
    MPI_CHK( mpi_copy( &dst->DQ, &src->DQ ) );
    MPI_CHK( mpi_copy( &dst->QP, &src->QP ) );

    MPI_CHK( mpi_copy( &dst->RN, &src->RN ) );
    MPI_CHK( mpi_copy( &dst->RP, &src->RP ) );
    MPI_CHK( mpi_copy( &dst->RQ, &src->RQ ) );

#if !defined(POLARSSL_RSA_NO_CRT)
    MPI_CHK( mpi_copy( &dst->Vi, &src->Vi ) );
    MPI_CHK( mpi_copy( &dst->Vf, &src->Vf ) );
#endif

    dst->padding = src->padding;
    dst->hash_id = src->hash_id;

cleanup:
    if( ret != 0 )
        rsa_free( dst );

    return( ret );
}
Пример #9
0
ALWAYS_INLINE void
FinalizeAsymmetricCipher( JS::HandleObject obj, bool wipe ) {

	AsymmetricCipherPrivate *pv = (AsymmetricCipherPrivate*)JL_GetPrivate(obj);
	if ( pv ) {

		if ( pv->hasKey ) {

			switch ( pv->cipher ) {
				case rsa:
					rsa_free( &pv->key.rsaKey );
					break;
				case ecc:
					ecc_free( &pv->key.eccKey );
					break;
				case dsa:
					dsa_free( &pv->key.dsaKey );
					break;
			#ifdef MKAT
				case katja:
					katja_free( &pv->key.katjaKey );
					break;
			#endif
			}
		}

		if ( wipe )
			zeromem(pv, sizeof(AsymmetricCipherPrivate));
		jl_free(pv);
	}
}
Пример #10
0
static DWORD VerifyWeakSignature(
    TMPQArchive * ha,
    PMPQ_SIGNATURE_INFO pSI)
{
    BYTE RevSignature[MPQ_WEAK_SIGNATURE_SIZE];
    BYTE Md5Digest[MD5_DIGEST_SIZE];
    rsa_key key;
    int hash_idx = find_hash("md5");
    int result = 0;

    // Calculate hash of the entire archive, skipping the (signature) file
    if(!CalculateMpqHashMd5(ha, pSI, Md5Digest))
        return ERROR_VERIFY_FAILED;

    // Import the Blizzard key in OpenSSL format
    if(!decode_base64_key(szBlizzardWeakPublicKey, &key))
        return ERROR_VERIFY_FAILED;

    // Verify the signature
    memcpy(RevSignature, &pSI->Signature[8], MPQ_WEAK_SIGNATURE_SIZE);
    memrev(RevSignature, MPQ_WEAK_SIGNATURE_SIZE);
    rsa_verify_hash_ex(RevSignature, MPQ_WEAK_SIGNATURE_SIZE, Md5Digest, sizeof(Md5Digest), LTC_LTC_PKCS_1_V1_5, hash_idx, 0, &result, &key);
    rsa_free(&key);

    // Return the result
    return result ? ERROR_WEAK_SIGNATURE_OK : ERROR_WEAK_SIGNATURE_ERROR;
}
Пример #11
0
static int rsa_genkey (lua_State *L) {
    rsa_context rsa;
    havege_state hs;
    int ret=0;
    
    rsa_init( &rsa, RSA_PKCS_V15, 0, havege_rand, &hs );
    
    if( ( ret = rsa_gen_key( &rsa, KEY_SIZE, EXPONENT ) ) != 0 )
    {
        luaL_error(L, "Error generating key (%d)", ret);
    }
    
    /* Public Key */
    if(ret = push_public_key(L, &rsa))
    {
    	luaL_error(L, "failed to obtain public key: error %d", ret );
    }
    
    /* Private Key */
    if(ret = push_private_key(L, &rsa))
    {
    	luaL_error(L, "failed to obtain private key: error %d", ret );
    }
    
    rsa_free( &rsa );
    
    return 2;
}
Пример #12
0
void cleanup_crypt(void)
{
    /* this never gets called because we never cleanly exit, but
       here it is for completeness */
    rsa_free(&key);
    unregister_prng(&yarrow_desc);
}
Пример #13
0
int main(int argc, char **argv)
{
    int rc = 0;
    prng_state prng;
    int prng_index, hash_index;
    rsa_key key;
    int i;

    ltc_mp = tfm_desc;

    prng_index = register_prng(&sprng_desc);  /* (fortuna_desc is a good choice if your platform's PRNG sucks.) */
    if (prng_index == -1) {
        fail("Failed to register a RNG");
    }

    hash_index = register_hash(&sha256_desc);
    if (hash_index == -1) {
        fail("Failed to register sha256 hasher");
    }

    if ((rc = rng_make_prng(128, prng_index, &prng, NULL)) != CRYPT_OK) {
        fail("rng_make_prng failed: %s", error_to_string(rc));
    }

    read_rsakey(&key, "privatekey.bin");

    for (i = 1; i < argc; i++) {
        sign_file(argv[i], &key, &prng, prng_index, hash_index);
    }

    rsa_free(&key);

    return 0;
}
Пример #14
0
int SparkProtocol::handshake(void)
{
  memcpy(queue + 40, device_id, 12);
  int err = blocking_receive(queue, 40);
  if (0 > err) return err;

  parse_device_pubkey_from_privkey(queue+52, core_private_key);

  rsa_context rsa;
  init_rsa_context_with_public_key(&rsa, server_public_key);
  const int len = 52+MAX_DEVICE_PUBLIC_KEY_LENGTH;
  err = rsa_pkcs1_encrypt(&rsa, RSA_PUBLIC, len, queue, queue + len);
  rsa_free(&rsa);

  if (err) return err;

  blocking_send(queue + len, 256);
  err = blocking_receive(queue, 384);
  if (0 > err) return err;

  err = set_key(queue);
  if (err) return err;

  queue[0] = 0x00;
  queue[1] = 0x10;
  hello(queue + 2, descriptor.was_ota_upgrade_successful());

  err = blocking_send(queue, 18);
  if (0 > err) return err;

  if (!event_loop())        // read the hello message from the server
      return -1;

  return 0;
}
Пример #15
0
void free_connection(connection_t *c) {
	if(!c)
		return;

	cipher_close(c->incipher);
	digest_close(c->indigest);
	cipher_close(c->outcipher);
	digest_close(c->outdigest);

	sptps_stop(&c->sptps);
	ecdsa_free(c->ecdsa);
	rsa_free(c->rsa);

	free(c->hischallenge);

	buffer_clear(&c->inbuf);
	buffer_clear(&c->outbuf);

	io_del(&c->io);

	if(c->socket > 0)
		closesocket(c->socket);

	free(c->name);
	free(c->hostname);

	if(c->config_tree)
		exit_configuration(&c->config_tree);

	free(c);
}
Пример #16
0
static int ctr_rsa_key_init(ctr_rsa_context* ctx )
{
    int ret;
    mpi P1, Q1;

    mpi_init( &P1, &Q1, NULL );

    MPI_CHK( mpi_sub_int( &P1, &ctx->rsa.P, 1 ) );
    MPI_CHK( mpi_sub_int( &Q1, &ctx->rsa.Q, 1 ) );

	/*
     * DP = D mod (P - 1)
     * DQ = D mod (Q - 1)
     * QP = Q^-1 mod P
     */
    MPI_CHK( mpi_mod_mpi( &ctx->rsa.DP, &ctx->rsa.D, &P1 ) );
    MPI_CHK( mpi_mod_mpi( &ctx->rsa.DQ, &ctx->rsa.D, &Q1 ) );
    MPI_CHK( mpi_inv_mod( &ctx->rsa.QP, &ctx->rsa.Q, &ctx->rsa.P ) );

cleanup:

    mpi_free(&Q1, &P1, NULL );

    if( ret != 0 )
    {
        rsa_free( &ctx->rsa );
        return( POLARSSL_ERR_RSA_KEY_GEN_FAILED | ret );
    }

    return( 0 );   
}
Пример #17
0
static int rsa_compat_test(void)
{
   rsa_key key;
   unsigned char buf[1024];
   unsigned long len;

   /* try reading the key */
   DO(rsa_import(openssl_private_rsa, sizeof(openssl_private_rsa), &key));

   /* now try to export private/public and compare */
   len = sizeof(buf);
   DO(rsa_export(buf, &len, PK_PRIVATE, &key));
   if (len != sizeof(openssl_private_rsa) || memcmp(buf, openssl_private_rsa, len)) {
      fprintf(stderr, "RSA private export failed to match OpenSSL output, %lu, %lu\n", len, (unsigned long)sizeof(openssl_private_rsa));
      return 1;
   }

   len = sizeof(buf);
   DO(rsa_export(buf, &len, PK_PUBLIC, &key));
   if (len != sizeof(openssl_public_rsa_stripped) || memcmp(buf, openssl_public_rsa_stripped, len)) {
      fprintf(stderr, "RSA(private) public export failed to match OpenSSL output\n");
      return 1;
   }
   rsa_free(&key);

   /* try reading the public key */
   DO(rsa_import(openssl_public_rsa_stripped, sizeof(openssl_public_rsa_stripped), &key));
   len = sizeof(buf);
   DO(rsa_export(buf, &len, PK_PUBLIC, &key));
   if (len != sizeof(openssl_public_rsa_stripped) || memcmp(buf, openssl_public_rsa_stripped, len)) {
      fprintf(stderr, "RSA(public) stripped public import failed to match OpenSSL output\n");
      return 1;
   }
   rsa_free(&key);

   /* try reading the public key */
   DO(rsa_import(openssl_public_rsa, sizeof(openssl_public_rsa), &key));
   len = sizeof(buf);
   DO(rsa_export(buf, &len, PK_PUBLIC, &key));
   if (len != sizeof(openssl_public_rsa_stripped) || memcmp(buf, openssl_public_rsa_stripped, len)) {
      fprintf(stderr, "RSA(public) SSL public import failed to match OpenSSL output\n");
      return 1;
   }
   rsa_free(&key);

   return 0;
}   
Пример #18
0
/*
 * Generate an RSA keypair
 */
int rsa_gen_key( rsa_context *ctx, int nbits, int exponent,
                 ulong (*rng_fn)(void *), void *rng_st )
{
    int ret;
    mpi P1, Q1, H, G;

    mpi_init( &P1, &Q1, &H, &G, NULL );

    memset( ctx, 0, sizeof( rsa_context ) );

    /*
     * find primes P and Q with Q < P so that:
     * GCD( E, (P-1)*(Q-1) ) == 1
     */
    CHK( mpi_lset( &ctx->E, exponent ) );

    nbits >>= 1;

    do
    {
        CHK( mpi_gen_prime( &ctx->P, nbits, 0, rng_fn, rng_st ) );
        CHK( mpi_gen_prime( &ctx->Q, nbits, 0, rng_fn, rng_st ) );

        if( mpi_cmp_mpi( &ctx->P, &ctx->Q ) < 0 )
            mpi_swap( &ctx->P, &ctx->Q );

        CHK( mpi_mul_mpi( &ctx->N, &ctx->P, &ctx->Q ) );
        CHK( mpi_sub_int( &P1, &ctx->P, 1 ) );
        CHK( mpi_sub_int( &Q1, &ctx->Q, 1 ) );
        CHK( mpi_mul_mpi( &H, &P1, &Q1 ) );
        CHK( mpi_gcd( &G, &ctx->E, &H  ) );
    }
    while( mpi_cmp_int( &G, 1 ) != 0 );

    /*
     * D  = E^-1 mod ((P-1)*(Q-1))
     * DP = D mod (P - 1)
     * DQ = D mod (Q - 1)
     * QP = Q^-1 mod P
     */
    CHK( mpi_inv_mod( &ctx->D , &ctx->E, &H  ) );
    CHK( mpi_mod_mpi( &ctx->DP, &ctx->D, &P1 ) );
    CHK( mpi_mod_mpi( &ctx->DQ, &ctx->D, &Q1 ) );
    CHK( mpi_inv_mod( &ctx->QP, &ctx->Q, &ctx->P ) );

    ctx->len = ( mpi_size( &ctx->N ) + 7 ) >> 3;

cleanup:

    mpi_free( &P1, &Q1, &H, &G, NULL );

    if( ret != 0 )
    {
        rsa_free( ctx );
        return( ERR_RSA_KEYGEN_FAILED | ret );
    }

    return( 0 );   
}
static int rsa_compat_test(void)
{
   rsa_key key;
   unsigned char buf[1024];
   unsigned long len;

   /* try reading the key */
   DO(rsa_import(openssl_private_rsa, sizeof(openssl_private_rsa), &key));

   /* now try to export private/public and compare */
   len = sizeof(buf);
   DO(rsa_export(buf, &len, PK_PRIVATE, &key));
   if (len != sizeof(openssl_private_rsa) || memcmp(buf, openssl_private_rsa, len)) {
      fprintf(stderr, "RSA private export failed to match OpenSSL output, %lu, %lu\n", len, sizeof(openssl_private_rsa));


{
int x;
printf("\n\n");
for (x = 0; x < len; ) { if (buf[x] == openssl_private_rsa[x]) printf("-- "); else printf("%02x ", buf[x]^openssl_private_rsa[x]); if (!(++x & 15)) printf("\n"); }
}
printf("\n\n");

      return 1;
   }

   len = sizeof(buf);
   DO(rsa_export(buf, &len, PK_PUBLIC, &key));
   if (len != sizeof(openssl_public_rsa) || memcmp(buf, openssl_public_rsa, len)) {
      fprintf(stderr, "RSA(private) public export failed to match OpenSSL output\n");
      return 1;
   }
   rsa_free(&key);

   /* try reading the public key */
   DO(rsa_import(openssl_public_rsa, sizeof(openssl_public_rsa), &key));
   len = sizeof(buf);
   DO(rsa_export(buf, &len, PK_PUBLIC, &key));
   if (len != sizeof(openssl_public_rsa) || memcmp(buf, openssl_public_rsa, len)) {
      fprintf(stderr, "RSA(public) public export failed to match OpenSSL output\n");
      return 1;
   }
   rsa_free(&key);

   return 0;
}   
Пример #20
0
void Curl_polarssl_close(struct connectdata *conn, int sockindex)
{
  rsa_free(&conn->ssl[sockindex].rsa);
  x509_free(&conn->ssl[sockindex].clicert);
  x509_free(&conn->ssl[sockindex].cacert);
  x509_crl_free(&conn->ssl[sockindex].crl);
  ssl_free(&conn->ssl[sockindex].ssl);
}
Пример #21
0
/*
    Generate an RSA keypair
 */
int rsa_gen_key(rsa_context *ctx, int nbits, int exponent)
{
    mpi     P1, Q1, H, G;
    int     ret;

    if (ctx->f_rng == NULL || nbits < 128 || exponent < 3) {
        return EST_ERR_RSA_BAD_INPUT_DATA;
    }
    mpi_init(&P1, &Q1, &H, &G, NULL);

    /*
        find primes P and Q with Q < P so that: GCD( E, (P-1)*(Q-1) ) == 1
     */
    MPI_CHK(mpi_lset(&ctx->E, exponent));

    do {
        MPI_CHK(mpi_gen_prime(&ctx->P, (nbits + 1) >> 1, 0, ctx->f_rng, ctx->p_rng));

        MPI_CHK(mpi_gen_prime(&ctx->Q, (nbits + 1) >> 1, 0, ctx->f_rng, ctx->p_rng));

        if (mpi_cmp_mpi(&ctx->P, &ctx->Q) < 0) {
            mpi_swap(&ctx->P, &ctx->Q);
        }
        if (mpi_cmp_mpi(&ctx->P, &ctx->Q) == 0) {
            continue;
        }
        MPI_CHK(mpi_mul_mpi(&ctx->N, &ctx->P, &ctx->Q));
        if (mpi_msb(&ctx->N) != nbits) {
            continue;
        }
        MPI_CHK(mpi_sub_int(&P1, &ctx->P, 1));
        MPI_CHK(mpi_sub_int(&Q1, &ctx->Q, 1));
        MPI_CHK(mpi_mul_mpi(&H, &P1, &Q1));
        MPI_CHK(mpi_gcd(&G, &ctx->E, &H));

    } while (mpi_cmp_int(&G, 1) != 0);

    /*
       D  = E^-1 mod ((P-1)*(Q-1))
       DP = D mod (P - 1)
       DQ = D mod (Q - 1)
       QP = Q^-1 mod P
     */
    MPI_CHK(mpi_inv_mod(&ctx->D, &ctx->E, &H));
    MPI_CHK(mpi_mod_mpi(&ctx->DP, &ctx->D, &P1));
    MPI_CHK(mpi_mod_mpi(&ctx->DQ, &ctx->D, &Q1));
    MPI_CHK(mpi_inv_mod(&ctx->QP, &ctx->Q, &ctx->P));

    ctx->len = (mpi_msb(&ctx->N) + 7) >> 3;

cleanup:
    mpi_free(&G, &H, &Q1, &P1, NULL);
    if (ret != 0) {
        rsa_free(ctx);
        return EST_ERR_RSA_KEY_GEN_FAILED | ret;
    }
    return 0;
}
Пример #22
0
static void Curl_polarssl_close(struct connectdata *conn, int sockindex)
{
  struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  rsa_free(&BACKEND->rsa);
  x509_crt_free(&BACKEND->clicert);
  x509_crt_free(&BACKEND->cacert);
  x509_crl_free(&BACKEND->crl);
  ssl_free(&BACKEND->ssl);
}
Пример #23
0
int test_rsa_encryption()
{
    RSA *rsa_pri_key = NULL;
    RSA *rsa_pub_key = NULL;

    unsigned char encryDataByte[1024] = {0};
    unsigned char decryDataString[1024] = {0};
    unsigned int decryStringLen = 0;

    /****************** create RSA Key **********************/
    puts("make_keys_by_create");
    make_keys_by_create(&rsa_pri_key, &rsa_pub_key);
    /***********************************************************/


    unsigned char msg[1024] = {0};
    int i = 0;
    for(i = 0; i < 11; ++i)
        msg[i] = 'A' + i / 10;

    /********************* encrypted msg ********************************/
    printf("rsa_encryption msg %d ( rsa_len:%d)--> %s\n", strlen(msg), RSA_size(rsa_pub_key), msg);
    //if( 0 != rsa_public_encryption(&rsa_pub_key, msg, strlen(msg), encryDataByte) )
    if( 0 != rsa_private_encryption(&rsa_pri_key, msg, strlen(msg), encryDataByte) )
    {
        return -1;
    }
    /*********************************************************************/
    
    /******************** decrypted msg ****************************************/
    puts("rsa_decryption");
    //rsa_private_decryption(&rsa_pri_key, encryDataByte, decryDataString);
    rsa_public_decryption(&rsa_pub_key, encryDataByte, decryDataString);
    /*************************************************************************/

    printf("decryDataString --> %s\n", decryDataString);

    if( rsa_pri_key )
        rsa_free( rsa_pri_key );
    if( rsa_pub_key )
        rsa_free( rsa_pub_key );

    return 0;
}
Пример #24
0
/**
*  Decrypts a string and removes the padding using either private or public key. 
* (depending on mode).
*  @param ciphertext: binary string to be decrypted.
*  @param key: table containing either the public or the private key, as generated by gen_key.
*  @return  The original message (if everything works ok).
*  @see  rsa_genkey
*/
static int luarsa_pkcs1_decrypt (lua_State *L) {
	int res = 0;
	int mode;
    size_t lmsg, lresult;
    rsa_context rsa;
    char *message = (char*)luaL_checklstring(L, 1, &lmsg); /* ciphertext */
    char result[KEY_SIZE];
    
    rsa_init( &rsa, RSA_PKCS_V15, 0, NULL, NULL ); 
    

    mode = processKey(L, 2, &rsa); /* keytable */
    
    rsa.len = lmsg;

    memset(result, 0, KEY_SIZE);
    printf("\nMode==%s\n", mode==RSA_PUBLIC ? "RSA_PUBLIC" : "RSA_PRIVATE" );
    printf("Size==%d\n", lmsg );
    printf("Crypt.Size==%d\n", rsa.len );
    
    printf("ver: %d\n", rsa.ver);
    printf("len: %d\n", rsa.len);
    printf("padding: %d\n", rsa.padding);
    printf("hash_id: %d\n", rsa.hash_id);
    
    mpi_print("N:%s\n", &rsa.N);
    mpi_print("E:%s\n", &rsa.E);
    
    if(mode!=RSA_PUBLIC) {
        mpi_print("D:%s\n", &rsa.D);
        mpi_print("P:%s\n", &rsa.P);
        mpi_print("Q:%s\n", &rsa.Q);
        mpi_print("DP:%s\n", &rsa.DP);
        mpi_print("DQ:%s\n", &rsa.DQ);
        mpi_print("QP:%s\n", &rsa.QP);

        //mpi_print("RN:%s\n", &rsa.RN);
        //mpi_print("RP:%s\n", &rsa.RP);
        //mpi_print("RQ:%s\n", &rsa.RQ);
    }
    
    // pass rsa context and ciphertext to decryption engine
    res = rsa_pkcs1_decrypt(&rsa, RSA_PRIVATE, &lmsg, message, result);
    printf("Orig.Size==%d\n", lmsg );
    
    if(res) {
    	luaL_error(L, "Error during cipher (%d)", res);
    }
    
    // push encrypted result buffer
    lua_pushlstring(L, result, lmsg); /* ciphertext */

    rsa_free( &rsa );
    
    return 1;
}
Пример #25
0
__hidden void __ustream_ssl_context_free(struct ustream_ssl_ctx *ctx)
{
#ifdef USE_VERSION_1_3
    pk_free(&ctx->key);
    x509_crt_free(&ctx->cert);
#else
    rsa_free(&ctx->key);
    x509_free(&ctx->cert);
#endif
    free(ctx);
}
Пример #26
0
/* this updates/creates only the key file, to use the key a reconnect is needed */
int vcrypt_generate_keys_sync(VCRYPT_CTX *ctx, const char* filename,
		char pub_checksum[FLETCHER_SIZE_STR])
{
	int ret;

	// TODO: this deletes the old key
	FILE *f = fopen(filename, "wb");
	if (f == NULL ) {
		return -ERR_FILE_WRITE;
	}

	// we use temporary rsa storage
	rsa_context rsa;
	rsa_init(&rsa, ctx->ssl_req.rsa.padding, ctx->ssl_req.rsa.hash_id);

	if ((ret = rsa_gen_key(&rsa, ctr_drbg_random, &ctx->ssl_req.ctr_drbg,
			2048 /*4096*/, 65537)) != 0) {
		return -ERR_RSA_ERROR_GENERATING_KEYS;
	}

	uint8_t keys[4096];
	int pk_len = asn1_encode_private_key_der(keys, sizeof keys, &rsa);

	if (pk_len <= 0) {
		fclose(f);
		rsa_free(&rsa);
		return -ERR_UNKNOWN(900);
	}

	if (fwrite(keys, 1, pk_len, f) != pk_len) {
		fclose(f);
		rsa_free(&rsa);
		return -ERR_FILE_WRITE;
	}

	rsa_get_public_key_fingerprint(&rsa, NULL, pub_checksum);

	rsa_free(&rsa);
	fclose(f);
	return pk_len > 0 ? 0 : pk_len;
}
Пример #27
0
int verify_signature(const unsigned char *signature,
                     const unsigned char *pubkey,
                     const unsigned char *expected_hmac)
{
  rsa_context rsa;
  init_rsa_context_with_public_key(&rsa, pubkey);

  int ret = rsa_pkcs1_verify(&rsa, RSA_PUBLIC, RSA_RAW, 20,
                             expected_hmac, signature);
  rsa_free(&rsa);
  return ret;
}
Пример #28
0
int
rsa_decrypt (const uint8_t *input, uint8_t *output, int msg_len,
	     struct key_data *kd)
{
  mpi P1, Q1, H;
  int r;
  int output_len;

  DEBUG_INFO ("RSA decrypt:");
  DEBUG_WORD ((uint32_t)&output_len);

  mpi_init (&P1, &Q1, &H, NULL);
  rsa_init (&rsa_ctx, RSA_PKCS_V15, 0);

  rsa_ctx.len = msg_len;
  DEBUG_WORD (msg_len);

  mpi_lset (&rsa_ctx.E, 0x10001);
  mpi_read_binary (&rsa_ctx.P, &kd->data[0], KEY_CONTENT_LEN / 2);
  mpi_read_binary (&rsa_ctx.Q, &kd->data[KEY_CONTENT_LEN/2],
		   KEY_CONTENT_LEN / 2);
#if 0 /* Using CRT, we don't use N */
  mpi_mul_mpi (&rsa_ctx.N, &rsa_ctx.P, &rsa_ctx.Q);
#endif
  mpi_sub_int (&P1, &rsa_ctx.P, 1);
  mpi_sub_int (&Q1, &rsa_ctx.Q, 1);
  mpi_mul_mpi (&H, &P1, &Q1);
  mpi_inv_mod (&rsa_ctx.D , &rsa_ctx.E, &H);
  mpi_mod_mpi (&rsa_ctx.DP, &rsa_ctx.D, &P1);
  mpi_mod_mpi (&rsa_ctx.DQ, &rsa_ctx.D, &Q1);
  mpi_inv_mod (&rsa_ctx.QP, &rsa_ctx.Q, &rsa_ctx.P);
  mpi_free (&P1, &Q1, &H, NULL);

  DEBUG_INFO ("RSA decrypt ...");

  r = rsa_pkcs1_decrypt (&rsa_ctx, RSA_PRIVATE, &output_len,
			 input, output, MAX_RES_APDU_DATA_SIZE);
  rsa_free (&rsa_ctx);
  if (r < 0)
    {
      DEBUG_INFO ("fail:");
      DEBUG_SHORT (r);
      return r;
    }
  else
    {
      res_APDU_size = output_len;
      DEBUG_INFO ("done.\r\n");
      GPG_SUCCESS ();
      return 0;
    }
}
Пример #29
0
uint8_t *rsa_apply(uint8_t *input, int inlen, int *outlen, int mode) {
  rsa_context trsa;
  const char *pers = "rsa_encrypt";
  int rc;

  entropy_context entropy;
  ctr_drbg_context ctr_drbg;
  entropy_init(&entropy);
  if ((rc = ctr_drbg_init(&ctr_drbg, entropy_func, &entropy, (const unsigned char *)pers,
                          strlen(pers))) != 0)
    debug(1, "ctr_drbg_init returned %d\n", rc);

  rsa_init(&trsa, RSA_PKCS_V21, POLARSSL_MD_SHA1); // padding and hash id get overwritten
  // BTW, this seems to reset a lot of parameters in the rsa_context
  rc = x509parse_key(&trsa, (unsigned char *)super_secret_key, strlen(super_secret_key), NULL, 0);
  if (rc != 0)
    debug(1, "Error %d reading the private key.");

  uint8_t *out = NULL;

  switch (mode) {
  case RSA_MODE_AUTH:
    trsa.padding = RSA_PKCS_V15;
    trsa.hash_id = POLARSSL_MD_NONE;
    debug(2, "rsa_apply encrypt");
    out = malloc(trsa.len);
    rc = rsa_pkcs1_encrypt(&trsa, ctr_drbg_random, &ctr_drbg, RSA_PRIVATE, inlen, input, out);
    if (rc != 0)
      debug(1, "rsa_pkcs1_encrypt error %d.", rc);
    *outlen = trsa.len;
    break;
  case RSA_MODE_KEY:
    debug(2, "rsa_apply decrypt");
    trsa.padding = RSA_PKCS_V21;
    trsa.hash_id = POLARSSL_MD_SHA1;
    out = malloc(trsa.len);
#if POLARSSL_VERSION_NUMBER >= 0x01020900
    rc = rsa_pkcs1_decrypt(&trsa, ctr_drbg_random, &ctr_drbg, RSA_PRIVATE, (size_t *)outlen, input,
                           out, trsa.len);
#else
    rc = rsa_pkcs1_decrypt(&trsa, RSA_PRIVATE, outlen, input, out, trsa.len);
#endif
    if (rc != 0)
      debug(1, "decrypt error %d.", rc);
    break;
  default:
    die("bad rsa mode");
  }
  rsa_free(&trsa);
  debug(2, "rsa_apply exit");
  return out;
}
Пример #30
0
wiced_result_t wiced_tls_deinit_context( wiced_tls_simple_context_t* tls_context )
{
    /* Check if context is of an advanced variety. Note that the server and advanced client context are exactly the same */
    if (tls_context->context_type == WICED_TLS_ADVANCED_CONTEXT)
    {
        x509_free(&((wiced_tls_advanced_context_t*)tls_context)->certificate);
        rsa_free(&((wiced_tls_advanced_context_t*)tls_context)->key);
    }

    ssl_free( &tls_context->context);

    return WICED_SUCCESS;
}