Click here to Skip to main content
15,917,060 members
Please Sign up or sign in to vote.
3.33/5 (3 votes)
See more:
I had written a C++ program to perform the Schmidt - Samoa Public Key encryption. The code is as below :

C#
void keygen(long &publickey,long &privatekey,long &p,long &q)
{
     p = genrndprimes(0,10);
     q = genrndprimes(10,30);
    long n = power(p,2)*q;
    long d = (1/n)%lcm((p-1),(q-1));

    publickey = n;
    privatekey = d;

}

void encrypt(char *str,long *nums,long key)
{
    for(long i=0;i<strlen(str);i++)
    {
        nums[i]=(long)power(str[i],key)%key;
    }
}

void decrypt(char *str,long *nums,long key,long p,long q)
{
        for(long i=0;i<strlen(str);i++)
    {
        str[i]=(long)power(nums[i],key)%(p*q);
    }

}

void main()
{
	char m[]="Hello!!";
	long *j = new long[strlen(m)];
	long p,q,privtkey,publkey;
	keygen(publkey,privtkey,p,q);
	encrypt(m,j,publkey);
	puts(m);
	cout<<"\n\n";
	decrypt(m,j,privtkey,p,q);
	cout<<"\n\n";
	puts(m);
	getch();
	
}

The code however does not seem to encrypt properly , and therefore decryption gives some unknown
characters (whose ASCII is unknown). What could be the mistake ? I have also optimised the pow() function with power() (which uses exponentiation by squaring.) but in vain.
Posted
Comments
Sergey Alexandrovich Kryukov 7-Jun-13 14:49pm    
Just one not directly related note: encoding should not work with strings, it should work with abstract data, an arbitrary array of bytes on input, another array of bytes on output (actually, unsigned char is good enough to represent a byte. And of course, it should be totally agnostic to encoding (after all, who needs ASCII these days?)...

Also, you never return values, even in cases where you apparently can. This is not C++ style... Generally, code style looks very awkward. Why, for example "publickey = n; privatekey = d;"? you could assign the values in first place...

—SA
compuknow 7-Jun-13 22:11pm    
If not ASCII , then which character set should I use? How can i process data with that character set in C++?
Sergey Alexandrovich Kryukov 7-Jun-13 22:43pm    
I just explained: encryption should work with any data, no encoding. It looks like you don't understand what data is...
—SA
Steve44 8-Jun-13 23:04pm    
My basic recommendation would be to write a unit test for the encryption:
- generate key pair,
- iterate over all byte values (0-255)
- in the loop: encrypt this byte to your long, decrypt the long, compare with original value
- repeat with different key pairs
This should help you find out, if your basic encryption/decryption algorithm is working.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900