int mpfr_round_p (mp_limb_t *bp, mp_size_t bn, mp_exp_t err0, mp_prec_t prec) { int i1, i2; i1 = mpfr_round_p_2 (bp, bn, err0, prec); i2 = mpfr_can_round_raw (bp, bn, MPFR_SIGN_POS, err0, GMP_RNDN, GMP_RNDZ, prec); if (i1 != i2) { fprintf (stderr, "mpfr_round_p(%d) != mpfr_can_round(%d)!\n" "bn = %ld, err0 = %ld, prec = %ld\nbp = ", i1, i2, bn, err0, prec); gmp_fprintf (stderr, "%NX\n", bp, bn); MPFR_ASSERTN (0); } return i1; }
int main(int argc, char **argv) { if (argc < 3) { printf("Usage: %s inputfile outputfile [pubkeyfile]\n", argv[0]); exit(0); } char *ptxtfname = argv[1]; char *ctxtfname = argv[2]; char *pkeyfname; if (argc != 4) { pkeyfname = "id_rsa.pub"; } else { pkeyfname = argv[3]; } FILE *fptxt = fopen(ptxtfname, "r"); FILE *fctxt = fopen(ctxtfname, "w"); FILE *fpkey = fopen(pkeyfname, "r"); pubkey pkey; mpz_init(pkey.n); mpz_init(pkey.e); gmp_fscanf(fpkey, "%Zd", &(pkey.n)); gmp_fscanf(fpkey, "%Zd", &pkey.e); int c = getc(fptxt); int count = 0; mpz_t next; mpz_init(next); while (c != EOF) { encrypt_char(next, c, pkey); gmp_fprintf(fctxt, "%Zd\n", next); c = getc(fptxt); } }
int MySha::computeSha256(const char * plaintextPath, const char * fileNameHash){ SHA256_CTX sha256; unsigned char hash[SHA256_DIGEST_LENGTH]; int i; FILE *plaintext; FILE *hashFile; char ligne[256]; char pathHash[50]; SHA256_Init(&sha256); plaintext = fopen(plaintextPath, "r"); if(plaintext == NULL){ return 1; } else{ while(fgets(ligne, 256, plaintext) != NULL){ SHA256_Update(&sha256, ligne, strlen(ligne)); } SHA256_Final(hash, &sha256); sprintf(pathHash, "../ressources/%s.hash", fileNameHash); // On stocke le hash dans un fichier if((hashFile = fopen(pathHash, "w")) == NULL){ return 1; } else{ for(i=0 ; i<SHA256_DIGEST_LENGTH ; i++){ gmp_fprintf(hashFile, "%02X", hash[i]); } fclose(plaintext); fclose(hashFile); return 0; } } }
static mp_size_t one_test (mpz_t a, mpz_t b, int i) { struct hgcd_matrix hgcd; struct hgcd_ref ref; mpz_t ref_r0; mpz_t ref_r1; mpz_t hgcd_r0; mpz_t hgcd_r1; mp_size_t res[2]; mp_size_t asize; mp_size_t bsize; mp_size_t hgcd_init_scratch; mp_size_t hgcd_scratch; mp_ptr hgcd_init_tp; mp_ptr hgcd_tp; asize = a->_mp_size; bsize = b->_mp_size; ASSERT (asize >= bsize); hgcd_init_scratch = MPN_HGCD_MATRIX_INIT_ITCH (asize); hgcd_init_tp = refmpn_malloc_limbs (hgcd_init_scratch); mpn_hgcd_matrix_init (&hgcd, asize, hgcd_init_tp); hgcd_scratch = mpn_hgcd_itch (asize); hgcd_tp = refmpn_malloc_limbs (hgcd_scratch); #if 0 fprintf (stderr, "one_test: i = %d asize = %d, bsize = %d\n", i, a->_mp_size, b->_mp_size); gmp_fprintf (stderr, "one_test: i = %d\n" " a = %Zx\n" " b = %Zx\n", i, a, b); #endif hgcd_ref_init (&ref); mpz_init_set (ref_r0, a); mpz_init_set (ref_r1, b); res[0] = hgcd_ref (&ref, ref_r0, ref_r1); mpz_init_set (hgcd_r0, a); mpz_init_set (hgcd_r1, b); if (bsize < asize) { _mpz_realloc (hgcd_r1, asize); MPN_ZERO (hgcd_r1->_mp_d + bsize, asize - bsize); } res[1] = mpn_hgcd (hgcd_r0->_mp_d, hgcd_r1->_mp_d, asize, &hgcd, hgcd_tp); if (res[0] != res[1]) { fprintf (stderr, "ERROR in test %d\n", i); fprintf (stderr, "Different return value from hgcd and hgcd_ref\n"); fprintf (stderr, "op1="); debug_mp (a, -16); fprintf (stderr, "op2="); debug_mp (b, -16); fprintf (stderr, "hgcd_ref: %ld\n", (long) res[0]); fprintf (stderr, "mpn_hgcd: %ld\n", (long) res[1]); abort (); } if (res[0] > 0) { if (!hgcd_ref_equal (&hgcd, &ref) || !mpz_mpn_equal (ref_r0, hgcd_r0->_mp_d, res[1]) || !mpz_mpn_equal (ref_r1, hgcd_r1->_mp_d, res[1])) { fprintf (stderr, "ERROR in test %d\n", i); fprintf (stderr, "mpn_hgcd and hgcd_ref returned different values\n"); fprintf (stderr, "op1="); debug_mp (a, -16); fprintf (stderr, "op2="); debug_mp (b, -16); abort (); } } refmpn_free_limbs (hgcd_init_tp); refmpn_free_limbs (hgcd_tp); hgcd_ref_clear (&ref); mpz_clear (ref_r0); mpz_clear (ref_r1); mpz_clear (hgcd_r0); mpz_clear (hgcd_r1); return res[0]; }
int main(int argc, char **argv) { int org=0; char *line; int i,j; int sourceline=0; char skout[500],pkout[500]; //printf("argc=%d\n",argc); if(argc!=3) { printf("usage: %s <in> <out>\n",argv[0]); exit(0); } sprintf(skout,"%s.hcrypt_sk",argv[2]); sprintf(pkout,"%s.hcrypt_pk",argv[2]); fhe_pk_init(pk); fhe_sk_init(sk); // fhe_pk_loadkey(pk,argv[3]); //fhe_pk_print(pk); puts("keygen"); fhe_keygen(pk,sk); fhe_pk_store(pk,pkout); fhe_sk_store(sk,skout); printf("wrote secret key: %s\n",skout); printf("wrote public key: %s\n",pkout); symbols=NULL; alloc=&symbols; FILE *r=NULL; FILE *w=NULL; //BufferedReader r=new BufferedReader(new FileReader("/tmp/test.asm")); r=fopen(argv[1],"r"); if(r==NULL) { puts("source error"); return 8; } //BufferedWriter w=new BufferedWriter(new FileWriter("/tmp/test.obj")); w=fopen(argv[2],"w"); if(w==NULL) { puts("target error"); return 8; } //System.out.println("PASS 1"); puts("pass 1"); line=(char*)malloc(1024); //HashMap<String,Integer> labels=new HashMap<String,Integer>(); while(!feof(r)) { char *token, *tokens[100]; //String label=null; char *label; int numtokens; //String line=r.readLine(); ++sourceline; fgets(line,100,r); if(*line==0) break; if(strstr(line,"INITAC")||strstr(line,"INITPC")) continue; //StringTokenizer st=new StringTokenizer(line," \t\n;"); numtokens=0; token=strtok(line," \n\t"); while(token!=NULL) { tokens[numtokens]=token; token=strtok(NULL," \n\t"); ++numtokens; } label=tokens[0]; if(numtokens==0) continue; if(numtokens==2) { if(!(*line==' '||*line=='\t')) { //++label; //labels.put(label, new Integer(org)); //printf("put symbol %s=%d\n",label,org); putsymbol(label,org,1,sourceline); } } else if(numtokens>2) { //++label; //labels.put(label, new Integer(org)); //printf("put symbol %s=%d\n",label,org); putsymbol(label,org,1,sourceline); } org++; } //printlist(symbols); printf(" %d symbols\n %d command words\n",numsymbols,org); //XXX //System.out.println("PASS 2"); puts("pass 2"); rewind(r); sourceline=0; //r=new BufferedReader(new FileReader("test.asm")); while(!feof(r)) { char *token, *tokens[100]; //String label=null; char *label,*opcode,*operand; int numtokens,symboladdress,cmd; char line0; struct node_t *search; //String label=null; ++sourceline; fgets(line,100,r); if(feof(r)) break; if(*line==0) break; line0=*line; numtokens=0; token=strtok(line," \n\t"); while(token!=NULL) { tokens[numtokens]=token; token=strtok(NULL," \n\t"); ++numtokens; } //StringTokenizer st=new StringTokenizer(line," \n\t;"); if(numtokens==0) continue; if(!strcmp(tokens[0],"INITAC")) { search=findsymbol(symbols,tokens[1]); if(search!=NULL) { symboladdress=search->i; } else { symboladdress=atoi(tokens[1]); if(symboladdress==0&&*tokens[1]!='0') { ok=0; printf("undef'd symbol %s in line %d\n",tokens[1],sourceline); } } for(i=1;i<256;i*=2) { if(symboladdress&i) fhe_encrypt(cipher,pk,1); else fhe_encrypt(cipher,pk,0); gmp_fprintf(w,"%Zd\n",cipher); } continue; } if(!strcmp(tokens[0],"INITPC")) { search=findsymbol(symbols,tokens[1]); if(search!=NULL) { symboladdress=search->i; } else { symboladdress=atoi(tokens[1]); if(symboladdress==0&&*tokens[1]!='0') { ok=0; printf("undef'd symbol %s in line %d\n",tokens[1],sourceline); } } for(i=1;i<256;i*=2) { if(symboladdress&i) fhe_encrypt(cipher,pk,1); else fhe_encrypt(cipher,pk,0); gmp_fprintf(w,"%Zd\n",cipher); } continue; } label=""; opcode=""; operand=""; if(line0==' '||line0=='\t') { opcode=tokens[0]; if(numtokens==2) operand=tokens[1]; } else { label=tokens[0]; opcode=tokens[1]; if(numtokens>2) operand=tokens[2]; } cmd=0; if(!strcmp(opcode,".BD")) cmd=100; if(!strcmp(opcode,"STa")) cmd=15; if(!strcmp(opcode,"L")) cmd=14; if(!strcmp(opcode,"ROL")) cmd=13; if(!strcmp(opcode,"ROR")) cmd=12; if(!strncmp(opcode,"ADD",3)) cmd=11; if(!strcmp(opcode,"CLC")) cmd=10; if(!strcmp(opcode,"SEC")) cmd=9; if(!strncmp(opcode,"XOR",3)) cmd=8; if(!strncmp(opcode,"AND",3)) cmd=7; if(!strncmp(opcode,"OR",2)) cmd=6; if(!strcmp(opcode,"BEQ")) cmd=5; if(!strcmp(opcode,"J")) cmd=4; if(!strcmp(opcode,"La")) cmd=3; if(!strcmp(opcode,"BMI")) cmd=2; if(!strncmp(opcode,"CMP",3)) cmd=1; if(opcode[strlen(opcode)-1]=='a') cmd+=16; if(*operand==0) operand="0"; search=findsymbol(symbols,operand); if(search!=NULL) { symboladdress=search->i; } else { symboladdress=atoi(operand); if(symboladdress==0&&*operand!='0'&&cmd<100) { ok=0; printf("undef'd symbol %s in line %d\n",operand,sourceline); } } //printf("%s,%s,%s (%d)\n",*label?label:"-",opcode,operand,symboladdress); //System.out.println(label+","+opcode+","+operand+"("+lookup+")"); //int[] operation=null; /* operation=Function.encode(5, cmd); int[] argument=Function.encode(8, Integer.parseInt(lookup!=null?lookup:operand)); for(int i=0;i<8;i++) { System.out.print(hex(argument[i])+" "); w.write(hex(argument[i])+" "); } for(int i=0;i<5;i++) { System.out.print(hex(operation[i])+" "); w.write(hex(operation[i])+" "); } System.out.println("\t\t"+line); w.write("\n"); */ //printf("%d %d -> ",cmd,symboladdress); if(cmd<100) { for(i=1;i<256;i*=2) { if(symboladdress&i) fhe_encrypt(cipher,pk,1); else fhe_encrypt(cipher,pk,0); gmp_fprintf(w,"%Zd\n",cipher); } for(i=1;i<32;i*=2) { if(cmd&i) fhe_encrypt(cipher,pk,1); else fhe_encrypt(cipher,pk,0); gmp_fprintf(w,"%Zd\n",cipher); } } else { if(cmd==100) //.BD binary data { if(strlen(operand)!=13) { printf("binary dataword length mismatch in line %d\n",sourceline); } for(i=0;i<13;i++) { if(operand[i]!='0'&&operand[i]!='1') { printf("binary dataword syntax error in line %d\n",sourceline); } if(operand[i]=='0') fhe_encrypt(cipher,pk,0); else fhe_encrypt(cipher,pk,1); gmp_fprintf(w,"%Zd\n",cipher); } } } //printf(".\n"); } printf("---- reference table start ----\n"); printlist(symbols); printf("---- reference table end ----\n"); //XXX fclose(w); fclose(r); freelist(symbols); fhe_pk_clear(pk); mpz_clear(cipher); printf("%s\n",ok?"ok":"errors"); return 0; }
int main (int argc, char **argv) { gmp_randstate_ptr rands; mp_ptr ap, rp, pp, scratch; int count = COUNT; unsigned i; TMP_DECL; TMP_MARK; if (argc > 1) { char *end; count = strtol (argv[1], &end, 0); if (*end || count <= 0) { fprintf (stderr, "Invalid test count: %s.\n", argv[1]); return 1; } } tests_start (); rands = RANDS; ap = TMP_ALLOC_LIMBS (MAX_LIMBS); rp = TMP_ALLOC_LIMBS (MAX_LIMBS); pp = TMP_ALLOC_LIMBS (MAX_LIMBS); scratch = TMP_ALLOC_LIMBS (3*MAX_LIMBS); /* For mpn_powlo */ for (i = 0; i < count; i++) { mp_size_t n; mp_limb_t k; int c; n = 1 + gmp_urandomm_ui (rands, MAX_LIMBS); if (i & 1) mpn_random2 (ap, n); else mpn_random (ap, n); ap[0] |= 1; if (i < 100) k = 3 + 2*i; else { mpn_random (&k, 1); if (k < 3) k = 3; else k |= 1; } mpn_broot (rp, ap, n, k); mpn_powlo (pp, rp, &k, 1, n, scratch); MPN_CMP (c, ap, pp, n); if (c != 0) { gmp_fprintf (stderr, "mpn_broot returned bad result: %u limbs\n", (unsigned) n); gmp_fprintf (stderr, "k = %Mx\n", k); gmp_fprintf (stderr, "a = %Nx\n", ap, n); gmp_fprintf (stderr, "r = %Nx\n", rp, n); gmp_fprintf (stderr, "r^n = %Nx\n", pp, n); abort (); } } TMP_FREE; tests_end (); return 0; }
int main(int argc, char * * argv) { int k; mpf_t one; mpf_t three; mpf_t negone; mpf_t two; mpf_t negthird; mpf_t sr12; mpf_t num; mpf_t denom; mpf_t tmp; FILE *f; if (argc < 2) { printf("%s <prec> [file]\n", argv[0]); return 1; } PREC = atol(argv[1]); if (argc > 2) f = fopen(argv[2], "w"); mpf_set_default_prec(4 * PREC); mpf_init(pi); mpf_init(one); mpf_init(two); mpf_init(three); mpf_init(negone); mpf_init(negthird); mpf_init(sr12); mpf_init(num); mpf_init(denom); mpf_init(tmp); mpf_set_ui(pi, 0); mpf_set_ui(one, 1); mpf_set_ui(two, 2); mpf_set_ui(three, 3); mpf_set_si(negone, -1); mpf_sqrt_ui(sr12, 12); mpf_div(negthird, negone, three); mpf_set_ui(num, 1); mpf_set_ui(denom, 1); printf("Alloc\r"); fflush(stdout); for (k = 0; k < PREC; k++) { mpf_pow_ui(num, negthird, k); mpf_set_ui(denom, 2*k + 1); mpf_div(tmp, num, denom); mpf_add(pi, pi, tmp); //if (k % 50 == 0) { double progress = k; progress /= PREC; progress *= 100; printf("\rProgress: %.2lf\r", progress); fflush(stdout); } } mpf_mul(pi, pi, sr12); gmp_printf("%.*Ff\n", PREC, pi); if (f) gmp_fprintf(f, "%.*Ff", PREC, pi); }
/* * Implementing second part of secure MP protocol. This function reads the input file containing the two encrypted products seperated by a newline, decrypts them, multiplies them and again encrypts their * product and writes to the output file. If the other party has n documents in its collection, this should be called n times by the native Jav API i.e. this acts per remotely-based collection document. * */ int read_decrypt_mul_encrypt_write_encrypted_rand_prod( const char * input_interm_prods_file_name, const char * output_encrypt_rand_prod_file_name, const char * key_file_name) { mpz_t tfidf_prod1; //holds input randomized, encrypted tfidf vector products mpz_t coord_prod2; //holds input randomized, encrypted binary vector products mpz_t out_enc_ran_prod; //holds the encrypted product of tfidf_prod1, coord_prod2 FILE *input_interm_prods_file=NULL, *output_encrypt_rand_prod_file=NULL; input_interm_prods_file = fopen(input_interm_prods_file_name, "r"); output_encrypt_rand_prod_file = fopen(output_encrypt_rand_prod_file_name, "w"); strncpy(g_key_file_name, key_file_name, sizeof(g_key_file_name)); //Initialize mpz_init(tfidf_prod1); mpz_init(coord_prod2); mpz_init(out_enc_ran_prod); init(); //variables are set to 0 //init(); //check if files are opened properly if (input_interm_prods_file == NULL) { printf("\n%s", "Error: open %s!", input_interm_prods_file_name); return -2; } if (output_encrypt_rand_prod_file == NULL) { printf("\n%s", "Error: open %s!", output_encrypt_rand_prod_file_name); return -2; } //Read the product values //File structure can be found in the Java function in which it is written i.e. //<Class_name>:<function_name> :: DocSimSecApp:acceptIntermValues() gmp_fscanf(input_interm_prods_file, "%Zd", tfidf_prod1); gmp_fscanf(input_interm_prods_file, "%Zd\n", coord_prod2); gmp_fprintf(stderr, "TFIDF Product read = %Zd\n\n", tfidf_prod1); gmp_fprintf(stderr, "Co-ord Product read = %Zd\n\n", coord_prod2); //Decrypt both decrypt(tfidf_prod1); decrypt(coord_prod2); gmp_fprintf(stderr, "After decrypting, TFIDF Product read = %Zd\n\n", tfidf_prod1); gmp_fprintf(stderr, "After decrypting, Co-ord Product read = %Zd\n\n", coord_prod2); //Multiply both mpz_mul(out_enc_ran_prod, tfidf_prod1, coord_prod2); mpz_mod(out_enc_ran_prod, out_enc_ran_prod, n); gmp_fprintf(stderr, "Unencrypted Product = %Zd\n\n", out_enc_ran_prod); //note obtained product is not encrypted, hence, encrypting it encrypt_big_num(out_enc_ran_prod, out_enc_ran_prod); gmp_fprintf(stderr, "Encrypted Product = %Zd\n\n", out_enc_ran_prod); gmp_fprintf(output_encrypt_rand_prod_file, "%Zd", out_enc_ran_prod); fflush(output_encrypt_rand_prod_file); fclose(input_interm_prods_file); fclose(output_encrypt_rand_prod_file); mpz_clear(tfidf_prod1); mpz_clear(coord_prod2); mpz_clear(out_enc_ran_prod); clear(); return 0; }
void test_main (void) { gmp_randstate_t state; mp_limb_t a[MAX_ECC_SIZE]; mp_limb_t ai[MAX_ECC_SIZE]; mp_limb_t ref[MAX_ECC_SIZE]; mp_limb_t scratch[ECC_MODINV_ITCH (MAX_ECC_SIZE)]; unsigned i; mpz_t r; gmp_randinit_default (state); mpz_init (r); for (i = 0; ecc_curves[i]; i++) { const struct ecc_curve *ecc = ecc_curves[i]; unsigned j; for (j = 0; j < COUNT; j++) { if (j & 1) mpz_rrandomb (r, state, ecc->size * GMP_NUMB_BITS); else mpz_urandomb (r, state, ecc->size * GMP_NUMB_BITS); mpz_limbs_copy (a, r, ecc->size); if (!ref_modinv (ref, a, ecc->p, ecc->size)) { if (verbose) fprintf (stderr, "Test %u (bit size %u) not invertible.\n", j, ecc->bit_size); continue; } ecc_modp_inv (ecc, ai, a, scratch); if (mpn_cmp (ref, ai, ecc->size)) { fprintf (stderr, "ecc_modp_inv failed (test %u, bit size %u):\n", j, ecc->bit_size); gmp_fprintf (stderr, "a = %Zx\n" "p = %Nx\n" "t = %Nx (bad)\n" "r = %Nx\n", r, ecc->p, ecc->size, ai, ecc->size, ref, ecc->size); abort (); } mpz_limbs_copy (a, r, ecc->size); if (!ref_modinv (ref, a, ecc->q, ecc->size)) { fprintf (stderr, "Test %u (bit size %u) not invertible.\n", j, ecc->bit_size); continue; } ecc_modq_inv (ecc, ai, a, scratch); if (mpn_cmp (ref, ai, ecc->size)) { fprintf (stderr, "ecc_modq_inv failed (test %u, bit size %u):\n", j, ecc->bit_size); gmp_fprintf (stderr, "a = %Zx\n" "p = %Nx\n" "t = %Nx (bad)\n" "r = %Nx\n", r, ecc->p, ecc->size, ai, ecc->size, ref, ecc->size); abort (); } } } gmp_randclear (state); mpz_clear (r); }
static void pdr_stride_in_loop (mpz_t stride, graphite_dim_t depth, poly_dr_p pdr) { poly_bb_p pbb = PDR_PBB (pdr); isl_map *map; isl_set *set; isl_aff *aff; isl_space *dc; isl_constraint *lma, *c; isl_val *islstride; graphite_dim_t time_depth; unsigned offset, nt; unsigned i; /* XXX isl rewrite following comments. */ /* Builds a partial difference equations and inserts them into pointset powerset polyhedron P. Polyhedron is assumed to have the format: T|I|T'|I'|G|S|S'|l1|l2. TIME_DEPTH is the time dimension w.r.t. which we are differentiating. OFFSET represents the number of dimensions between columns t_{time_depth} and t'_{time_depth}. DIM_SCTR is the number of scattering dimensions. It is essentially the dimensionality of the T vector. The following equations are inserted into the polyhedron P: | t_1 = t_1' | ... | t_{time_depth-1} = t'_{time_depth-1} | t_{time_depth} = t'_{time_depth} + 1 | t_{time_depth+1} = t'_{time_depth + 1} | ... | t_{dim_sctr} = t'_{dim_sctr}. */ /* Add the equality: t_{time_depth} = t'_{time_depth} + 1. This is the core part of this alogrithm, since this constraint asks for the memory access stride (difference) between two consecutive points in time dimensions. */ /* Add equalities: | t1 = t1' | ... | t_{time_depth-1} = t'_{time_depth-1} | t_{time_depth+1} = t'_{time_depth+1} | ... | t_{dim_sctr} = t'_{dim_sctr} This means that all the time dimensions are equal except for time_depth, where the constraint is t_{depth} = t'_{depth} + 1 step. More to this: we should be careful not to add equalities to the 'coupled' dimensions, which happens when the one dimension is stripmined dimension, and the other dimension corresponds to the point loop inside stripmined dimension. */ /* pdr->accesses: [P1..nb_param,I1..nb_domain]->[a,S1..nb_subscript] ??? [P] not used for PDRs? pdr->extent: [a,S1..nb_subscript] pbb->domain: [P1..nb_param,I1..nb_domain] pbb->transformed: [P1..nb_param,I1..nb_domain]->[T1..Tnb_sctr] [T] includes local vars (currently unused) First we create [P,I] -> [T,a,S]. */ map = isl_map_flat_range_product (isl_map_copy (pbb->transformed), isl_map_copy (pdr->accesses)); /* Add a dimension for L: [P,I] -> [T,a,S,L].*/ map = isl_map_add_dims (map, isl_dim_out, 1); /* Build a constraint for "lma[S] - L == 0", effectively calculating L in terms of subscripts. */ lma = build_linearized_memory_access (map, pdr); /* And add it to the map, so we now have: [P,I] -> [T,a,S,L] : lma([S]) == L. */ map = isl_map_add_constraint (map, lma); /* Then we create [P,I,P',I'] -> [T,a,S,L,T',a',S',L']. */ map = isl_map_flat_product (map, isl_map_copy (map)); /* Now add the equality T[time_depth] == T'[time_depth]+1. This will force L' to be the linear address at T[time_depth] + 1. */ time_depth = psct_dynamic_dim (pbb, depth); /* Length of [a,S] plus [L] ... */ offset = 1 + isl_map_dim (pdr->accesses, isl_dim_out); /* ... plus [T]. */ offset += isl_map_dim (pbb->transformed, isl_dim_out); c = isl_equality_alloc (isl_local_space_from_space (isl_map_get_space (map))); c = isl_constraint_set_coefficient_si (c, isl_dim_out, time_depth, 1); c = isl_constraint_set_coefficient_si (c, isl_dim_out, offset + time_depth, -1); c = isl_constraint_set_constant_si (c, 1); map = isl_map_add_constraint (map, c); /* Now we equate most of the T/T' elements (making PITaSL nearly the same is (PITaSL)', except for one dimension, namely for 'depth' (an index into [I]), after translating to index into [T]. Take care to not produce an empty map, which indicates we wanted to equate two dimensions that are already coupled via the above time_depth dimension. Happens with strip mining where several scatter dimension are interdependend. */ /* Length of [T]. */ nt = pbb_nb_scattering_transform (pbb) + pbb_nb_local_vars (pbb); for (i = 0; i < nt; i++) if (i != time_depth) { isl_map *temp = isl_map_equate (isl_map_copy (map), isl_dim_out, i, isl_dim_out, offset + i); if (isl_map_is_empty (temp)) isl_map_free (temp); else { isl_map_free (map); map = temp; } } /* Now maximize the expression L' - L. */ set = isl_map_range (map); dc = isl_set_get_space (set); aff = isl_aff_zero_on_domain (isl_local_space_from_space (dc)); aff = isl_aff_set_coefficient_si (aff, isl_dim_in, offset - 1, -1); aff = isl_aff_set_coefficient_si (aff, isl_dim_in, offset + offset - 1, 1); islstride = isl_set_max_val (set, aff); isl_val_get_num_gmp (islstride, stride); isl_val_free (islstride); isl_aff_free (aff); isl_set_free (set); if (dump_file && (dump_flags & TDF_DETAILS)) { gmp_fprintf (dump_file, "\nStride in BB_%d, DR_%d, depth %d: %Zd ", pbb_index (pbb), PDR_ID (pdr), (int) depth, stride); } }
int test_sieve(fact_obj_t* fobj, void* args, int njobs, int are_files) /* if(are_files), then treat args as a char** list of (external) polys * else args is a nfs_job_t* array of job structs * the latter is preferred */ // @ben: the idea is a new yafu function "testsieve(n, ...)" where args are // an arbitrary list of files of external polys { uint32 count; int i, minscore_id = 0; double* score = (double*)malloc(njobs * sizeof(double)); double t_time, min_score = 999999999.; char orig_name[GSTR_MAXSIZE]; // don't clobber fobj->nfs_obj.job_infile char time[80]; uint32 spq_range = 2000, actual_range; FILE *flog; char** filenames; // args nfs_job_t* jobs; // args struct timeval stop, stop2; // stop time of this job struct timeval start, start2; // start time of this job TIME_DIFF * difference; if( score == NULL ) { printf("Couldn't alloc memory!\n"); exit(-1); } // check to make sure we can find ggnfs sievers if (check_for_sievers(fobj, 0) == 1) { printf("test: can't find ggnfs lattice sievers - aborting test sieving\n"); return -1; } gettimeofday(&start2, NULL); strcpy(orig_name, fobj->nfs_obj.job_infile); // necessary because parse/fill_job_file() get filename from fobj if( are_files ) { // read files into job structs (get fblim) filenames = (char**) args; jobs = (nfs_job_t*)malloc(njobs * sizeof(nfs_job_t)); if( jobs == NULL ) { printf("Couldn't alloc memory!\n"); exit(-1); } memset(jobs, 0, njobs*sizeof(nfs_job_t)); for(i = 0; i < njobs; i++) { uint32 missing_params; strcpy(fobj->nfs_obj.job_infile, filenames[i]); missing_params = parse_job_file(fobj, jobs+i); // get fblim get_ggnfs_params(fobj, jobs+i); // get siever if( missing_params ) { if( VFLAG >= 0 ) printf("test: warning: \"%s\" is missing some paramters (%#X). filling them.\n", filenames[i], missing_params); fill_job_file(fobj, jobs+i, missing_params); } // adjust a/rlim, lpbr/a, and mfbr/a if advantageous skew_snfs_params(fobj, jobs+i); } } else { // create poly files jobs = (nfs_job_t *) args; filenames = (char**)malloc(njobs*sizeof(char*)); if( !filenames ) { printf("malloc derped it up!\n"); exit(-1); } for(i = 0; i < njobs; i++) { FILE* out; filenames[i] = (char*)malloc(GSTR_MAXSIZE); if( !filenames[i] ) { printf("malloc failed\n"); exit(-1); } sprintf(filenames[i], "test-sieve-%d.poly", i); out = fopen(filenames[i], "w"); if( !out ) { printf("test: couldn't open %s for writing, aborting test sieve\n", filenames[i]); return -1; } if( jobs[i].snfs ) print_snfs(jobs[i].snfs, out); else { gmp_fprintf(out, "n: %Zd\n", fobj->nfs_obj.gmp_n); print_poly(jobs[i].poly, out); } fclose(out); strcpy(fobj->nfs_obj.job_infile, filenames[i]); fill_job_file(fobj, jobs+i, PARAM_FLAG_ALL); } // that seems like a lot more code than it should be } strcpy(fobj->nfs_obj.job_infile, orig_name); // now we can get to the actual testing for(i = 0; i < njobs; i++) { char syscmd[GSTR_MAXSIZE], tmpbuf[GSTR_MAXSIZE], side[32]; FILE* in; // should probably scale the range of special-q to test based // on input difficulty, but not sure how to do that easily... if( jobs[i].poly->side == RATIONAL_SPQ) { sprintf(side, "rational"); jobs[i].startq = jobs[i].rlim; // no reason to test sieve *inside* the fb } else { sprintf(side, "algebraic"); jobs[i].startq = jobs[i].alim; // ditto } flog = fopen(fobj->flogname, "a"); //create the afb/rfb - we don't want the time it takes to do this to //pollute the sieve timings sprintf(syscmd, "%s -b %s -k -c 0 -F", jobs[i].sievername, filenames[i]); if (VFLAG > 0) printf("\ntest: generating factor bases\n"); gettimeofday(&start, NULL); system(syscmd); gettimeofday(&stop, NULL); difference = my_difftime (&start, &stop); t_time = ((double)difference->secs + (double)difference->usecs / 1000000); free(difference); if (VFLAG > 0) printf("test: fb generation took %6.4f seconds\n", t_time); logprint(flog, "test: fb generation took %6.4f seconds\n", t_time); MySleep(.1); //start the test sprintf(syscmd,"%s%s -%c %s -f %u -c %u -o %s.out", jobs[i].sievername, VFLAG>0?" -v":"", side[0], filenames[i], jobs[i].startq, spq_range, filenames[i]); if (VFLAG > 0) printf("test: commencing test sieving of polynomial %d on the %s side over range %u-%u\n", i, side, jobs[i].startq, jobs[i].startq + spq_range); logprint(flog, "test: commencing test sieving of polynomial %d on the %s side over range %u-%u\n", i, side, jobs[i].startq, jobs[i].startq + spq_range); print_job(&jobs[i], flog); fclose(flog); gettimeofday(&start, NULL); system(syscmd); gettimeofday(&stop, NULL); difference = my_difftime (&start, &stop); t_time = ((double)difference->secs + (double)difference->usecs / 1000000); free(difference); //count relations sprintf(tmpbuf, "%s.out", filenames[i]); in = fopen(tmpbuf, "r"); actual_range = 0; count = 0; if( !in ) { score[i] = 999999999.; //est = 7*365*24*3600; // 7 years seems like a nice round number } else { // scan the data file and // 1) count the relations // 2) save the last four relations to a buffer in order to extract the last processed // special-q. // we need both 1) and 2) to compute yield correctly. char **lines, *ptr, tmp[GSTR_MAXSIZE]; int line; int j; lines = (char **)malloc(4 * sizeof(char *)); for (j=0; j < 4; j++) lines[j] = (char *)malloc(GSTR_MAXSIZE * sizeof(char)); line = 0; count = 0; while (1) { // read a line into the next position of the circular buffer ptr = fgets(tmp, GSTR_MAXSIZE, in); if (ptr == NULL) break; // quick check that it might be a valid line if (strlen(tmp) > 30) { // wrap if (++line > 3) line = 0; // then copy strcpy(lines[line], tmp); } count++; } fclose(in); line = get_spq(lines, line, fobj); actual_range = line - jobs[i].startq; if (VFLAG > 0) printf("test: found %u relations in a range of %u special-q\n", count, actual_range); if (actual_range > spq_range) actual_range = spq_range; for (j=0; j < 4; j++) free(lines[j]); free(lines); score[i] = t_time / count; // use estimated sieving time to rank, not sec/rel, since the latter // is a function of parameterization and therefore not directly comparable // to each other. score[i] = (score[i] * jobs[i].min_rels * 1.25) / THREADS; // be conservative about estimates } flog = fopen(fobj->flogname, "a"); if( score[i] < min_score ) { minscore_id = i; min_score = score[i]; if (VFLAG > 0) printf("test: new best estimated total sieving time = %s (with %d threads)\n", time_from_secs(time, (unsigned long)score[i]), THREADS); logprint(flog, "test: new best estimated total sieving time = %s (with %d threads)\n", time_from_secs(time, (unsigned long)score[i]), THREADS); // edit lbpr/a depending on test results. we target something around 2 rels/Q. // could also change siever version in more extreme cases. if (count > 4*actual_range) { if (VFLAG > 0) printf("test: yield greater than 4x/spq, reducing lpbr/lpba\n"); jobs[i].lpba--; jobs[i].lpbr--; jobs[i].mfba -= 2; jobs[i].mfbr -= 2; } if (count > 8*actual_range) { char *pos; int siever; pos = strstr(jobs[i].sievername, "gnfs-lasieve4I"); siever = (pos[14] - 48) * 10 + (pos[15] - 48); if (VFLAG > 0) printf("test: yield greater than 8x/spq, reducing siever version\n"); switch (siever) { case 11: if (VFLAG > 0) printf("test: siever version cannot be decreased further\n"); jobs[i].snfs->siever = 11; break; case 12: pos[15] = '1'; jobs[i].snfs->siever = 11; break; case 13: pos[15] = '2'; jobs[i].snfs->siever = 12; break; case 14: pos[15] = '3'; jobs[i].snfs->siever = 13; break; case 15: pos[15] = '4'; jobs[i].snfs->siever = 14; break; case 16: pos[15] = '5'; jobs[i].snfs->siever = 15; break; } } if (count < actual_range) { if (VFLAG > 0) printf("test: yield less than 1x/spq, increasing lpbr/lpba\n"); jobs[i].lpba++; jobs[i].lpbr++; jobs[i].mfba += 2; jobs[i].mfbr += 2; } if (count < (actual_range/2)) { char *pos; int siever; pos = strstr(jobs[i].sievername, "gnfs-lasieve4I"); siever = (pos[14] - 48) * 10 + (pos[15] - 48); if (VFLAG > 0) printf("test: yield less than 1x/2*spq, increasing siever version\n"); switch (siever) { case 16: if (VFLAG > 0) printf("test: siever version cannot be increased further\n"); jobs[i].snfs->siever = 16; break; case 15: pos[15] = '6'; jobs[i].snfs->siever = 16; break; case 14: pos[15] = '5'; jobs[i].snfs->siever = 15; break; case 13: pos[15] = '4'; jobs[i].snfs->siever = 14; break; case 12: pos[15] = '3'; jobs[i].snfs->siever = 13; break; case 11: pos[15] = '2'; jobs[i].snfs->siever = 12; break; } } } else { if (VFLAG > 0) printf("test: estimated total sieving time = %s (with %d threads)\n", time_from_secs(time, (unsigned long)score[i]), THREADS); logprint(flog, "test: estimated total sieving time = %s (with %d threads)\n", time_from_secs(time, (unsigned long)score[i]), THREADS); } fclose(flog); remove(tmpbuf); // clean up after ourselves sprintf(tmpbuf, "%s", filenames[i]); remove(tmpbuf); sprintf(tmpbuf, "%s.afb.0", filenames[i]); remove(tmpbuf); } // clean up memory allocated if( are_files ) { for(i = 0; i < njobs; i++) { mpz_polys_free(jobs[i].poly); free(jobs[i].poly); } free(jobs); } else { for(i = 0; i < njobs; i++) free(filenames[i]); free(filenames); } flog = fopen(fobj->flogname, "a"); gettimeofday(&stop2, NULL); difference = my_difftime (&start2, &stop2); t_time = ((double)difference->secs + (double)difference->usecs / 1000000); free(difference); if (VFLAG > 0) printf("test: test sieving took %1.2f seconds\n", t_time); logprint(flog, "test: test sieving took %1.2f seconds\n", t_time); return minscore_id; }
int main(int argc, char *argv[]) { DIR *d; FILE *fpub, *fciph, *fplain, *fprod, *fkey; paillier_pubkey_t *pub; paillier_plaintext_t *plain, *plain_sum, *plain_temp; paillier_prvkey_t *priv; paillier_get_rand_t get_rand; paillier_ciphertext_t *cipher, *cipher_prod, *cipher_total; int count = 0, count1=0, val = 163000, no_of_copies = 10; long int key_int, key_int1, key_rnd; struct dirent *dir; char* len; mpz_t rndKey, randNum, rnd,rnd_sum, rndno, sum, pl_sum; /* Hold our random numbers */ mpz_t rndBnd; /* Bound for mpz_urandomm */ mpz_t key, key1; //key for PRF mpz_t plain_total, plain_nomod; gmp_randstate_t gmpRandState, gmpRandState1, gmpRandState2; /* Random generator state object */ mpz_init(sum); mpz_init(pl_sum); mpz_init(rnd); mpz_init(rndno); mpz_init(rndBnd); mpz_init(randNum); mpz_init(key); mpz_init(key1); mpz_init(rnd_sum); mpz_init(plain_total); mpz_init(rnd); mpz_init(rndKey); mpz_init(plain_nomod); mpz_set_ui(plain_total, 0); plain = (paillier_plaintext_t*) malloc(sizeof(paillier_plaintext_t)); plain_sum = (paillier_plaintext_t*) malloc(sizeof(paillier_plaintext_t)); plain_temp = (paillier_plaintext_t*) malloc(sizeof(paillier_plaintext_t)); cipher_prod = (paillier_ciphertext_t*) malloc(sizeof(paillier_ciphertext_t)); cipher_total = (paillier_ciphertext_t*) malloc(sizeof(paillier_ciphertext_t)); cipher = (paillier_ciphertext_t*) malloc(sizeof(paillier_ciphertext_t)); len = (char *)malloc(2048*sizeof(char)); //mpz_init(cipher_prod->c); mpz_init(cipher_total->c); mpz_set_ui(rnd_sum, 0); mpz_init_set_str(cipher_prod->c, "1", 10); mpz_init_set_str(cipher_total->c, "1", 10); mpz_init_set_str(plain_sum->m, "0", 10); // printf("\nloading pailler keys"); if((fpub = fopen("pub.txt", "r"))) { pub = (paillier_pubkey_t*) malloc(sizeof(paillier_pubkey_t)); priv = (paillier_prvkey_t*) malloc(sizeof(paillier_prvkey_t)); mpz_init(pub->n_squared); mpz_init(pub->n); fgets(len, 1000, fpub); mpz_init_set_str(pub->p, len, 10); fgets(len, 1000, fpub); mpz_init_set_str(pub->q, len, 10); fgets(len, 1000, fpub); mpz_init_set_str(pub->n_plusone, len, 10); //printf("value of nplusone : \n"); //mpz_out_str(stdout, 10, pub->n_plusone); paillier_keygen(&pub, &priv, get_rand, 0); pub->bits = mpz_sizeinbase(pub->n, 2); fclose(fpub); } gmp_randinit_default(gmpRandState); mpz_set_str(rndBnd, "163000", 10); mpz_set_ui(rndKey, time(NULL)); gmp_randseed(gmpRandState, rndKey); fkey = fopen("prf_key.txt", "w"); mpz_urandomm(rndno, gmpRandState, pub->n); mpz_set(key, rndno); element_fprintf(fkey, "%Zd\n", key); mpz_urandomm(rndno, gmpRandState, pub->n); mpz_set(key1, rndno); element_fprintf(fkey, "%Zd", key1); fclose(fkey); gmp_randseed(gmpRandState, key); //mpz_out_str(stdout, 10, rnd); //****Opening files to read files and encrypt***** int i, j; mpz_t rand_val[val], rand_init[no_of_copies], mpz_result[no_of_copies]; char fileName[1000], file[1000]; //strcpy(fileName, "./cipher/copy3/output"); mpz_set_str(sum, "0", 10); mpz_set_str(pl_sum, "0", 10); for(j =0; j < no_of_copies; j++) { mpz_init(rand_init[j]); mpz_urandomm(rand_init[j], gmpRandState, pub->n); mpz_add(sum, sum, rand_init[j]); // mpz_mod(sum, sum, pub->n); //printf("\n 1st rand \n"); //mpz_out_str(stdout, 10, rand_init[j]); } // printf("\nsum\n"); // mpz_out_str(stdout, 10, sum); mpz_set_str(pl_sum, "0", 10); gmp_randseed(gmpRandState, key1); for(j =0; j < no_of_copies; j++) { mpz_set_ui(cipher_prod->c, 1); for(i = 0; i < val; i++) { sprintf(fileName, "./cipher/copy%d/output", (j+1)); if(j == 0) { do mpz_urandomm(randNum, gmpRandState, rndBnd); while(mpz_cmp_ui(randNum,0) ==0); mpz_init(rand_val[i]); mpz_set(rand_val[i], randNum); //printf("\n2ndrand\n"); //mpz_out_str(stdout, 10, randNum); // printf("random\n"); // mpz_out_str(stdout, 10, rand_val[i]); } else { mpz_set(randNum, rand_val[i]); } // sprintf(num, "output%d.txt", (j+1)); mpz_get_str(file, 10, randNum); strcat(fileName, file); strcat(fileName,".txt"); count = 0; // printf("\n%s", fileName); //mpz_out_str(stdout, 10, randNum); if(!(fciph = fopen(fileName, "r"))) { printf("\n not able to read %s", fileName); // fputs("not possible to read file!\n", stderr); } else { fgets(len, 1000, fciph); mpz_init_set_str(cipher->c, len, 10); //if(strstr(dir->d_name, "output") != NULL) //{ // printf("\ncipher\n"); //mpz_out_str(stdout, 10, cipher->c); paillier_mul(pub, cipher_prod, cipher_prod, cipher); // printf("\ncipher after product\n"); //mpz_out_str(stdout, 10, cipher_prod->c); //} fclose(fciph); } if(j == 0) { strcpy(fileName, "./split/output"); strcat(fileName, file); strcat(fileName,".txt"); if(!(fplain = fopen(fileName, "r"))) { printf("\n not read %s", fileName); count1++; } else { fgets(len, 1000, fplain); // printf("\npleain sum\n"); // mpz_out_str(stdout, 10, plain_sum->m); mpz_init_set_str(plain->m, len, 10); // if(strstr(dir->d_name, "output") != NULL) //{ mpz_add(plain_sum->m, plain_sum->m, plain->m); //mpz_mod(pla in_sum->m, plain_sum->m, pub->n); //} fclose(fplain); } } } mpz_powm(cipher_prod->c, cipher_prod->c, rand_init[j], pub->n_squared); paillier_mul(pub, cipher_total, cipher_total, cipher_prod); mpz_mul(plain_temp->m, plain_sum->m, rand_init[j]); mpz_add(plain_total, plain_total, plain_temp->m); mpz_mod(plain_total, plain_total, pub->n); } plain = paillier_dec(plain, pub, priv, cipher_total); printf("\n decrypt \n"); mpz_out_str(stdout, 10, plain->m); // printf("\n plain total \n"); //mpz_out_str(stdout, 10, plain_total); printf("\n plain text total\n"); mpz_out_str(stdout, 10, plain_sum->m); mpz_mul(pl_sum, plain_sum->m, sum); mpz_mul(pl_sum, pl_sum, pub->n); mpz_mul(pl_sum, pl_sum, priv->lambda); // mpz_mod(pl_sum, pl_sum, pub->n); printf("\n plain text * rnd\n"); mpz_out_str(stdout, 10, pl_sum); if((fprod = fopen("result/cipher_result.txt", "w"))) { printf("\nWriting the result to file \n"); gmp_fprintf(fprod, "%Zd\n", cipher_total->c); fclose(fprod); } return 0; }
int main(int argc, char *argv[]) { ///list all the files in the directory/// DIR *d; FILE *fpub, *fpriv, *fciph, *fplain, *ftag, *fpairing, *ftemp, *frand;//, *fp6, *fp7; paillier_pubkey_t *pub; paillier_prvkey_t *priv; paillier_get_rand_t get_rand; paillier_plaintext_t *plain; paillier_ciphertext_t *cipher, *cipher_copy; paillier_tag* tag; mpz_t tag_sig, *rand_prf; gmp_randstate_t rand; char *len; struct stat st= {0}; unsigned char *data; int count=0, count1=0, gbytes, n, no_copies=10; struct dirent *dir; ///pairing parameters pairing_t pairing; //pairing_t p; //printf("setting pairing parameters\n"); //pairing_init_set_str(pairing, param_str); // printf("after pairing setup\n"); element_t g, h, u, temp_pow, test1, test2; element_t public_key, sig; element_t secret_key; ///end of pairing parameters //initialize pairing parametrs pbc_demo_pairing_init(pairing, argc, argv); element_init_G2(g, pairing); element_init_G1(u, pairing); element_init_G1(test1, pairing); element_init_G2(test2, pairing); element_init_G1(temp_pow, pairing); element_init_G2(public_key, pairing); // element_from_hash(h, "hashofmessage", 13); element_init_G1(h, pairing); element_init_G1(sig, pairing); element_init_Zr(secret_key, pairing); //end of pairing parameters initialization //set up pairing parameters //generate system parameters element_random(g); // n = pairing_length_in_bytes_x_only_G1(pairing); // data = pbc_malloc(n); // gbytes = pairing_length_in_bytes_G2(pairing); // printf(" \n g in bytes %d \n", gbytes); // element_printf("system parameter g = %B\n", g); //generate private key element_random(secret_key); //generate u element_random(u); //calculating hash of a file name and mapping it to element in group G1 // element_from_hash(h, "FileName", 8); element_random(h); //element_printf("private key = %B\n", secret_key); //compute corresponding public key element_pow_zn(public_key, g, secret_key); //element_printf("public key = %B\n", public_key); //end of setup tag = (paillier_tag*) malloc(sizeof(paillier_tag)); plain = (paillier_plaintext_t*) malloc(sizeof(paillier_plaintext_t)); cipher = (paillier_ciphertext_t*) malloc(sizeof(paillier_ciphertext_t)); mpz_init(plain->m); mpz_init(tag->t); mpz_init(cipher->c); mpz_init(tag_sig); rand_prf = (mpz_t*) malloc(n*sizeof(mpz_t)); len = (char *)malloc(2048*sizeof(char)); //****paillier key generation**** if(!(fpub = fopen("pub.txt", "r"))) { //fputs("Not able to read public key file!\n", stderr); paillier_keygen(&pub, &priv, get_rand,450); //fclose(fpub); fpub = fopen("pub.txt", "w"); gmp_fprintf(fpub, "%Zd\n", pub->p); gmp_fprintf(fpub, "%Zd\n", pub->q); gmp_fprintf(fpub, "%Zd\n", pub->n_plusone); //***Writing private keys into a file*** fpriv = fopen("priv.txt", "w"); gmp_fprintf(fpriv, "%Zd\n", priv->lambda); gmp_fprintf(fpriv, "%Zd\n", priv->x); fclose(fpriv); //****End of writing private key in a file*** } else { printf("\n in else"); pub = (paillier_pubkey_t*) malloc(sizeof(paillier_pubkey_t)); priv = (paillier_prvkey_t*) malloc(sizeof(paillier_prvkey_t)); mpz_init(pub->n_squared); mpz_init(pub->n); fgets(len, 1000, fpub); mpz_init_set_str(pub->p, len, 10); fgets(len, 1000, fpub); mpz_init_set_str(pub->q, len, 10); fgets(len, 1000, fpub); mpz_init_set_str(pub->n_plusone, len, 10); //printf("value of nplusone : \n"); //mpz_out_str(stdout, 10, pub->n_plusone); paillier_keygen(&pub, &priv, get_rand, 0); pub->bits = mpz_sizeinbase(pub->n, 2); } fclose(fpub); //****end of paillier key generation**** //printf("writing pairing parameters to a file\n"); //writing pairing keys to file fpairing = fopen("pairing.txt", "w"); /* n = pairing_length_in_bytes_compressed_G2(pairing); data = pbc_malloc(n); element_to_bytes_compressed(data, g); element_printf(" decomp g %B\n", g); element_from_bytes_compressed(test2, data); element_printf(" decomp g %B\n", test2); */ //writing compressed g to file element_fprintf(fpairing, "%B\n", g); // element_printf(" g = %B\n", g); /*n = pairing_length_in_bytes_compressed_G1(pairing); data = pbc_malloc(n); element_to_bytes_compressed(data, u); element_printf(" decomp g %B\n", u); element_from_bytes_compressed(test1, data); element_printf(" decomp g %B\n", test1); //writing compressed u to file */ element_fprintf(fpairing, "%B\n", u); //element_printf(" u = %B\n", u); //writing secret key to file element_fprintf(fpairing, "%B\n", secret_key); //element_printf(" sk = %B\n", secret_key); // printf("secret key = %s\n",secret_key); /* n = pairing_length_in_bytes_compressed_G2(pairing); data = pbc_malloc(n); element_to_bytes_compressed(data, public_key); //writing compressed public key to file */ element_fprintf(fpairing, "%B\n", public_key); //element_printf("pk = %B\n", public_key); /* n = pairing_length_in_bytes_compressed_G1(pairing); data = pbc_malloc(n); element_to_bytes_compressed(data, h); element_printf(" decomp g %B\n", h); element_from_bytes_compressed(test1, data); element_printf(" decomp g %B\n", test1); //writing compressed h to file */ element_fprintf(fpairing, "%B\n", h); //element_printf("h = %B\n", h); //writing n to file gmp_fprintf(fpairing, "%Zd\n", pub->n); fclose(fpairing); //end of writing pairing keys to file cipher_copy = (paillier_ciphertext_t*)malloc(no_copies*sizeof(paillier_ciphertext_t)); frand = fopen("rand.txt","w"); int i; init_rand(rand, get_rand, pub->bits / 8 + 1); for(i = 0; i< no_copies; i++) { mpz_init(rand_prf[i]); do mpz_urandomb(rand_prf[i], rand, pub->bits); while( mpz_cmp(rand_prf[i], pub->n) >= 0 ); gmp_fprintf(frand, "%Zd\n", rand_prf[i]); //printf("\nrandom : \n"); //mpz_out_str(stdout, 10, rand_prf[i]); } fclose(frand); //****Opening files to read files and encrypt***** d = opendir("./split"); if (d) { while ((dir = readdir(d)) != NULL) { //printf("%s\n", dir->d_name); char fileName[1000], copy[1000]; strcpy(fileName, "./split/"); strcat(fileName,dir->d_name); //printf("\nfile name %s", fileName); if(!(fplain = fopen(fileName, "r"))) { printf("\n not able to read %s", fileName); // fputs("not possible to read file!\n", stderr); count1++; } else { //printf("\n able to read %s", fileName); fgets(len, 2048, fplain); mpz_init_set_str(plain->m, len, 10); // mpz_out_str(stdout, 10, plain->m); fclose(fplain); //Writing cipher text to files strcpy(fileName, "./cipher/"); //strcat(fileName,dir->d_name); //printf("\nfilename %s",fileName); paillier_enc(tag, cipher_copy, pub,plain, get_rand, no_copies, rand_prf); // mpz_out_str(stdout, 10, tag->t); int j; for(j=0;j < no_copies; j++) { char num[20]; strcpy(copy, fileName); sprintf(num, "copy%d/", (j+1)); // strcat(copy, ); strcat(copy, num); if(stat(copy, &st) == -1) mkdir(copy,0777); strcat(copy,dir->d_name); if(!(fciph = fopen(copy, "w"))) { printf("\nnot able to open file for writing cipher text %s", copy); } else { // printf("\nbefore enc"); gmp_fprintf(fciph, "%Zd\n", cipher_copy[j].c); fclose(fciph); } } //writing tags to files strcpy(fileName, "./tag/"); strcat(fileName,dir->d_name); //printf("\nfilename %s",fileName); if(!(ftag = fopen(fileName, "w"))) { printf("not able to open file for writing tag %s", fileName); } else { element_pow_mpz(temp_pow,u, tag->t); element_mul(temp_pow, temp_pow, h); element_pow_zn(sig, temp_pow, secret_key); element_fprintf(ftag, "%B", sig); fclose(ftag); } } count++; } closedir(d); } printf("\nTotal number of files : %d, unreadable files %d", count, count1); return 0; }
uint64 *sieve_to_depth(uint32 *seed_p, uint32 num_sp, mpz_t lowlimit, mpz_t highlimit, int count, int num_witnesses, uint64 *num_p) { //public interface to a routine which will sieve a range of integers //with the supplied primes and either count or compute the values //that survive. Basically, it is just the sieve, but with no //guareentees that what survives the sieving is prime. The idea is to //remove cheap composites. uint64 retval, i, range, tmpl, tmph; uint64 *values = NULL; mpz_t tmpz; mpz_t *offset; if (mpz_cmp(highlimit, lowlimit) <= 0) { printf("error: lowlimit must be less than highlimit\n"); *num_p = 0; return values; } offset = (mpz_t *)malloc(sizeof(mpz_t)); mpz_init(tmpz); mpz_init(*offset); mpz_set(*offset, lowlimit); mpz_sub(tmpz, highlimit, lowlimit); range = mpz_get_64(tmpz); if (count) { //this needs to be a range of at least 1e6 if (range < 1000000) { //go and get a new range. tmpl = 0; tmph = 1000000; //since this is a small range, we need to //find a bigger range and count them. values = GetPRIMESRange(seed_p, num_sp, offset, tmpl, tmph, &retval); *num_p = 0; //count how many are in the original range of interest for (i = 0; i < retval; i++) { mpz_add_ui(tmpz, *offset, values[i]); if ((mpz_cmp(tmpz, lowlimit) >= 0) && (mpz_cmp(highlimit, tmpz) >= 0)) (*num_p)++; } free(values); values = NULL; } else { //check for really big ranges uint64 maxrange = 100000000000ULL; if (range > maxrange) { uint32 num_ranges = (uint32)(range / maxrange); uint64 remainder = range % maxrange; uint32 j; *num_p = 0; tmpl = 0; tmph = tmpl + maxrange; for (j = 0; j < num_ranges; j++) { *num_p += spSOE(seed_p, num_sp, offset, tmpl, &tmph, 1, NULL); if (VFLAG > 1) printf("so far, found %" PRIu64 " primes\n",*num_p); tmpl += maxrange; tmph = tmpl + maxrange; } if (remainder > 0) { tmph = tmpl + remainder; *num_p += spSOE(seed_p, num_sp, offset, tmpl, &tmph, 1, NULL); } if (VFLAG > 1) printf("so far, found %" PRIu64 " primes\n",*num_p); } else { //we're in a sweet spot already, just get the requested range *num_p = spSOE(seed_p, num_sp, offset, 0, &range, 1, NULL); } } } else { //this needs to be a range of at least 1e6 if (range < 1000000) { //there is slack built into the sieve limit, so go ahead and increase //the size of the interval to make it at least 1e6. tmpl = 0; tmph = tmpl + 1000000; //since this is a small range, we need to //find a bigger range and count them. values = GetPRIMESRange(seed_p, num_sp, offset, tmpl, tmph, &retval); *num_p = 0; for (i = 0; i < retval; i++) { mpz_add_ui(tmpz, *offset, values[i]); if ((mpz_cmp(tmpz, lowlimit) >= 0) && (mpz_cmp(highlimit, tmpz) >= 0)) (*num_p)++; } } else { //we don't need to mess with the requested range, //so GetPRIMESRange will return the requested range directly //and the count will be in NUM_P values = GetPRIMESRange(seed_p, num_sp, offset, 0, range, num_p); } if (num_witnesses > 0) { int pchar = 0; thread_soedata_t *thread_data; //an array of thread data objects uint32 lastid; int j; //allocate thread data structure thread_data = (thread_soedata_t *)malloc(THREADS * sizeof(thread_soedata_t)); // conduct PRP tests on all surviving values if (VFLAG > 0) printf("starting PRP tests with %d witnesses on %" PRIu64 " surviving candidates\n", num_witnesses, *num_p); // start the threads for (i = 0; i < THREADS - 1; i++) start_soe_worker_thread(thread_data + i, 0); start_soe_worker_thread(thread_data + i, 1); range = *num_p / THREADS; lastid = 0; // divvy up the range for (j = 0; j < THREADS; j++) { thread_soedata_t *t = thread_data + j; t->startid = lastid; t->stopid = t->startid + range; lastid = t->stopid; if (VFLAG > 2) printf("thread %d computing PRPs from %u to %u\n", (int)i, t->startid, t->stopid); } // the last one gets any leftover if (thread_data[THREADS-1].stopid != (uint32)*num_p) thread_data[THREADS-1].stopid = (uint32)*num_p; // allocate space for stuff in the threads if (THREADS == 1) { thread_data[0].ddata.primes = values; } else { for (j = 0; j < THREADS; j++) { thread_soedata_t *t = thread_data + j; mpz_init(t->tmpz); mpz_init(t->offset); mpz_init(t->lowlimit); mpz_init(t->highlimit); mpz_set(t->offset, *offset); mpz_set(t->lowlimit, lowlimit); mpz_set(t->highlimit, highlimit); t->current_line = (uint64)num_witnesses; t->ddata.primes = (uint64 *)malloc((t->stopid - t->startid) * sizeof(uint64)); for (i = t->startid; i < t->stopid; i++) t->ddata.primes[i - t->startid] = values[i]; } } // now run with the threads for (j = 0; j < THREADS; j++) { thread_soedata_t *t = thread_data + j; if (j == (THREADS - 1)) { t->linecount = 0; for (i = t->startid; i < t->stopid; i++) { if (((i & 128) == 0) && (VFLAG > 0)) { int k; for (k = 0; k<pchar; k++) printf("\b"); pchar = printf("progress: %d%%",(int)((double)i / (double)(*num_p) * 100.0)); fflush(stdout); } mpz_add_ui(tmpz, *offset, t->ddata.primes[i - t->startid]); if ((mpz_cmp(tmpz, lowlimit) >= 0) && (mpz_cmp(highlimit, tmpz) >= 0)) { if (mpz_probab_prime_p(tmpz, num_witnesses)) t->ddata.primes[t->linecount++] = t->ddata.primes[i - t->startid]; } } } else { t->command = SOE_COMPUTE_PRPS; #if defined(WIN32) || defined(_WIN64) SetEvent(t->run_event); #else pthread_cond_signal(&t->run_cond); pthread_mutex_unlock(&t->run_lock); #endif } } //wait for each thread to finish for (i = 0; i < THREADS; i++) { thread_soedata_t *t = thread_data + i; if (i < (THREADS - 1)) { #if defined(WIN32) || defined(_WIN64) WaitForSingleObject(t->finish_event, INFINITE); #else pthread_mutex_lock(&t->run_lock); while (t->command != SOE_COMMAND_WAIT) pthread_cond_wait(&t->run_cond, &t->run_lock); #endif } } //stop the worker threads for (i=0; i<THREADS - 1; i++) stop_soe_worker_thread(thread_data + i, 0); // combine results and free stuff if (THREADS == 1) { retval = thread_data[0].linecount; } else { retval = 0; for (i=0; i<THREADS; i++) { thread_soedata_t *t = thread_data + i; for (j=0; j < t->linecount; j++) values[retval++] = t->ddata.primes[j]; free(t->ddata.primes); mpz_clear(t->tmpz); mpz_clear(t->offset); mpz_clear(t->lowlimit); mpz_clear(t->highlimit); } } free(thread_data); if (VFLAG > 0) { int k; for (k = 0; k<pchar; k++) printf("\b"); } *num_p = retval; if (VFLAG > 0) printf("found %" PRIu64 " PRPs\n", *num_p); } // now dump the requested range of primes to a file, or the // screen, both, or neither, depending on the state of a couple // global configuration variables if (PRIMES_TO_FILE) { FILE *out; if (num_witnesses > 0) out = fopen("prp_values.dat", "w"); else out = fopen("sieved_values.dat","w"); if (out == NULL) { printf("fopen error: %s\n", strerror(errno)); printf("can't open file for writing\n"); } else { for (i = 0; i < *num_p; i++) { mpz_add_ui(tmpz, *offset, values[i]); if ((mpz_cmp(tmpz, lowlimit) >= 0) && (mpz_cmp(highlimit, tmpz) >= 0)) gmp_fprintf(out,"%Zd\n",tmpz); } fclose(out); } } if (PRIMES_TO_SCREEN) { for (i = 0; i < *num_p; i++) { mpz_add_ui(tmpz, *offset, values[i]); if ((mpz_cmp(tmpz, lowlimit) >= 0) && (mpz_cmp(highlimit, tmpz) >= 0)) gmp_printf("%Zd\n",tmpz); } printf("\n"); } } mpz_clear(tmpz); mpz_clear(*offset); free(offset); return values; }
void test_main (void) { unsigned i; struct knuth_lfib_ctx rctx; struct dsa_signature signature; struct tstring *digest; knuth_lfib_init (&rctx, 4711); dsa_signature_init (&signature); digest = SHEX (/* sha256("abc") */ "BA7816BF 8F01CFEA 414140DE 5DAE2223" "B00361A3 96177A9C B410FF61 F20015AD"); for (i = 0; ecc_curves[i]; i++) { const struct ecc_curve *ecc = ecc_curves[i]; struct ecc_point pub; struct ecc_scalar key; if (verbose) fprintf (stderr, "Curve %d\n", ecc->bit_size); ecc_point_init (&pub, ecc); ecc_scalar_init (&key, ecc); ecdsa_generate_keypair (&pub, &key, &rctx, (nettle_random_func *) knuth_lfib_random); if (verbose) { gmp_fprintf (stderr, "Public key:\nx = %Nx\ny = %Nx\n", pub.p, ecc->size, pub.p + ecc->size, ecc->size); gmp_fprintf (stderr, "Private key: %Nx\n", key.p, ecc->size); } if (!ecc_valid_p (&pub)) die ("ecdsa_generate_keypair produced an invalid point.\n"); ecdsa_sign (&key, &rctx, (nettle_random_func *) knuth_lfib_random, digest->length, digest->data, &signature); if (!ecdsa_verify (&pub, digest->length, digest->data, &signature)) die ("ecdsa_verify failed.\n"); digest->data[3] ^= 17; if (ecdsa_verify (&pub, digest->length, digest->data, &signature)) die ("ecdsa_verify returned success with invalid digest.\n"); digest->data[3] ^= 17; mpz_combit (signature.r, 117); if (ecdsa_verify (&pub, digest->length, digest->data, &signature)) die ("ecdsa_verify returned success with invalid signature.r.\n"); mpz_combit (signature.r, 117); mpz_combit (signature.s, 93); if (ecdsa_verify (&pub, digest->length, digest->data, &signature)) die ("ecdsa_verify returned success with invalid signature.s.\n"); ecc_point_clear (&pub); ecc_scalar_clear (&key); } dsa_signature_clear (&signature); }
int ecpp_test(unsigned long n) { mpz_t a, b, x0, y0, xt, yt, tmp; int z; int is_prime = 0; if (n <= USHRT_MAX) { return sieve_test(n); } mpz_init(a); mpz_init(b); mpz_init(x0); mpz_init(y0); mpz_init(xt); mpz_init(yt); mpz_init(tmp); #ifdef DEBUG gmp_fprintf(stderr, "\nTesting %d with ECPP...\n", n); #endif /* DEBUG */ for (;;) /* keep trying while the curve order factoring fails */ { for (;;) /* keep trying while n divides curve discriminant */ { /* initialise a random point P = (x0, y0) * and a random elliptic curve E(a, b): y^2 = x^3 + a*x + b * with b expressed in terms of (a, x0, y0) so the point lies on the curve */ mpz_set_ui(a, rand() % n); mpz_set_ui(x0, rand() % n); mpz_set_ui(y0, rand() % n); mpz_init(b); mpz_mul(b, y0, y0); mpz_mul(tmp, x0, x0); mpz_submul(b, tmp, x0); mpz_submul(b, a, x0); mpz_mod_ui(b, b, n); #ifdef DEBUG gmp_fprintf(stderr, "\n\tn = %d\n", n); gmp_fprintf(stderr, "\tE: y^2 = x^3 + %Zd * x + %Zd\n", a, b); gmp_fprintf(stderr, "\tP = (%Zd,%Zd,1)\n", x0, y0); #endif /* DEBUG */ /* the discriminant of the curve and n are required to be coprimes * -- if not, then either * A) n divides the discriminant -- a new curve must be generated * B) n is composite and a proper factor is found -- the algorithm can * terminate */ ec_discriminant(tmp, a, b); #ifdef DEBUG mpz_mod_ui(tmp, tmp, n); gmp_fprintf(stderr, "\tdelta(E/GF(n)) = %Zd\n", tmp); #endif /* DEBUG */ mpz_gcd_ui(tmp, tmp, n); #ifdef DEBUG gmp_fprintf(stderr, "\tgcd(delta, n) = %Zd\n", tmp); #endif /* DEBUG */ if (0 == mpz_cmp_ui(tmp, 1)) { break; } else if (0 != mpz_cmp_ui(tmp, n)) { #ifdef DEBUG gmp_fprintf(stderr, "\tfound a proper factor, %d is composite\n", n); #endif /* DEBUG */ is_prime = 0; goto cleanup_and_return; } } /* P + P != 0, or a new curve is generated */ z = ec_add(xt, yt, x0, y0, 1, x0, y0, 1, n, a); #ifdef DEBUG gmp_fprintf(stderr, "\t2 * P = (%Zd,%Zd,%d)\n", xt, yt, z); #endif /* DEBUG */ if (0 == z) { continue; } /* the curve order algorithm failing indicates n is composite */ if (!(ec_order(tmp, a, b, n))) { #ifdef DEBUG gmp_fprintf(stderr, "\tcurve order algorithm failed, %d must be composite\n", n); #endif /* DEBUG */ is_prime = 0; break; } #ifdef DEBUG gmp_fprintf(stderr, "\t|E/GF(n)| = %Zd\n", tmp); #endif /* DEBUG */ /* the curve order should be the multiple of 2 and a "probable prime" n -- * if the order is not even, a new curve is generated */ if (!mpz_even_p(tmp)) { #ifdef DEBUG gmp_fprintf(stderr, "\t|E/GF(n)| is odd, generating new curve...\n"); #endif /* DEBUG */ continue; } /* order * P = 0, or n is composite */ z = ec_times(xt, yt, x0, y0, 1, tmp, n, a); #ifdef DEBUG gmp_fprintf(stderr, "\t|E| * P = (%Zd,%Zd,%d)\n", xt, yt, z); #endif /* DEBUG */ if (0 != z) { #ifdef DEBUG gmp_fprintf(stderr, "\t|E| * P is non-zero, %d is composite\n", n); #endif /* DEBUG */ is_prime = 0; break; } /* at this point, order/2 being a prime implies n is a prime -- * a recursive call to ecpp_test is used to test order/2 for primality */ mpz_div_ui(tmp, tmp, 2); if (ecpp_test(mpz_get_ui(tmp))) { is_prime = 1; break; } } cleanup_and_return: mpz_clear(a); mpz_clear(b); mpz_clear(x0); mpz_clear(y0); mpz_clear(xt); mpz_clear(yt); mpz_clear(tmp); return is_prime; }
static void gt_out_info(FILE *out, field_ptr f) { gmp_fprintf(out, "roots of unity, order %Zd, ", f->order); field_out_info(out, f->data); }
static mp_size_t one_test (mpz_t a, mpz_t b, int i) { struct hgcd_matrix hgcd; struct hgcd_ref ref; mpz_t ref_r0; mpz_t ref_r1; mpz_t hgcd_r0; mpz_t hgcd_r1; int res[2]; mp_size_t asize; mp_size_t bsize; mp_size_t hgcd_init_scratch; mp_size_t hgcd_scratch; mp_ptr hgcd_init_tp; mp_ptr hgcd_tp; mp_limb_t marker[4]; asize = a->_mp_size; bsize = b->_mp_size; ASSERT (asize >= bsize); hgcd_init_scratch = MPN_HGCD_MATRIX_INIT_ITCH (asize); hgcd_init_tp = refmpn_malloc_limbs (hgcd_init_scratch + 2) + 1; mpn_hgcd_matrix_init (&hgcd, asize, hgcd_init_tp); hgcd_scratch = mpn_hgcd_appr_itch (asize); hgcd_tp = refmpn_malloc_limbs (hgcd_scratch + 2) + 1; mpn_random (marker, 4); hgcd_init_tp[-1] = marker[0]; hgcd_init_tp[hgcd_init_scratch] = marker[1]; hgcd_tp[-1] = marker[2]; hgcd_tp[hgcd_scratch] = marker[3]; #if 0 fprintf (stderr, "one_test: i = %d asize = %d, bsize = %d\n", i, a->_mp_size, b->_mp_size); gmp_fprintf (stderr, "one_test: i = %d\n" " a = %Zx\n" " b = %Zx\n", i, a, b); #endif hgcd_ref_init (&ref); mpz_init_set (ref_r0, a); mpz_init_set (ref_r1, b); res[0] = hgcd_ref (&ref, ref_r0, ref_r1); mpz_init_set (hgcd_r0, a); mpz_init_set (hgcd_r1, b); if (bsize < asize) { _mpz_realloc (hgcd_r1, asize); MPN_ZERO (hgcd_r1->_mp_d + bsize, asize - bsize); } res[1] = mpn_hgcd_appr (hgcd_r0->_mp_d, hgcd_r1->_mp_d, asize, &hgcd, hgcd_tp); if (hgcd_init_tp[-1] != marker[0] || hgcd_init_tp[hgcd_init_scratch] != marker[1] || hgcd_tp[-1] != marker[2] || hgcd_tp[hgcd_scratch] != marker[3]) { fprintf (stderr, "ERROR in test %d\n", i); fprintf (stderr, "scratch space overwritten!\n"); if (hgcd_init_tp[-1] != marker[0]) gmp_fprintf (stderr, "before init_tp: %Mx\n" "expected: %Mx\n", hgcd_init_tp[-1], marker[0]); if (hgcd_init_tp[hgcd_init_scratch] != marker[1]) gmp_fprintf (stderr, "after init_tp: %Mx\n" "expected: %Mx\n", hgcd_init_tp[hgcd_init_scratch], marker[1]); if (hgcd_tp[-1] != marker[2]) gmp_fprintf (stderr, "before tp: %Mx\n" "expected: %Mx\n", hgcd_tp[-1], marker[2]); if (hgcd_tp[hgcd_scratch] != marker[3]) gmp_fprintf (stderr, "after tp: %Mx\n" "expected: %Mx\n", hgcd_tp[hgcd_scratch], marker[3]); abort (); } if (!hgcd_appr_valid_p (a, b, res[0], &ref, ref_r0, ref_r1, res[1], &hgcd)) { fprintf (stderr, "ERROR in test %d\n", i); fprintf (stderr, "Invalid results for hgcd and hgcd_ref\n"); fprintf (stderr, "op1="); debug_mp (a, -16); fprintf (stderr, "op2="); debug_mp (b, -16); fprintf (stderr, "hgcd_ref: %ld\n", (long) res[0]); fprintf (stderr, "mpn_hgcd_appr: %ld\n", (long) res[1]); abort (); } refmpn_free_limbs (hgcd_init_tp - 1); refmpn_free_limbs (hgcd_tp - 1); hgcd_ref_clear (&ref); mpz_clear (ref_r0); mpz_clear (ref_r1); mpz_clear (hgcd_r0); mpz_clear (hgcd_r1); return res[0]; }
DEBUG_FUNCTION void debug_gmp_value (mpz_t val) { gmp_fprintf (stderr, "%Zd", val); }
/** * entry point of the program. * * @function main * * @date 2016-01-15 * * @revision none * * @designer Eric Tsang * * @programmer Eric Tsang * * @note * * sets up synchronization primitives, spawns worker threads, generates tasks * for workers, receives results from workers, waits for workers to terminate, * writes results to a file, and stdout. * * @signature int main(int argc,char** argv) * * @param argc number of command line arguments * @param argv array of c strings of command line arguments * * @return status code. */ int main(int argc,char** argv) { // parse command line arguments if (argc != 4) { fprintf(stderr,"usage: %s [integer] [path to log file] [num workers]\n",argv[0]); return 1; } if(mpz_set_str(prime.value,argv[1],10) == -1) { fprintf(stderr,"usage: %s [integer] [path to log file] [num workers]\n",argv[0]); return 1; } int logfile = open(argv[2],O_CREAT|O_WRONLY|O_APPEND); FILE* logFileOut = fdopen(logfile,"w"); if(logfile == -1 || errno) { fprintf(stderr,"usage: %s [integer] [path to log file] [num workers]\nerror occurred: ",argv[0]); perror(0); return 1; } unsigned int numWorkers = atoi(argv[3]); if (numWorkers <= 0) { fprintf(stderr,"usage: %s [integer] [path to log file] [num workers]\n num workers must be larger than or equal to 1",argv[0]); return 1; } // set up synchronization primitives for(register unsigned int i; i < numWorkers*MAX_PENDING_TASKS_PER_WORKER; ++i) { tasksNotFullSem.post(); } // get start time long startTime = current_timestamp(); // create the worker threads std::vector<pthread_t> workers; for(register unsigned int i = 0; i < numWorkers; ++i) { pthread_t worker; pthread_create(&worker,0,worker_routine,0); workers.push_back(worker); } // create tasks and place them into the tasks vector { Number prevPercentageComplete; Number percentageComplete; Number tempLoBound; Number loBound; for(mpz_set_ui(loBound.value,1); mpz_cmp(loBound.value,prime.value) <= 0; mpz_add_ui(loBound.value,loBound.value,MAX_NUMBERS_PER_TASK)) { // calculate and print percentage complete mpz_set(prevPercentageComplete.value,percentageComplete.value); mpz_mul_ui(tempLoBound.value,loBound.value,100); mpz_div(percentageComplete.value,tempLoBound.value,prime.value); if(mpz_cmp(prevPercentageComplete.value,percentageComplete.value) != 0) { gmp_fprintf(stdout,"%Zd%\n",percentageComplete.value); gmp_fprintf(logFileOut,"%Zd%\n",percentageComplete.value); } // insert the task into the task queue once there is room Number* newNum = new Number(); mpz_set(newNum->value,loBound.value); tasksNotFullSem.wait(); Lock scopelock(&taskAccess.sem); tasks.push_back(newNum); } } allTasksProduced = true; // join all worker threads for(register unsigned int i = 0; i < numWorkers; ++i) { void* unused; pthread_join(workers[i],&unused); } // get end time long endTime = current_timestamp(); // print out calculation results std::sort(results.begin(),results.end(),[](Number* i,Number* j) { return mpz_cmp(i->value,j->value) < 0; }); fprintf(stdout,"factors: "); fprintf(logFileOut,"factors: "); for(register unsigned int i = 0; i < results.size(); ++i) { gmp_fprintf(stdout,"%s%Zd",i?", ":"",results[i]->value); gmp_fprintf(logFileOut,"%s%Zd",i?", ":"",results[i]->value); delete results[i]; } fprintf(stdout,"\n"); fprintf(logFileOut,"\n"); // print out execution results fprintf(stdout,"total runtime: %lums\n",endTime-startTime); fprintf(logFileOut,"total runtime: %lums\n",endTime-startTime); // release system resources fclose(logFileOut); close(logfile); return 0; }
int main (int argc, char **argv) { gmp_randstate_ptr rands; long count = COUNT; mp_ptr mp; mp_ptr ap; mp_ptr tp; mp_ptr scratch; mpz_t m, a, r, g; int test; mp_limb_t ran; mp_size_t itch; TMP_DECL; tests_start (); rands = RANDS; TMP_MARK; mpz_init (m); mpz_init (a); mpz_init (r); mpz_init (g); if (argc > 1) { char *end; count = strtol (argv[1], &end, 0); if (*end || count <= 0) { fprintf (stderr, "Invalid test count: %s.\n", argv[1]); return 1; } } mp = TMP_ALLOC_LIMBS (MAX_SIZE); ap = TMP_ALLOC_LIMBS (MAX_SIZE); tp = TMP_ALLOC_LIMBS (MAX_SIZE); scratch = TMP_ALLOC_LIMBS (mpn_sec_invert_itch (MAX_SIZE) + 1); for (test = 0; test < count; test++) { mp_bitcnt_t bits; int rres, tres; mp_size_t n; bits = urandom () % (GMP_NUMB_BITS * MAX_SIZE) + 1; if (test & 1) mpz_rrandomb (m, rands, bits); else mpz_urandomb (m, rands, bits); if (test & 2) mpz_rrandomb (a, rands, bits); else mpz_urandomb (a, rands, bits); mpz_setbit (m, 0); if (test & 4) { /* Ensure it really is invertible */ if (mpz_sgn (a) == 0) mpz_set_ui (a, 1); else for (;;) { mpz_gcd (g, a, m); if (mpz_cmp_ui (g, 1) == 0) break; mpz_remove (a, a, g); } } rres = mpz_invert (r, a, m); if ( (test & 4) && !rres) { gmp_fprintf (stderr, "test %d: Not invertible!\n" "m = %Zd\n" "a = %Zd\n", test, m, a); abort (); } ASSERT_ALWAYS (! (test & 4) || rres); n = (bits + GMP_NUMB_BITS - 1) / GMP_NUMB_BITS; ASSERT_ALWAYS (n <= MAX_SIZE); itch = mpn_sec_invert_itch (n); scratch[itch] = ran = urandom (); mpz_to_mpn (ap, n, a); mpz_to_mpn (mp, n, m); tres = mpn_sec_invert (tp, ap, mp, n, bit_size (ap, n) + bit_size (mp, n), scratch); if (rres != tres || (rres == 1 && !mpz_eq_mpn (tp, n, r)) || ran != scratch[itch]) { gmp_fprintf (stderr, "Test %d failed.\n" "m = %Zd\n" "a = %Zd\n", test, m, a); fprintf (stderr, "ref ret: %d\n" "got ret: %d\n", rres, tres); if (rres) gmp_fprintf (stderr, "ref: %Zd\n", r); if (tres) gmp_fprintf (stderr, "got: %Nd\n", tp, n); if (ran != scratch[itch]) fprintf (stderr, "scratch[itch] changed.\n"); abort (); } } TMP_FREE; mpz_clear (m); mpz_clear (a); mpz_clear (r); mpz_clear (g); tests_end (); return 0; }
/* * This function reads the encrypted query sent by client, computes the intermediate cosine tfidf product and cosine co-ordination factor, * randomizes these two values and writes them along with respective randomizing values into the output_file_name. * */ int read_encrypt_vec_from_file_comp_inter_sec_prod( int vsizelocal, const char * input_encr_tfidf_file_name, const char * input_encr_bin_file_name, const char * input_tfidf_vec_file_name, const char * input_bin_vec_file_name, const char * output_file_name, const char * key_file_name) { int input_size = 0, i, temp, *p_tfidf_vec, *p_bin_vec; mpz_t *vec1; //holds input encrypted tfidf q values mpz_t *vec2; //holds input encrypted binary q values mpz_t cosine_result; mpz_t co_ord_factor; mpz_t random_no; FILE *input_encr_tfidf_file, *input_tfidf_vec_file, *input_bin_vec_file, *output_file, *input_encr_bin_file; vsize = vsizelocal; input_encr_tfidf_file = fopen(input_encr_tfidf_file_name, "r"); input_encr_bin_file = fopen(input_encr_bin_file_name, "r"); input_tfidf_vec_file = fopen(input_tfidf_vec_file_name, "r"); input_bin_vec_file = fopen(input_bin_vec_file_name, "r"); output_file = fopen(output_file_name, "w"); strncpy(g_key_file_name, key_file_name, sizeof(g_key_file_name)); printf("Number of vector dimensions = %d\n", vsizelocal); //printf("p_tfidf_vec:%p, ENOMEM:%d\n", p_tfidf_vec, (errno == ENOMEM)?1:0); //initialize vectors and big number variables //Dynamically creating the array vec1 = (mpz_t *)malloc(vsizelocal*sizeof(mpz_t)); vec2 = (mpz_t *)malloc(vsizelocal*sizeof(mpz_t)); p_tfidf_vec = (int*)malloc(vsize*sizeof(int)); p_bin_vec = (int*)malloc(vsize*sizeof(int)); printf("p_tfidf_vec:%p, ENOMEM:%d\n", p_tfidf_vec, (errno == ENOMEM)?1:0); //initialize vectors and big number variables for (i = 0; i < vsizelocal; i++) mpz_init(*(vec1+i)); for (i = 0; i < vsizelocal; i++) mpz_init(*(vec2+i)); //variables are set to 0 mpz_init(cosine_result); mpz_init(co_ord_factor); mpz_init(random_no); init(); //variables are set to 0 //init(); //check if files are opened properly if (input_encr_tfidf_file == NULL) { printf("\n%s", "Error: open input_encr_tfidf_file!"); return -2; } if (input_encr_bin_file == NULL) { printf("\n%s", "Error: open input_encr_bin_file!"); return -2; } if (input_tfidf_vec_file == NULL) { printf("\n%s", "Error: open input_tfidf_vec_file!"); return -3; } if (input_bin_vec_file == NULL) { printf("\n%s", "Error: open input_bin_vec_file!"); return -4; } if (output_file == NULL) { printf("\n%s", "Error: open output_file!"); exit(1); } //fill in the first vector input_size = 0; while ( (input_size < vsizelocal) ) { if ( input_size == vsizelocal - 1 ) { gmp_fscanf(input_encr_tfidf_file,"%Zd", (vec1+input_size)); } else { gmp_fscanf(input_encr_tfidf_file,"%Zd\n", (vec1+input_size)); } gmp_printf("%d>> READ %Zd\n", input_size+1, *(vec1+input_size)); input_size++; } if ( !( input_size == vsizelocal ) ) { fprintf(stderr, "%s:%d::ERROR! TFIDF: Nothing to read OR parsing error! input_size:%d, vsizelocal:%d\n", __func__, __LINE__, input_size, vsizelocal); return -4; } input_size = 0; while ( (input_size < vsizelocal) ) { if ( input_size == vsizelocal - 1 ) { gmp_fscanf(input_encr_bin_file,"%Zd", (vec2+input_size)); } else { gmp_fscanf(input_encr_bin_file,"%Zd\n", (vec2+input_size)); } gmp_printf("%d>> READ %Zd\n", input_size+1, *(vec2+input_size)); input_size++; } if ( !( input_size == vsizelocal ) ) { fprintf(stderr, "%s:%d::ERROR! Binary: Nothing to read OR parsing error! input_size:%d, vsizelocal:%d\n", __func__, __LINE__, input_size, vsizelocal); return -4; } printf("\n"); input_size = 0; //fill in the second vector for( fscanf(input_tfidf_vec_file,"%d", &temp); temp != EOF && input_size < vsize; fscanf(input_tfidf_vec_file, "%d", &temp) ){ printf("Non encrypted TFIDF Input::Wt.:%d\n", temp); *(p_tfidf_vec + input_size) = temp; input_size ++; } input_size = 0; for( fscanf(input_bin_vec_file,"%d", &temp); temp != EOF && input_size < vsize; fscanf(input_bin_vec_file, "%d", &temp) ){ printf("Non encrypted Binary Input::Wt.:%d\n", temp); *(p_bin_vec + input_size) = temp; input_size ++; } encrypt(cosine_result, 0); //compute encrypted the vec1 * p_tfidf_vec (dot product) for (i = 0; i < input_size; i++) { //compute m1 * m2 mpz_powm_ui(big_temp, *(vec1+i), *(p_tfidf_vec+i), n_square); //compute m1 + m2 mpz_mul(cosine_result, cosine_result, big_temp); mpz_mod(cosine_result, cosine_result, n_square); } encrypt(co_ord_factor, 0); //compute encrypted the vec2 * co_ord_factor (dot product) for (i = 0; i < input_size; i++) { //compute m1 * m2 mpz_powm_ui(big_temp, *(vec2+i), *(p_bin_vec+i), n_square); //compute m1 + m2 mpz_mul(co_ord_factor, co_ord_factor, big_temp); mpz_mod(co_ord_factor, co_ord_factor, n_square); } /* * Donot decrypt here as we would not be having the CORRESPONDING private key * */ //decrypt the encrypted dot product //decrypt(cosine_result); //TODO: Remove this debug decryption. - START mpz_t dot_prod; mpz_init(dot_prod); mpz_set(dot_prod, cosine_result); decrypt(dot_prod); gmp_fprintf(stderr, "\n%s:%d:: Query*%s TFIDF cosine product: %Zd\n", __func__, __LINE__, input_encr_tfidf_file_name, dot_prod); mpz_set(dot_prod, co_ord_factor); decrypt(dot_prod); gmp_fprintf(stderr, "%s:%d:: Query*%s CO-ORD. cosine product: %Zd\n\n", __func__, __LINE__, input_encr_bin_file_name, dot_prod); fflush(stderr); mpz_clear(dot_prod); //TODO: Remove this debug decryption. - END //decrypt the encrypted co ordination factor //decrypt(co_ord_factor); /* * Generate two random numbers of the modulo n_square and the add these two * to the two results - cosine product and co_ord_factor. * Write these two random values one after the other * and then the randomized values after them in the output file * given for performing the secure multiplication * protocol. All should be seperated by a newline except maybe the last one * written to the file. FORMAT - output file * ===START=== * r_1 * randomized cosine tfidf product * r_2 * randomized cosine co-ord. product * ===END=== * */ //Generate random number, say r_1 get_random_r_given_modulo(random_no, n_square); //Write r_1 to outputfile mpz_out_str(output_file, 10, random_no); fprintf(output_file, "\n"); //Calculate randomized cosine tfidf product, MULTIPLYING to add mpz_mul(cosine_result, cosine_result, random_no); //Compute modulus mpz_mod(cosine_result, cosine_result, n_square); //Write randomized cosine tfidf product to output file mpz_out_str(output_file, 10, cosine_result); fprintf(output_file, "\n"); //Generate random number, say r_2 get_random_r_given_modulo(random_no, n_square); //Write r_2 to outputfile mpz_out_str(output_file, 10, random_no); fprintf(output_file, "\n"); //Calculate randomized cosine tfidf product, MULTIPLYING to add mpz_mul(co_ord_factor, co_ord_factor, random_no); //Compute modulus mpz_mod(co_ord_factor, co_ord_factor, n_square); //Write randomized cosine co_ord product to output file mpz_out_str(output_file, 10, co_ord_factor); gmp_printf("\nThus similarity of %s and %s score = %Zd written in %s\n", input_encr_tfidf_file_name, input_tfidf_vec_file_name, cosine_result, output_file_name); #if 0 //print the cosine_result if (mpz_out_str(output_file, 10, cosine_result) == 0) printf("ERROR: Not able to write the cosine_result!\n"); fprintf(output_file, "\n"); #endif gmp_printf("\nThus co-ord. factor of %s and %s score = %Zd written in %s\n", input_encr_bin_file_name, input_bin_vec_file_name, co_ord_factor, output_file_name); #if 0 //print the co_ord_factor if (mpz_out_str(output_file, 10, co_ord_factor) == 0) printf("ERROR: Not able to write the co_ord_factor!\n"); #endif fclose(input_encr_tfidf_file); fclose(input_encr_bin_file); //fflush(input_tfidf_vec_file); fclose(input_tfidf_vec_file); //fflush(input_bin_vec_file); fclose(input_bin_vec_file); fflush(output_file); fclose(output_file); //release space used by big number variables for (i = 0; i < vsizelocal; i++) mpz_clear(*(vec1+i)); for (i = 0; i < vsizelocal; i++) mpz_clear(*(vec2+i)); mpz_clear(cosine_result); mpz_clear(co_ord_factor); mpz_clear(random_no); clear(); free(vec1); free(vec2); free(p_tfidf_vec); free(p_bin_vec); return 0; }