0

I'm trying to make a RSA algorithm. For that i need rabin-miller+witness+modular exponentiation(at least I'm required to use that). The problem comes when i generate random numbers to check with rabin miller if they are primes, and the result is that non-prime numbers are prime for rabin-miller algorithm. Could somebody give me a hand to see where i fail. Thanks in advance.

int mod_exp(int a, int b, int n){

    int d = 1,i,j=0;
    int binary[15];
    for(i=0;i<=15;i++){
        binary[i] = -1;
    }
    i=0;
    do{
        binary[i]=(b%2);

            if((b%2)==1)
                b=(b-1)/2;
            else
                b=b/2;
        i++;
    }while(b!=0);

    do{
        d= (d*d)%n;
        if(binary[i]==1)
            d=(d*a)%n;
        i--;
    }while(i!=-1);
    return d;

}

bool wittness(int a, int n){
    int u=n-1,k=0;
    long x, temp;
    while(u%2== 0 ){
        u=u/2;
        k++;
    }
    x=mod_exp(a,u,n);
    for(int i=1;i<=k;i++){
        temp=x;
        cout<< "primera x:"<<x<<endl;
        x=long(x*x)%n;
        cout<< "segunda x:"<<x<<endl;
        if(x==1 && temp!=1 && temp != n-1)
            return true;

    }
    if(x!=1)
        return true;
    return false;

}


bool miller_rabin(int n, int s){

    int a,j;
    srand(time(NULL));

    for(j = 0; j<=s;j++){

       a=rand()%s+1;
       if(!wittness(a,n))
        return false;
    }
    return true;
}
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Lolo
  • 7
  • 1
  • 7
  • I take it this is an exercise, rather than code you are planning to release in an actual product? The former is fine; for the latter - just use a library written by experts! (You can't write tests for "is this library insecure?") – Martin Bonner supports Monica Dec 13 '15 at 21:14
  • I've just seen you are using "int" - which is usually 32bits. Given that uint512_t is hopelessly insecure for RSA, this is *clearly* "exercise" not "production". – Martin Bonner supports Monica Dec 13 '15 at 21:16
  • I thought everybody would undrstand when i said "(at least I'm required to use that)" sorry if you didnt. Yes, it´s an exercise and it works, i just had problems calling the functions. Thanks anyway to those who helped. – Lolo Dec 13 '15 at 21:27

1 Answers1

1

I haven't looked at all of the code, but your mod_exp function is certainly incorrect. The two expressions (d*d)%n and (d*a)%n are both susceptible to overflow, and if overflow occurs you will get an incorrect result.

user448810
  • 17,381
  • 4
  • 34
  • 59