Exemple #1
0
        public void DecryptFile(IFileReader fileReader, IFileWriter fileWriter, uint d)
        {
            if (fileReader == null)
            {
                throw new ArgumentNullException(nameof(fileReader));
            }

            if (fileWriter == null)
            {
                throw new ArgumentNullException(nameof(fileWriter));
            }

            if (d < 1)
            {
                throw new ArgumentException($"{nameof(d)} must be higher than 0");
            }

            KeysFromLastRun.Clear();
            RsaKeysFromLastRun.Clear();

            var e    = fileReader.ReadBits(32);
            var n    = fileReader.ReadBits(32);
            var keys = GetKeysFromFile(fileReader, n, d);

            var indexOfByte = 0;

            while (!fileReader.ReachedEndOfFile)
            {
                var encryptedByte = (byte)fileReader.ReadBits(8);
                var decryptedByte = DecryptByte(encryptedByte, keys, indexOfByte);
                fileWriter.WriteValueOnBits(decryptedByte, 8);

                indexOfByte++;
            }
        }
        public void EncryptFile(IFileReader fileReader, IFileWriter fileWriter, uint n, uint e)
        {
            if (fileReader == null)
            {
                throw new ArgumentNullException(nameof(fileReader));
            }

            if (fileWriter == null)
            {
                throw new ArgumentNullException(nameof(fileWriter));
            }

            if (n < 1)
            {
                throw new ArgumentException($"{nameof(n)} must be higher than 0");
            }

            if (e < 1)
            {
                throw new ArgumentException($"{nameof(e)} must be higher than 0");
            }

            KeysFromLastRun.Clear();
            RsaKeysFromLastRun.Clear();

            // TODO: Is it normal for the random key to be smaller than n?
            var randomKeys = GetRandomKeys(n - 1);
            var rsaKeys    = GetRsaKeys(randomKeys, n, e);

            fileWriter.WriteValueOnBits(e, 32);
            fileWriter.WriteValueOnBits(n, 32);
            WriteRsaKeysToFile(rsaKeys, fileWriter);

            var currentIndex = 0;

            while (!fileReader.ReachedEndOfFile)
            {
                var currentByte = (byte)fileReader.ReadBits(8);
                var encodedByte = GetEncodedByte(currentByte, randomKeys, currentIndex);

                fileWriter.WriteValueOnBits(encodedByte, 8);

                currentIndex++;
            }
        }