Exemplo n.º 1
0
        public static void Encrypt(int bitsKeyLength, TestPrimeDelegate testPrime, string inputFilePath,
                                   string sourceFilePath, string publicKeyFilePath, string privateKeyFilePath)
        {
            var bytesKeyLength = bitsKeyLength / 8;
            var p = GenerateLargePrimeNumber(bytesKeyLength, testPrime);
            var q = GenerateLargePrimeNumber(bytesKeyLength, testPrime);

            var n    = p * q;
            var phiN = EulerFunction(p, q);

            Debug.Assert(Gcd(PublicExponent, phiN).IsOne);
            // calculate d
            BigInteger d, tmp;
            var        g = Gcd(PublicExponent, phiN, out d, out tmp);

            d = (d % phiN + phiN) % phiN;

            Console.WriteLine("Writing public key to " + publicKeyFilePath);
            WriteKeyToFile(n, publicKeyFilePath);
            Console.WriteLine("Writing private key to " + privateKeyFilePath);
            WriteKeyToFile(d, privateKeyFilePath);

            Console.WriteLine("Writing encrypted data to " + DefaultEncryptedFileName);
            using (var reader = File.OpenRead(Path.GetFullPath(DefaultSourceFileName))) {
                using (var writer = File.CreateText(Path.GetFullPath(DefaultEncryptedFileName))) {
                    int b;
                    var first = true;

                    while ((b = reader.ReadByte()) != -1)
                    {
                        if (!first)
                        {
                            writer.Write(Delimeter);
                        }
                        else
                        {
                            first = false;
                        }

                        var encryptedBytes = BinPowMod(b, PublicExponent, n);
                        writer.Write(encryptedBytes.ToString());
                    }
                }
            }
        }
Exemplo n.º 2
0
        private static BigInteger GenerateLargePrimeNumber(int bytesLength, TestPrimeDelegate testPrime)
        {
            while (true)
            {
                var candidate = GenerateRandomNumber(bytesLength);
                while (candidate <= 2)
                {
                    candidate = GenerateRandomNumber(bytesLength);
                }
                // make odd
                candidate |= 1;

                if (testPrime(candidate))
                {
                    return(candidate);
                }
            }
        }