我想实现 ElGamal 加密。我的学校工作需要这个,但是当我想要解密时,最后一步总是 0,因为(b/Math.Pow(a,x))%primenumber总是小于 1。
这是密钥生成:
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;
        }