2013-01-05 73 views
1

我想實現ElGamal加密。我需要爲我的學校工作,但是當我想要做解密的最後一步始終是0原因的(B/Math.Pow(A,X))%primenumber總是小於1ElGamal C#實現

這裏是密鑰生成:

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} 

這裏是加密功能:

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; 

     } 

這裏是我的解密功能:

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; 
     } 

回答

2

您正在使用Math.Pow(base, exponent) % modulus進行模冪運算。這是行不通的,因爲浮點數不能代表加密需要的大整數。改爲使用System.Numerics.BigInteger.ModPow(base, exponent, modulus)

該部門可能不工作,因爲您使用整數除法,而不是乘以右邊的modular multiplicative inverse