我想实现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;
}
答案 0 :(得分:2)
您正在使用Math.Pow(base, exponent) % modulus
进行模幂运算。这不起作用,因为浮点不能代表加密需要的大整数。请改用System.Numerics.BigInteger.ModPow(base, exponent, modulus)
。
该除法可能不起作用,因为你使用整数除法,而不是乘以右边的modular multiplicative inverse。