1

我想实现 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;
        }
4

1 回答 1

2

您正在使用Math.Pow(base, exponent) % modulus模幂运算。那是行不通的,因为浮点数不能代表加密货币需要的大整数。改为使用System.Numerics.BigInteger.ModPow(base, exponent, modulus)

除法可能不起作用,因为您使用整数除法,而不是与右侧的模乘法逆相乘。

于 2013-01-06T14:25:39.433 回答