Hejsa, jeg er igang med lidt RSA kryptering, men jeg har lidt problemer med
at få koden til at virke.
Jeg sender 4711 ind men får 0 tilbage.
Jeg gætter på at fejlen ligger i metoden power ( )
jeg har taget udgangspunkt i et java eksemple, hvilket sikkert ikke var den
bedste ide. Da jeg ikke ligefrem er nogen haj til C++.
nå men her er hele koden. håber nogen kan hjælpe mig
mvh
Anders Gulbæk
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <iostream>
class RSA
{
private: long message,p,q;
long x;
long y;
long n,z,e,d;
long code,decode;
//Number of witnesses in primality test
int TRIALS;
public: RSA(long msg)
{
message = msg;
TRIALS =5;
}
void calculate();
void euclid(long a, long b);
void printResult();
int isPrime(long n);
long greatestCommon(long a, long b);
long greatestCommon2(long a, long b);
long power(long x, long n, long p);
long findInverse(long a, long n);
long witness(long a, long i, long n);
};
void RSA:: calculate()
{
for(p=25000;!isPrime(p);p++)
;
std::cout<<"p: "<<p<<std::endl;
for(q=30000+2;!isPrime(q);q++)
;
std::cout<<"q: "<<q<<std::endl;
n = p*q;
std::cout<<"n: "<<n<<std::endl;
z = (p-1)*(q-1);
std::cout<<"z: "<<z<<std::endl;
for(e = z / 10;greatestCommon(e,z)!=1;e++)
;
std::cout<<"Encryption key e: "<<e<<std::endl;
d = findInverse(e,z);
std::cout<<"Decryption key d: "<<d<<std::endl;
code = power(message,e,n);
std::cout<<"Kodet: "<<code<<std::endl;
decode = power(code,d,n);
std::cout<<"Dekodet: "<<decode<<std::endl;
int stop;
std::cin>>stop;
}
long RSA:: witness(long a, long i, long n)
{
if (i==0)
return 1;
long x = witness(a,i/2,n);
if(x==0)
return 0;
long y = (x*x)%n;
if(y==1 && x!=1 && x!=n-1)
return 0;
if (i%2!=0)
y = (a*y)%n;
return y;
}
int RSA:: isPrime(long n)
{
for(int counter = 0; counter < TRIALS; counter++)
{
long r = rand()%(n-3); //Skal laves om til Random()
if(witness(r+ 2, n - 1, n) != 1)
return 0;
}
return 1;
}
long RSA:: greatestCommon(long a, long b)
{
if(b==0)
return a;
else
return greatestCommon2(b,a%b);
}
long RSA:: greatestCommon2(long a, long b)
{
if(b==0)
return a;
else
return greatestCommon(b,a%b);
}
void RSA:: euclid(long a, long b)
{
long x1,y1;
if(b==0)
{
x=1;
y=0;
}
else
{
euclid(b,a%b);
x1 = x; y1 = y;
x = y1;
y = x1 -(a/b)*y1;
}
}
long RSA:: findInverse(long a, long n)
{
euclid(a,n);
return x>0?x:x+n;
}
long RSA:: power(long x, long n, long p)
{
if(n==0)
return 1;
long tmp = power((x*x)%p,n/2,p);
if(n%2!=0)
tmp = (tmp*x)%p;
return tmp;
}
void RSA:: printResult()
{
std::cout <<"p="+p<< std::endl;
std::cout <<"q="+q<< std::endl;
std::cout <<"n="+n<< std::endl;
std::cout <<"z="+z<< std::endl;
std::cout <<"e="+e<< std::endl;
std::cout <<"d="+d<< std::endl;
std::cout <<"message="+message<< std::endl;
std::cout <<"Code="+code<< std::endl;
std::cout <<"Decode="+decode<< std::endl;
}
void main()
{
long x = 4711;
RSA rsa = RSA(x);
rsa.calculate();
rsa.printResult();
}
|