Adesanya Olusegun

Adesanya Olusegun

  • NA
  • 19
  • 26.1k

need help converting this C code to C#

Apr 7 2014 8:53 PM
am sorry for disturbing you once again but i need your help to convert the lines of code

//cipher function called from either encrypt or decrypt
int cipher(unsigned int exponent, unsigned int text, unsigned int modulus)
{
unsigned long result;
result = 1;
//use the square and multiply algorithm to calculate the result
while (exponent > 0)
{
if ((exponent & 1) == 1) // if the least significant bit of exponent is
a 1
{
result = (result * text) % modulus; // multiply result so far by text
and use modulus to keep result small
}
exponent >>= 1; // shift the exponent right by 1, losing the most
significant bit (0110 becomes 011)
text = (text * text) % modulus; //square the text and use modulus to
keep small
}
return result;
}
//encrypt function called from menu.c
int encrypt (void)
{
unsigned int plaintext, exponent, modulus, result;
//Open public_key.txt and read out the two values stored in it
FILE *fptr;
fptr = fopen("public_key.txt","r");
if (fptr != NULL) //check if file exists
{
fscanf(fptr,"%d %d", &exponent, &modulus); //read the values
fflush(fptr);
fclose(fptr);
//Get plaintext off user it must be less than the modulus
do
{
printf("Enter Plaintext, must be a positive number less than the
modulus n: %d:\n", modulus);
scanf("%d",&plaintext);
} while (plaintext >= modulus);
//encrypt the plaintext using the cipher function
result = cipher(exponent, plaintext, modulus);
//print out the result for the user
printf("Encrypted message is %d\n", result);
}
else //if the file doesn't exist print the error
{
printf("\nERROR: ENCRYPTION UNSUCCESSFULL\n\n\n"); //if there was an
error
return(1);
}
return 0;
}
//decrypt function called from menu.c
int decrypt (void)
{
unsigned int ciphertext, exponent, modulus, result;
//Open private_key.txt and read out the two values stored in it
FILE *fptr;
fptr = fopen("private_key.txt","r");
if (fptr != NULL)//check the file exists
{
fscanf(fptr,"%d %d", &exponent, &modulus); //read values
fflush(fptr);
fclose(fptr);
//Get ciphertext of user
printf("Enter ciphertext:\n");
scanf("%d",&ciphertext);
//decrypt the message
result = cipher(exponent, ciphertext, modulus);
//print the result for the user
printf("Decrypted message is %d\n", result);
}
else //if the file doesn't exist print the error
{
printf("\nERROR: DECRYPTION UNSUCCESSFULL\n\n\n"); //if there was an
error
return(1);
}
return 0;
}

Answers (2)