The algorithm is designed to encrypt biginteger numbers. The essence of the problem is that my algorithm works only with a key length of 16 bits, if you put any other number, which always works incorrectly. The algorithm is based on an article from Wikipedia. I cannot use the RSACryptoServiceProvider algorithm built into C #.
public class RSA_I { public BigInteger e; public BigInteger d; public BigInteger n; public BigInteger Fi; public RSA_I() { } public RSA_I(int keySize) { e = 65537; snova: BigInteger q = GetBigint(keySize / 2); BigInteger p = GetBigint(keySize / 2); if (p % 2 == 0) p += 1; if (q % 2 == 0) q += 1; while (!Test_MIl_Rab(q, keySize / 2, 5)) { q = (q + GetBigint(keySize / 2)) / 2; } while (!Test_MIl_Rab(p, keySize / 2 , 5) && p == q) { p = (p + GetBigint(keySize / 2)) / 2; } BigInteger E_fynk = BigInteger.Multiply((q - 1) , (p - 1)); if (E_fynk % e == 0) goto snova; Fi = E_fynk; n = BigInteger.Multiply(q, p); d = ObrEllement(e, E_fynk); if (BigInteger.ModPow(BigInteger.Multiply(d, e), 1, E_fynk) != 1) goto snova; } /// <summary> /// шифрование /// </summary> public BigInteger Encrypt(BigInteger text) { return BigInteger.ModPow(text, e, n); } /// <summary> /// дешифровка /// </summary> public BigInteger Decrypt(BigInteger text) { return BigInteger.ModPow(text, d, n); } public BigInteger GetBigint(int size) { var rand = new RNGCryptoServiceProvider(); byte[] By = new byte[size / 8]; rand.GetBytes(By); BigInteger X = new BigInteger(By); return BigInteger.Abs(X); } private BigInteger GetBigint(BigInteger min, BigInteger max, int a) { RNGCryptoServiceProvider c = new RNGCryptoServiceProvider(); byte[] randomNumber = new byte[a / 8]; c.GetBytes(randomNumber); BigInteger result = Math.Abs(BitConverter.ToInt32(randomNumber, 0)); return (result % max + min) % max; } private bool Test_MIl_Rab(BigInteger n, int size_s, int Rt) { if (n <= 1) return false; if (n == 2) return true; if (n % 2 == 0) return false; BigInteger s = 0; BigInteger d = n - 1; while (d % 2 == 0) { d /= 2; s++; } long[] V = { 2, 3, 5, 7, 9 }; for (int i = 0; i < Rt; i++) { BigInteger K = BigInteger.ModPow(V[i], d, n); for (int j = 0; j < s; j++) { K = (K * K) % n; if (K == n - 1 || K == -1) break; } if (K != n - 1) return false; } return true; } private BigInteger ObrEllement(BigInteger a, BigInteger mod) { BigInteger i = mod, v = 0, d = 1; while (a > 0) { BigInteger t = i / a, x = a; a = i % x; i = x; x = d; d = v - t * x; v = x; } v %= mod; if (v < 0) v = (v + mod) % mod; return v; } }
BigInteger.ModPow(BigInteger.Multiply(d, e), 1, E_fynk)looks strange. why raise to degree 1? I think you have an error in generatingeanddvalues. - Mikhail Vaysman