3

I have a problem with calculate of ASCII value with exponent and modulus. I want calculate ASCII value of "K" with RSA algorithm.

K in ascii value is 75

c   = m^e mod n
    = 75^41 mod 689
    = 316

Then how to make it into source code in C#? I got error "cannot implicity convert type".

this my source code

int n = 689;
int e = 41;
int d = 137;
string value = "K";

for (int i = 0; i < value.Length; i++)
{
    int c = (int)i;
    c = Math.Pow(i,e);
}
Console.ReadLine();
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Indra776
  • 41
  • 5
  • Not sure if it's related to your error message, but you seem to have an error in your code, the inner part of the for loop should work on `value[i]` instead of `i`. – jojonas Mar 30 '16 at 13:02

3 Answers3

3

Since 75^41 will overflow if cast to an int you have to do a little math trick. A*B mod N is equivalent to (A mod N) * (B mod N) mod N, so you just do the multiplication in a loop, taking the remainder each time:

public static int PowModN(int a, int b, int n)
{
    a = a % n;
    int c = 1;
    for(int i=1; i <= b; i++)
        c = (c*a % n);

    return c;
}

and change your loop to:

for (int i = 0; i < value.Length; i++)
{
    int c = (int)i;
    c = PowModN(i,e,n);
}
D Stanley
  • 149,601
  • 11
  • 178
  • 240
  • i have use your method but the result still error, the error message is like this "Error 4 An object reference is required for the non-static field, method, or property 'ConsoleApplication1.Program.PowModN(int, int, int)'" – Indra776 Mar 30 '16 at 13:30
  • If all of your code is in `static Main` then you can make `PowModN` `static` as well. I have updated my answer accordingly. – D Stanley Mar 30 '16 at 13:38
  • @JamesKPolk Great catch, James. Fixed. – D Stanley Mar 31 '16 at 12:41
1
string value = "K";

// Convert the string into a byte[].
byte[] asciiBytes = Encoding.ASCII.GetBytes(value);

Once you get the array out put you can set it to a variable and do whatever math you need to do.

sjr59
  • 93
  • 1
  • 9
  • i have use that method but when i operate it with math.pow() , that make an error, – Indra776 Mar 30 '16 at 12:45
  • Math.pow output is a double, not an int. cast it to an int or make your variable a double. i also believe the interior parameters need to be doubles as well. – sjr59 Mar 30 '16 at 12:48
0

The output of Math.Pow is a double, and takes two floats as arguments. At the very least, cast the output of Math.Pow(i,e) to be an int, like so:

c = (int)Math.Pow(i,e)

This is one of the worst things about C#, imo. Not sure why it doesn't innately support integer exponentiation.

What type is i? It might need to be casted to doubles as well.

Matt Messersmith
  • 12,939
  • 6
  • 51
  • 52