2013-01-05 5 views
1

Je veux implémenter le cryptage ElGamal. J'ai besoin pour mon travail scolaire, mais quand je veux faire le décryptage de la dernière étape est toujours 0 cause de (b/Math.pow (a, x))% primenumber est toujours inférieure à 1.ElGamal C# implémentation

Voici le clés génération:

public void GenerateKey() { 
    this.x = 3; 
    this.prvocislo = PrimeGen.findPrimes(29).Max(); //prime number 
    this.g = this.prvocislo % 12; 
    this.y = Convert.ToInt32(Math.Pow(this.g, this.x) % this.prvocislo); 
    this.k = 23;//601} 

est ici fonction Crypter:

public string Encrypt(string word) { 
      List<string> words = new List<string>(); 

      words = PrimeGen.SplitToArray(word, 2); 

      string encrypted=""; 

      string sss = PrimeGen.GetStringFromBytes(PrimeGen.GetBytesFromInt(PrimeGen.GetIntFromBytes(PrimeGen.GetBytesFromString("ah")))); //returns ah so conversion works 
      foreach (string s in words) 
      { 
       int a = Convert.ToInt32(Math.Pow(g,k) % prvocislo); 
       int b = Convert.ToInt32((Math.Pow(y, k) * PrimeGen.GetIntFromBytes(PrimeGen.GetBytesFromString(s))) % prvocislo); 
       string aS = PrimeGen.GetStringFromBytes(PrimeGen.INT2LE(a + posun)); 
       string bS = PrimeGen.GetStringFromBytes(PrimeGen.INT2LE(b + posun)); 
       encrypted = encrypted + aS + bS; 
      } 
      return encrypted; 

     } 

Voici ma Décrypter fonction:

public string Decrypt(string ElgamalEncrypted) { 
      string decrypted = ""; 
      for (int i = 0; i < ElgamalEncrypted.Length; i = i + 2) { 
       string aS = ElgamalEncrypted.Substring(i, 2); 
       string bS = ElgamalEncrypted.Substring(i + 2, 2); 
       int a = PrimeGen.GetIntFromBytes(PrimeGen.GetBytesFromString(aS)) - posun; 
       int b = PrimeGen.GetIntFromBytes(PrimeGen.GetBytesFromString(bS)) - posun; 
       if(b==0) b=1; 
       if (a == 0) a = 1; 
       decrypted=decrypted+PrimeGen.GetStringFromBytes(PrimeGen.GetBytesFromInt(Convert.ToInt32(((b/Math.Pow(a,x))%prvocislo)))); 


      } 
      return decrypted; 
     } 

Répondre

2

Vous utilisez Math.Pow(base, exponent) % modulus pour l'exponentiation modulaire. Cela ne fonctionne pas parce que les points flottants ne peuvent pas représenter les besoins entiers crypto grands. Utilisez System.Numerics.BigInteger.ModPow(base, exponent, modulus) à la place.

La division ne fonctionne probablement pas car vous utilisez une division entière, au lieu de multiplier par modular multiplicative inverse du côté droit.