Алгоритм RSA: неверный открытый текст при расшифровке - PullRequest
0 голосов
/ 25 января 2019
class Calculate
{
  double gcd(double a, double b)
  {
    if (b == 0)
    {
      return a;
    }
    return gcd(b, a % b);
  }

  Calculate()
  {
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter values of p : ");
    double p = sc.nextDouble();
    System.out.print("\nEnter value of q : ");
    double q = sc.nextDouble();
    System.out.print("\nEnter Message: ");
    double m = sc.nextDouble();  // message

    double n = p * q;
    System.out.println("n = " + n);    // first part of the public key
    double phi = (p - 1) * (q - 1);
    System.out.println("phi = " + phi);

    // assuming e = 3 
    double e = 3;        // second part of the public key

    // e must be relatively prime and smaller than phi
    while (e < phi)
    {
      if (gcd(e, phi) == 1)
      {
        break;
      }
      else
      {
        e++;
      }
    }

    // to find d
    // method : (k * phi + 1) / e = quotient should be 0 ( perfectly divisible)
    double k = 1;
    double d;
    while (true)
    {
      double temp = 1 + (k * phi);
      if (temp % e == 0)
      {
        d = temp / e;
        break;
      }
      else
      {
        k++;
      }
    }
    System.out.println("d = " + d);

    // encryption
    double c = 0;  // cypher text
    double x = Math.pow(m, e);
    c = x % n;
    System.out.println("Encrypted Data: " + c);

    // decryption
    BigDecimal pt;      // plain text
    double y = Math.pow(c, d);
    BigDecimal Y = BigDecimal.valueOf(y);
    BigDecimal N = BigDecimal.valueOf(n);
    pt = Y.remainder(N);
    System.out.println("Decrypted Data: " + pt);
  }
}

p = 11

q = 5

м = 9

Расчет вручную дает значения:

n = 55

фи = 40

д = 27

Зашифрованный текст = 14,0

Это правильные значения.

Но я получаю неправильное значение для расшифровки, хотя формула верна.

Расшифрованный текст = 25.0 // Неверное значение. Должно быть 9.

Во-первых, я решил, что двойного недостаточно для представления больших значений при расчете простого текста.

Поэтому я использовал BigDecimal (я новичок в этом)

Формула для расчета расшифрованного текста верна. Я не понимаю, что не так с программой.

1 Ответ

0 голосов
/ 25 января 2019

Я думаю, что вы забыли сделать .mod (N) вместо .remainder ().

// decryption
BigInteger N = BigDecimal.valueOf(n).toBigInteger();
//converting double value of c to BigInteger
BigInteger C = BigDecimal.valueOf(c).toBigInteger();
int dint = (int) Math.round(d);
BigInteger msgback = (C.pow(dint)).mod(N);
System.out.println("Decrypted Data: " + msgback);

Это немного измененная версия, я преобразовал двойной d в целое число, чтобы можно было назвать pow.Удачи!

...