Exemplo n.º 1
0
        public void RsaCryptorTest()
        {
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
            {
                RSAParameters rsaKeyInfo = rsa.ExportParameters(true);

                byte[] data = new byte[100];
                new Random().NextBytes(data);

                var cryptor = new RsaMachine(rsaKeyInfo);

                byte[] encrypted = cryptor.Encrypt(data);
                byte[] decrypted = cryptor.Decrypt(encrypted);

                Assert.IsTrue(data.SequenceEqual(decrypted));
            }
        }
Exemplo n.º 2
0
        public void DsaSignerTest()
        {
            using (
                RSACryptoServiceProvider dsaprovider = new RSACryptoServiceProvider())
            {
                RSAParameters keys = dsaprovider.ExportParameters(true);

                byte[] data = new byte[100];
                new Random().NextBytes(data);

                RsaMachine    signer = new RsaMachine(keys);
                HashAlgorithm hasher = MD5.Create();

                byte[] signature = signer.Sign(data, hasher);

                Assert.IsTrue(signer.CheckSignature(data, hasher, signature));
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Decrypts a file.
        /// </summary>
        /// <param name="input"><see cref="EncryptedFile"/> that will be decrypted.</param>
        /// <param name="output">Output <see cref="Stream"/> where the decrypted file will be written.</param>
        /// <param name="reportProgress">Action that is used to report progress of decryption in percentages.</param>
        public void Decrypt(EncryptedFile input, Stream output, Action <int> reportProgress = null)
        {
            BinaryReader reader = new BinaryReader(input.BaseStream);

            reader.BaseStream.Position = input.HeaderLength;
            output.Position            = 0;
            BinaryWriter outputWriter = new BinaryWriter(output);

            byte[] decryptedAlgKey = new RsaMachine(this.Key).Decrypt(input.EncryptedKey);
            reportProgress?.Invoke(35);

            IMachine decryptor = null;

            if (input.CryptorCode == AesMachine.Signature)
            {
                decryptor = new AesMachine(decryptedAlgKey, reader.ReadBytes(16));
            }
            else if (input.CryptorCode == TDesMachine.Signature)
            {
                decryptor = new TDesMachine(decryptedAlgKey, reader.ReadBytes(16));
            }
            else if (input.CryptorCode == TwofishMachine.Signature)
            {
                decryptor = new TwofishMachine(decryptedAlgKey, reader.ReadBytes(16));
            }

            for (int i = 0; i < input.NumberOfBlocks; i++)
            {
                int    currentBlockSize = BitConverter.ToInt32(reader.ReadBytes(4), 0);
                byte[] block            = reader.ReadBytes(currentBlockSize);
                outputWriter.Write(decryptor.Decrypt(block));
                reportProgress?.Invoke((int)(((float)i / (float)input.NumberOfBlocks) * 1000.00));
            }

            reportProgress?.Invoke(1000);
        }
Exemplo n.º 4
0
        public UserInformation Login(string username, string password, out UserDatabase data)
        {
            UserDatabase dataComp = new UserDatabase(this.userDatabasePath);

            var user = dataComp.GetUser(username);

            if (user != null && user.IsPasswordValid(password))
            {
                var userCert = new X509Certificate2(user.PublicCertificate);

                if (userCert == null)
                {
                    throw new Exception("Certificate error.");
                }

                if (CertificateValidator.VerifyCertificate(userCert) == false)
                {
                    throw new Exception("Certificate is invalid.");
                }

                byte[] keyRaw            = File.ReadAllBytes(this.privateKeyPath);
                var    privateParameters = new KeyFileParser(keyRaw).GetParameters();
                RSACryptoServiceProvider publicKeyProvider = (RSACryptoServiceProvider)userCert.PublicKey.Key;
                if (!RsaMachine.AreKeysMatched(publicKeyProvider.ExportParameters(false), privateParameters))
                {
                    throw new Exception("The given private key does not match this user's certificate.");
                }

                data = dataComp;
                return(new UserInformation(user, privateParameters));
            }
            else
            {
                throw new Exception("Invalid username or password.");
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// Encrypts a file using a combination of an encryption and a hash algorithm.
        /// </summary>
        /// <param name="input"><see cref="OriginalFile"/> to be encrypted.</param>
        /// <param name="output">Output <see cref="Stream"/> where the encrypted file will be written.</param>
        /// <param name="algs">Combination of an encryption and a hash algorithm.</param>
        /// <param name="reportProgress">Action used to report progress somewhere.</param>
        public void Encrypt(OriginalFile input, Stream output, CryptCombo algs, Action <int> reportProgress = null)
        {
            BinaryWriter writer = new BinaryWriter(output); // to write to output
            BinaryReader reader = new BinaryReader(input.FileContent);

            writer.Seek(0, SeekOrigin.Begin); // write to beginning, this will override if there is something there
            reader.BaseStream.Position = 0;   // read from beginning

            long numberOfBlocks = input.FileContent.Length / algs.Machine.BlockSize;

            if (numberOfBlocks * algs.Machine.BlockSize < input.FileContent.Length)
            {
                numberOfBlocks++;
            }

            var algKey     = algs.Machine.Key;
            var cryptedkey = new RsaMachine(this.ReceiverPublicKey).Encrypt(algKey);

            byte[] header = new byte[] { };
            header = header // we concat here instead of writing directly so we can calculate hash
                     .Concat(Helpers.MagicBytes)
                     .Concat(Encoding.ASCII.GetBytes(algs.Machine.GetSignatureString()))
                     .Concat(Encoding.ASCII.GetBytes(Helpers.GetCodeFromHasher(algs.Hasher)))
                     .Concat(BitConverter.GetBytes(cryptedkey.Length))
                     .Concat(cryptedkey)
                     .Concat(BitConverter.GetBytes(input.Extension.Length))
                     .Concat(Encoding.ASCII.GetBytes(input.Extension))
                     .Concat(BitConverter.GetBytes(numberOfBlocks))
                     .ToArray();

            var contentHashAggregate = algs.Hasher.ComputeHash(header);

            writer.Write(header);
            reportProgress?.Invoke(25);

            byte[] additionalData = algs.Machine.AdditionalData;
            if (additionalData != null)
            {
                contentHashAggregate = algs.Hasher.ComputeHash(contentHashAggregate.Concat(algs.Hasher.ComputeHash(additionalData)).ToArray());
                writer.Write(additionalData);
            }

            reportProgress?.Invoke(30);
            for (int i = 0; i < numberOfBlocks; i++)
            {
                byte[] buffer         = reader.ReadBytes(algs.Machine.BlockSize);
                byte[] encryptedBlock = algs.Machine.Encrypt(buffer);
                byte[] encSize        = BitConverter.GetBytes(encryptedBlock.Length);
                byte[] blockToWrite   = encSize.Concat(encryptedBlock).ToArray();
                contentHashAggregate = algs.Hasher.ComputeHash(contentHashAggregate.Concat(algs.Hasher.ComputeHash(blockToWrite)).ToArray());
                writer.Write(blockToWrite);

                int progress = (int)(((float)i / (float)numberOfBlocks) * 1000.00);
                reportProgress?.Invoke(progress < 980 ? progress : 980);
            }

            byte[] rsaSignature = new RsaMachine(this.SenderPrivateKey).Sign(contentHashAggregate, algs.Hasher);
            reportProgress?.Invoke(990);

            writer.Write(rsaSignature.Length);
            writer.Write(rsaSignature);
            reportProgress?.Invoke(1000);
        }