Example #1
0
        /// <summary>
        /// AES解密
        /// </summary>
        /// <param name="encryptStr">密文字符串</param>
        /// <returns>明文</returns>
        public static string AESDecrypt(string encryptStr, string key)
        {
            byte[] bKey      = Encoding.UTF8.GetBytes(key.Replace("-", ""));
            byte[] bIV       = Encoding.UTF8.GetBytes(key.Substring(0, 16));
            byte[] byteArray = Convert.FromBase64String(encryptStr);

            Rijndael aes = Rijndael.Create();

            try
            {
                using (MemoryStream mStream = new MemoryStream())
                {
                    using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateDecryptor(bKey, bIV), CryptoStreamMode.Write))
                    {
                        cStream.Write(byteArray, 0, byteArray.Length);
                        cStream.FlushFinalBlock();
                        return(Encoding.UTF8.GetString(mStream.ToArray()));
                    }
                }
            }
            catch
            {
                return(null);
            }
            finally
            {
                aes.Clear();
                aes.Dispose();
                aes = null;
            }
        }
        private static JObject Unprotect(string protectedStr, SecureString password)
        {
            byte[]       bytesBuff = Convert.FromBase64String(protectedStr);
            Rijndael     rijndael  = Rijndael.Create();
            MemoryStream mStream   = new MemoryStream();
            CryptoStream cStream   = null;

            try
            {
                var p = password.SecureStringToString();
                Rfc2898DeriveBytes crypto = new Rfc2898DeriveBytes(p, _salt);
                rijndael.IV  = crypto.GetBytes(rijndael.BlockSize / 8);
                rijndael.Key = crypto.GetBytes(rijndael.KeySize / 8);
                cStream      = new CryptoStream(mStream, rijndael.CreateDecryptor(), CryptoStreamMode.Write);
                cStream.Write(bytesBuff, 0, bytesBuff.Length);
                cStream.Dispose();
                var json = System.Text.Encoding.Unicode.GetString(mStream.ToArray());
                return(JObject.Parse(json));
            }
            catch (CryptographicException)
            {
                throw new NotAuthorizedWalletException(ErrorCodes.BadPassword);
            }
            catch (JsonReaderException)
            {
                throw new NotAuthorizedWalletException(ErrorCodes.BadPassword);
            }
            finally
            {
                rijndael.Dispose();
                mStream.Dispose();
            }
        }
Example #3
0
        /// <summary>
        /// AES加密
        /// </summary>
        /// <param name="plainStr">明文字符串</param>
        /// <returns>密文</returns>
        public static string AESEncrypt(string plainStr, string key, out string errorMessage)
        {
            byte[] bKey      = Encoding.UTF8.GetBytes(key.Replace("-", ""));
            byte[] bIV       = Encoding.UTF8.GetBytes(key.Substring(0, 16));
            byte[] byteArray = Encoding.UTF8.GetBytes(plainStr);
            errorMessage = "";
            Rijndael aes = Rijndael.Create();

            try
            {
                using (MemoryStream mStream = new MemoryStream())
                {
                    using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateEncryptor(bKey, bIV), CryptoStreamMode.Write))
                    {
                        cStream.Write(byteArray, 0, byteArray.Length);
                        cStream.FlushFinalBlock();
                        return(Convert.ToBase64String(mStream.ToArray()));
                    }
                }
            }
            catch (Exception ex)
            {
                errorMessage = ex.Message;
                return(null);
            }
            finally
            {
                aes.Clear();
                aes.Dispose();
                aes = null;
            }
        }
Example #4
0
 public void Dispose()
 {
     if (rijndael != null)
     {
         rijndael.Dispose();
     }
 }
        private static byte[] Decrypt(byte[] cipherData, byte[] key, byte[] iv)
        {
            MemoryStream ms = null;

            try
            {
                ms = new MemoryStream();
                Rijndael alg = null;
                try
                {
                    alg = Rijndael.Create();

                    alg.Key = key;
                    alg.IV  = iv;

                    CryptoStream cs = null;
                    try
                    {
                        cs = new CryptoStream(ms, alg.CreateDecryptor(), CryptoStreamMode.Write);

                        var result = ms;
                        ms = null;

                        cs.Write(cipherData, 0, cipherData.Length);
                        cs.Close();

                        cs = null;

                        return(result.ToArray());
                    }
                    finally
                    {
                        if (cs != null)
                        {
                            cs.Dispose();
                        }
                    }
                }
                finally
                {
                    if (alg != null)
                    {
                        alg.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                throw new CriptografiaException("Não foi possível efetuar a descriptografia.", ex);
            }
            finally
            {
                if (ms != null)
                {
                    ms.Dispose();
                }
            }
        }
Example #6
0
        /// <summary>
        /// Uses the Rijndael class to decrypt the application key file.
        /// </summary>
        /// <param name="filePath">Application key file path.</param>
        /// <param name="password">Password to decrypt the application key file.</param>
        /// <returns>The decrypted string.</returns>
        public static string DecryptKey(string filePath, string password)
        {
            FileInfo fi = new FileInfo(filePath);

            bool padding = false;

            if (DomMan.Cryptography.IsEncrypted(filePath) == true)
            {
                padding = true;
                RemoveFilePadding(fi.FullName);
            }

            FileStream fs = fi.OpenRead();

            byte[] salt = new byte[saltSize];

            fs.Read(salt, 0, saltSize);

            // Initialize the algorithm with salt.
            Rfc2898DeriveBytes keyGenerator = new Rfc2898DeriveBytes(password, salt);
            Rijndael           rijndael     = Rijndael.Create();

            rijndael.IV  = keyGenerator.GetBytes(rijndael.BlockSize / saltSize);
            rijndael.Key = keyGenerator.GetBytes(rijndael.KeySize / saltSize);

            CryptoStream cs = new CryptoStream(fs, rijndael.CreateDecryptor(), CryptoStreamMode.Read);

            keyGenerator.Dispose();
            rijndael.Dispose();

            string plaintext;

            try
            {
                using (StreamReader sr = new StreamReader(cs))
                {
                    plaintext = sr.ReadToEnd();
                }
            }
            catch (CryptographicException x)
            {
                fs.Close();
                if (padding == true)
                {
                    AddFilePadding(filePath);
                }
                return("CryptographicException\n\n" + x.Message);
            }

            if (padding == true)
            {
                AddFilePadding(fi.FullName);
            }

            return(plaintext);
        }
        private static byte[] Encrypt(byte[] clearData, byte[] key, byte[] iv)
        {
            MemoryStream ms = null;

            try
            {
                ms = new MemoryStream();

                Rijndael alg = null;
                try
                {
                    alg = Rijndael.Create();

                    alg.Key = key;
                    alg.IV  = iv;


                    CryptoStream cs = null;
                    try
                    {
                        cs = new CryptoStream(ms, alg.CreateEncryptor(), CryptoStreamMode.Write);

                        var result = ms;
                        ms = null;

                        cs.Write(clearData, 0, clearData.Length);
                        cs.Close();

                        cs = null;

                        return(result.ToArray());
                    }
                    finally
                    {
                        if (cs != null)
                        {
                            cs.Dispose();
                        }
                    }
                }
                finally
                {
                    if (alg != null)
                    {
                        alg.Dispose();
                    }
                }
            }
            finally
            {
                if (ms != null)
                {
                    ms.Dispose();
                }
            }
        }
 protected virtual void Dispose(bool disposing)
 {
     if (!disposedValue)
     {
         if (disposing)
         {
             rijndael.Dispose();
         }
         disposedValue = true;
     }
 }
        public void Encrypt(Stream clearData, Stream encryptedData)
        {
            EncryptException ee = null;

            if (ActivePrivateKey == null)
            {
                throw new PrivateKey.InvalidPrivateKeyException();
            }
            else
            {
                Rijndael     alg = null;
                CryptoStream cs  = null;
                try
                {
                    alg = Rijndael.Create();


                    alg.Key = ActivePrivateKey.Value;
                    alg.IV  = ActiveIV.Value;

                    cs = new CryptoStream(encryptedData, alg.CreateEncryptor(), CryptoStreamMode.Write);

                    clearData.CopyTo(cs);

                    cs.Close();
                }
                catch (Exception ex)
                {
                    ee = new EncryptException(ex);
                }
                finally
                {
                    if (cs != null)
                    {
                        cs.Dispose();
                        GC.SuppressFinalize(cs);
                        cs = null;
                    }

                    if (alg != null)
                    {
                        alg.Dispose();
                        GC.SuppressFinalize(alg);
                        alg = null;
                    }
                }
            }

            if (ee != null)
            {
                throw ee;
            }
        }
Example #10
0
        protected virtual void Dispose(bool disposing)
        {
            if (IsDisposed)
            {
                return;
            }

            IsDisposed = true;

            if (disposing)
            {
                _rijn?.Dispose();
            }
        }
Example #11
0
        // Token: 0x060000CF RID: 207 RVA: 0x00007C74 File Offset: 0x00005E74
        private byte[] iDecrypt(byte[] data, byte[] key, byte[] iv)
        {
            MemoryStream memoryStream = new MemoryStream();
            Rijndael     rijndael     = Rijndael.Create();

            rijndael.Key = key;
            rijndael.IV  = iv;
            CryptoStream cryptoStream = new CryptoStream(memoryStream, rijndael.CreateDecryptor(), CryptoStreamMode.Write);

            cryptoStream.Write(data, 0, data.Length);
            cryptoStream.Close();
            rijndael.Dispose();
            return(memoryStream.ToArray());
        }
Example #12
0
        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            lock (this)
            {
                if (!Disposed)
                {
                    Disposed = true;
                    GC.SuppressFinalize(this);

                    if (_csp != null)
                    {
                        _csp.Clear();
                        _csp.Dispose();
                        _csp = null;
                    }
                }
            }
        }
Example #13
0
        private bool disposedValue = false; // To detect redundant calls

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    // TODO: dispose managed state (managed objects).
                    _encryptor.Dispose();
                    _encryptorTransform.Dispose();
                    _decryptorTransform.Dispose();
                    _pdb.Dispose();
                }

                // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
                // TODO: set large fields to null.

                disposedValue = true;
            }
        }
Example #14
0
        // Con este método ciframos el texto que introduzca el usuario y lo devolvemos
        public static String CifrarTexto(String texto, byte[] clave)
        {
            // Instanciamos el Rijndael
            Rijndael cifradoRijn = Rijndael.Create();

            byte[] encriptado = null;
            byte[] salida     = null;
            try
            {
                // Asignamos en la clave del Rijndael la clave introducida por el usuario
                cifradoRijn.Key = clave;
                // Generamos un vector de inicialización
                cifradoRijn.GenerateIV();
                // Convertimos el texto introducido a un array de bytes
                byte[] entrada = Encoding.UTF8.GetBytes(texto);
                // Encriptamos el mensaje
                encriptado = cifradoRijn.CreateEncryptor().TransformFinalBlock(entrada, 0, entrada.Length);
                // Inicializamos un array de bytes con la longitud del mensaje encriptado y la longitud del vector de inicialización
                salida = new byte[cifradoRijn.IV.Length + encriptado.Length];
                // Copiamos el vector al principio del array salida
                cifradoRijn.IV.CopyTo(salida, 0);
                // Copiamos el mensaje encriptado en el array salida después del vector
                encriptado.CopyTo(salida, cifradoRijn.IV.Length);
            }
            catch (Exception)
            {
                throw new Exception("Error al cifrar los datos.");
            }
            finally
            {
                // Limpiamos el Rijndael
                cifradoRijn.Dispose();
                cifradoRijn.Clear();
            }
            // Convertimos el array de bytes salida a String
            String resultado = Encoding.Default.GetString(salida);

            // Devolvemos el resultado
            return(resultado);
        }
Example #15
0
        //Con este método usamos el mensaje cifrado y la clave introducida para descirar el mensaje
        public static String DescifrarTexto(byte[] entrada, byte[] clave)
        {
            // Instanciamos el Rijndael
            Rijndael cifradoRijn = Rijndael.Create();

            // Inicializamos un array temporal con la longitud del vector de inicialización
            byte[] arrayTemporal = new byte[cifradoRijn.IV.Length];
            // Inicializamos un array que tendrá la longitud del mensaje encriptado
            byte[] encriptado      = new byte[entrada.Length - cifradoRijn.IV.Length];
            String textodescifrado = String.Empty;

            try
            {
                // Asignamos la clave
                cifradoRijn.Key = clave;
                // Copiamos en el array temporal el vector de inicialización
                Array.Copy(entrada, arrayTemporal, arrayTemporal.Length);
                // Copiamos el mensaje sin el vector de inicialización en un array
                Array.Copy(entrada, arrayTemporal.Length, encriptado, 0, encriptado.Length);
                // Asignamos el vector de inicialización
                cifradoRijn.IV = arrayTemporal;
                // Desencriptamos el mensaje
                byte[] prueba = cifradoRijn.CreateDecryptor().TransformFinalBlock(encriptado, 0, encriptado.Length);
                // Convertimos el mensaje descifrado a String
                textodescifrado = Encoding.UTF8.GetString(prueba);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                // Limpiamos el Rijndael
                cifradoRijn.Dispose();
                cifradoRijn.Clear();
            }
            // Devolvemos el mensaje descifrado
            return(textodescifrado);
        }
Example #16
0
        /// <summary>
        /// 指定されたパスワード、元のファイル、出力先で暗号化及び復号を非同期的に行います
        /// </summary>
        /// <param name="password"></param>
        /// <param name="outfile"></param>
        /// <returns></returns>
        public virtual async Task WriteStreamAsync(string password, string readPath, string outPath, CancellationToken token)
        {
            try
            {
                switch (CryptoMode)
                {
                case CryptoMode.ENCRYPTION:    //暗号化
                    await FileEncryption(password, readPath, outPath + @"\" +  
                                         Path.GetFileName(readPath) + ".safer", token);

                    break;

                case CryptoMode.DENCRYPTION:    //復号
                    await FileDecryption(password, readPath, outPath + @"\" +
                                         Path.GetFileName(readPath).Replace(".safer", ""), token);

                    break;
                }
            }
            catch (OperationCanceledException)
            {
                MessageBox.Show("操作を中止しました。", "確認", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
            catch (CryptographicException)
            {
                if (token.IsCancellationRequested)
                {
                    MessageBox.Show("操作を中止しました。", "確認", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); return;
                }
                MessageBox.Show("パスワードが間違っていませんか?", "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                rijndael.Dispose();
                argon2?.Dispose();
            }
        }
Example #17
0
 public void Dispose()
 {
     _dynamicRijndael?.Dispose();
 }
Example #18
0
 public void Dispose()
 {
     rijndael.Dispose();
 }
Example #19
0
File: AES.cs Project: onixion/MAD
 public void Dispose()
 {
     _aes.Dispose();
     _pdb.Dispose();
     _gen.Dispose();
 }
Example #20
0
 public virtual void Dispose()
 {
     Stream?.Dispose();
     _baseStream?.Dispose();
     _algorithm?.Dispose();
 }
Example #21
0
 public static void Dispose()
 {
     _rijndael.Dispose();
 }
Example #22
0
 /// <summary>
 /// Releases unmanaged and - optionally - managed resources.
 /// </summary>
 public void Dispose()
 {
     _rijAlg.Dispose();
 }
Example #23
0
        // encrypt specified file
        public override void EncryptData(string path)
        {
            // init classes
            Messages       messages   = new Messages();
            EncryptDecrypt decrypt    = new Decrypt();
            Validation     validation = new Validation();
            Method         methods    = new Method();

            // variables
            byte[] secretKey = null; byte[] IV = null;;
            string elapsedTime, directory, fileName, filePath, lastItem;
            bool   firstRun = true, error = false, lastRun = false;

            // new list
            List <string> fileList = new List <string>();

            // add files to list if directory, else add only the path itself
            if (validation.ValidateDirectory(path))
            {
                fileList = new List <string>(methods.GetFiles(path));
            }
            else
            {
                fileList.Add(path);
            }

            // get last item in fileList
            lastItem = fileList[(fileList.Count - 1)];

            // new stopwatch
            Stopwatch stopWatch = new Stopwatch();

            stopWatch.Start();

            try {
                // encrypt all files in fileList
                foreach (string file in fileList)
                {
                    // set and reset variables
                    byte[]             encryptedBytes = null, fileAsBytes = null, extensionAsBytes = null;
                    IEnumerable <byte> fullBytes = null, plainBytes = null;
                    string             extension = null;

                    // if last iteration
                    if (file.Equals(lastItem))
                    {
                        lastRun = true;
                    }

                    // read file
                    fileAsBytes = File.ReadAllBytes(file);

                    // extension to be appended to file
                    extension = Path.GetExtension(file);

                    // append extension to file
                    extensionAsBytes = Encoding.ASCII.GetBytes(extension);
                    plainBytes       = fileAsBytes.Concat(extensionAsBytes);
                    fileAsBytes      = plainBytes.ToArray();

                    // create rijndael object
                    Rijndael rijndael = Rijndael.Create();

                    // generate only one key/IV for the current instance
                    if (firstRun)
                    {
                        secretKey = Encoding.ASCII.GetBytes(methods.generateKey(16)); IV = Encoding.ASCII.GetBytes(methods.generateKey(16)); firstRun = false; Console.WriteLine(Environment.NewLine);
                    }

                    // set values
                    rijndael.Key     = secretKey;
                    rijndael.Mode    = CipherMode.CBC;
                    rijndael.Padding = PaddingMode.PKCS7;
                    rijndael.IV      = IV;

                    // open streams with data
                    MemoryStream memoryStream = new MemoryStream();
                    CryptoStream cryptoStream = new CryptoStream(memoryStream, rijndael.CreateEncryptor(), CryptoStreamMode.Write);

                    // progress notification
                    Console.SetCursorPosition(0, Console.CursorTop - 1);
                    methods.ClearCurrentConsoleLine();
                    if (!lastRun)
                    {
                        messages.ProcessMessage(file);
                    }
                    else
                    {
                        messages.ProcessCompleteMessage();
                    }

                    // encrypt
                    cryptoStream.Write(fileAsBytes, 0, fileAsBytes.Length);
                    cryptoStream.Close();

                    // append IV to content
                    fullBytes      = memoryStream.ToArray().Concat(IV).ToArray();
                    encryptedBytes = fullBytes.ToArray();
                    memoryStream.Close();

                    // write encrypted content to file
                    System.IO.File.WriteAllBytes(file, encryptedBytes);

                    // progress notification
                    Console.SetCursorPosition(0, Console.CursorTop + 1);
                    methods.ClearCurrentConsoleLine();
                    if (!lastRun)
                    {
                        messages.EncryptProgressMessage(file);
                    }
                    else
                    {
                        messages.EncryptionCompleteMessage();
                    }

                    // set file extension to .rip
                    File.Move(file, Path.ChangeExtension(file, ".rip"));

                    // clear resources
                    rijndael.Dispose();
                }
            } catch (Exception E) {
                error = true;
                if (E is UnauthorizedAccessException)
                {
                    messages.AuthMessage();
                }
                else if (E is CryptographicException)
                {
                    messages.CryptoError();
                }
                else
                {
                    messages.UnexpectedError();
                }
            }

            // print if no error was encountered
            if (!error)
            {
                messages.FileToRipMessage();
            }

            // stop stopwatch
            stopWatch.Stop();

            // print elapsed time
            TimeSpan ts = stopWatch.Elapsed;

            elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                                        ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
            messages.TimeMessage(elapsedTime);

            // catch file/directory creation/write errors
            try {
                // create directory if it does not already exist then add file containing key
                directory = Path.GetPathRoot(Environment.GetFolderPath(Environment.SpecialFolder.System)) + "autocryptKeyStorage";
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }
                fileName = DateTime.Now.ToString("HH_mm_ss") + "_keyKeeper.key";
                filePath = directory + "\\" + fileName;
                File.WriteAllText(Path.Combine(directory, fileName), methods.WarpKey(Encoding.ASCII.GetString(secretKey)));

                // print if no error was encountered
                if (!error)
                {
                    messages.SuccessMessage();
                }

                // print if key is not empty or null
                if (!Encoding.ASCII.GetString(secretKey).Equals("") || !Encoding.ASCII.GetString(secretKey).Equals(null))
                {
                    // provide user with decryption key
                    messages.KeyMessage(methods.WarpKey(Encoding.ASCII.GetString(secretKey)), filePath);
                }
            } catch (Exception E) {
                // if matrix is null or if unexpected error
                if (E is ArgumentNullException)
                {
                    messages.NoKeyError();
                }
                else
                {
                    messages.UnexpectedError();
                }
            }

            // countdown until program will close
            methods.Countdown(30);
        }
 public void Dispose()
 {
     Encryptor.Dispose();
     Decryptor.Dispose();
     RijObject.Dispose();
 }
Example #25
0
 public void Dispose()
 {
     _encryptor.Dispose();
     _decryptor.Dispose();
     _rijObject.Dispose();
 }
Example #26
0
        static void Main(string[] args)
        {
            try
            {
                //Для подключения к SQLite, создается один раз
                SQLiteFactory factory = (SQLiteFactory)DbProviderFactories.GetFactory("System.Data.SQLite");

                Console.WriteLine("Сгенерировать новую БД SQLite? (y/n)");
                ConsoleKeyInfo keyInfo = Console.ReadKey(false);
                if (keyInfo.KeyChar == 'y' || keyInfo.KeyChar == 'у' || keyInfo.KeyChar == 'д')
                {
                    //генерация новой БД
                    Console.WriteLine("Запись данных в БД SQLite");
                    WriteSQLite(factory);
                    Console.WriteLine("Нажмите любую клавишу для продолжения...");
                    Console.ReadKey(true);
                }

                //чтение БД
                Console.WriteLine("Чтение данных из БД SQLite");
                List <FullRow> rows     = ReadSQLite(factory);
                string         str_data = JsonConvert.SerializeObject(rows);

                // подключаемся к удаленному хосту
                IPEndPoint ipPoint = new IPEndPoint(IPAddress.Parse(address), port);
                Socket     socket  = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.Connect(ipPoint);

                Console.WriteLine("Шифрование данных");

                // получаем публичный ключ RSA
                byte[]        data_rsa   = new byte[2048]; // буфер для ответа
                int           bytes      = socket.Receive(data_rsa, data_rsa.Length, 0);
                string        serial_rsa = Encoding.Unicode.GetString(data_rsa, 0, bytes);
                RSAParameters rsaParams  = JsonConvert.DeserializeObject <RSAParameters>(serial_rsa);

                //шифруем симметричным шифрованием данные
                Rijndael cipher    = Rijndael.Create();
                string   encrypted = Encrypt(str_data, cipher.Key, cipher.IV);
                //string decrypted = Decrypt(encrypted, cipher.Key, cipher.IV);

                //шифруем RSA ключ симметричного шифрования
                byte[] encrypted_key = RSAEncrypt(cipher.Key, rsaParams);
                //byte[] decrypted_key = RSAEncrypt(encrypted_key, RSA.ExportParameters(true));

                //удаляем из памяти экземпляр класса симметричного шифрования
                byte[] iv = cipher.IV;
                cipher.Dispose();

                Console.WriteLine("Пересылка данных");

                //отправляем зашифрованный ключ симметричного шифрования
                socket.Send(encrypted_key);

                // получаем подтверждение
                byte[] data = new byte[256]; // буфер для ответа
                bytes = socket.Receive(data, data.Length, 0);
                string answer = Encoding.Unicode.GetString(data, 0, bytes);
                if (!answer.Equals("ready"))
                {
                    throw new Exception("Получены некорректные данные");
                }

                //отправляем инициализующий вектор симметричного шифрования в открытом виде
                socket.Send(iv);

                //получаем подтверждение
                data   = new byte[256]; // буфер для ответа
                bytes  = socket.Receive(data, data.Length, 0);
                answer = Encoding.Unicode.GetString(data, 0, bytes);
                if (!answer.Equals("ready"))
                {
                    throw new Exception("Получены некорректные данные");
                }

                //отправляем размер данных
                byte[] data_rows = Encoding.Unicode.GetBytes(encrypted);
                string message   = "отправка " + data_rows.Length;
                data = Encoding.Unicode.GetBytes(message);
                socket.Send(data);

                // получаем подтверждение
                data   = new byte[256]; // буфер для ответа
                bytes  = socket.Receive(data, data.Length, 0);
                answer = Encoding.Unicode.GetString(data, 0, bytes);
                if (!answer.Equals("ready"))
                {
                    throw new Exception("Получены некорректные данные");
                }

                //отправляем зашифрованные данные
                socket.Send(data_rows);

                // получаем количество доставленных байт
                data   = new byte[256]; // буфер для ответа
                bytes  = socket.Receive(data, data.Length, 0);
                answer = Encoding.Unicode.GetString(data, 0, bytes);

                //отображаем отчет
                string[] res = answer.Split(' ');
                if (res.Length != 2 || !res[0].Equals("доставлено"))
                {
                    throw new Exception("Получены некорректные данные");
                }
                int count = int.Parse(res[1]);
                Console.WriteLine("Отправлено {0} байт.\nДоставлено {1} байт", data_rows.Length, count);

                // закрываем сокет
                socket.Shutdown(SocketShutdown.Both);
                socket.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Произошла ошибка {0}. Приложение будет закрыто.", ex.Message);
            }

            Console.WriteLine("Нажмите любую клавишу для выхода...");
            Console.ReadKey(true);
            Environment.Exit(0);
        }
Example #27
0
        // decrypt specified file
        public override void DecryptData(string path)
        {
            // init classes
            Messages   messages   = new Messages();
            Input      input      = new Input();
            Validation validation = new Validation();
            Method     methods    = new Method();

            // variables
            string userInput = null, lastItem;

            byte[] IV = null;
            bool   error = false, lastRun = false;

            // validate length of key
            messages.AccessMessage();
            userInput = input.ReadInput();
            while (!validation.ValidateKey(userInput))
            {
                messages.KeyError(); userInput = input.ReadInput();
            }
            Console.WriteLine(Environment.NewLine);

            // if userinput is a path read specified file as string and set userInput to content string
            if (File.Exists(userInput))
            {
                // reuse key length check aswell as check if extension is .key
                while (!validation.ValidateKey(userInput) && Path.GetExtension(userInput).Equals(".key"))
                {
                    messages.KeyError(); userInput = input.ReadInput();
                }
                userInput = File.ReadAllText(userInput);
            }

            // new list
            List <string> fileList = new List <string>();

            // add files to list if directory, else add only the path itself
            if (validation.ValidateDirectory(path))
            {
                fileList = new List <string>(methods.GetFiles(path));
            }
            else
            {
                fileList.Add(path);
            }

            // get last item in fileList
            lastItem = fileList[(fileList.Count - 1)];

            // new stopwatch
            Stopwatch stopWatch = new Stopwatch();

            stopWatch.Start();

            try
            {
                // encrypt all files in fileList
                foreach (string file in fileList)
                {
                    // set and reset variables
                    byte[] decryptedBytes = null, encryptedBytes = null;
                    string extension      = null;

                    // if last iteration
                    if (file.Equals(lastItem))
                    {
                        lastRun = true;
                    }

                    // read file as bytes
                    encryptedBytes = File.ReadAllBytes(file);

                    // get IV from file
                    IV = Encoding.ASCII.GetBytes(Encoding.UTF8.GetString(encryptedBytes).Substring(Encoding.UTF8.GetString(encryptedBytes).Length - 16));

                    // remove IV from filecontent
                    encryptedBytes = encryptedBytes.Take(encryptedBytes.Count() - 16).ToArray();

                    // create rijndael object
                    Rijndael rijndael = Rijndael.Create();

                    // set values
                    rijndael.Key     = Encoding.ASCII.GetBytes(methods.CorrectKey(userInput.Trim()));
                    rijndael.Mode    = CipherMode.CBC;
                    rijndael.Padding = PaddingMode.PKCS7;
                    rijndael.IV      = IV;

                    // new streams
                    MemoryStream memoryStream = new MemoryStream();
                    CryptoStream cryptoStream = new CryptoStream(memoryStream, rijndael.CreateDecryptor(), CryptoStreamMode.Write);

                    // progress notification
                    Console.SetCursorPosition(0, Console.CursorTop - 1);
                    methods.ClearCurrentConsoleLine();
                    if (!lastRun)
                    {
                        messages.ProcessMessage(file);
                    }
                    else
                    {
                        messages.ProcessCompleteMessage();
                    }

                    // decrypt
                    cryptoStream.Write(encryptedBytes, 0, encryptedBytes.Length);
                    cryptoStream.Close();

                    decryptedBytes = memoryStream.ToArray();
                    memoryStream.Close();

                    // obtain true file extension and remove from decrypted bytes
                    for (int i = decryptedBytes.Count() - 1; i >= 0; i--)
                    {
                        extension += Convert.ToChar(decryptedBytes[i]);
                        if (extension.Contains("."))
                        {
                            break;
                        }
                    }

                    // reverse extension to obtain actual extension
                    extension = new string(extension.Reverse().ToArray());

                    // remove true file extension from decrypted bytes
                    decryptedBytes = decryptedBytes.Take(decryptedBytes.Count() - extension.Length).ToArray();

                    // write decrypted content to file
                    System.IO.File.WriteAllBytes(file, decryptedBytes);

                    // progress notification
                    Console.SetCursorPosition(0, Console.CursorTop + 1);
                    methods.ClearCurrentConsoleLine();
                    if (!lastRun)
                    {
                        messages.DecryptProgressMessage(file);
                    }
                    else
                    {
                        messages.DecryptionCompleteMessage();
                    }

                    // revert to true file extension
                    File.Move(file, Path.ChangeExtension(file, extension));

                    // clear resources
                    rijndael.Dispose();
                }
            }
            catch (Exception E) {
                error = true;
                if (E is UnauthorizedAccessException)
                {
                    messages.AuthMessage();
                }
                else if (E is CryptographicException)
                {
                    messages.CryptoError();
                }
                else
                {
                    messages.UnexpectedError();
                }
            }

            // print if no error was encountered
            if (!error)
            {
                messages.FileToOriginalMessage();
            }

            // stop stopwatch
            stopWatch.Stop();

            // print elapsed time
            TimeSpan ts          = stopWatch.Elapsed;
            string   elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                                                 ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);

            messages.TimeMessage(elapsedTime);

            // print if no error was encountered
            if (!error)
            {
                messages.DecryptMessage();
            }

            // countdown until program will close
            methods.Countdown(30);
        }
Example #28
0
        /// <summary>
        /// Saves the current XML data to the specified file. All XML data in the file will be overwritten.
        /// </summary>
        /// <param name="strFilePath"> FilePath to save to. If "" is passed in for strFilePath, then m_strXMLFileName
        ///  will be used for the path. Otherwise the default file name will be appended to the strFilePath</param>
        /// <returns>Whether or not the save was successful.</returns>
        // Revision History
        // MM/DD/YY who Version Issue# Description
        // -------- --- ------- ------ ---------------------------------------------
        // 05/27/08 jrf 1.50.28        Created
        //
        public override bool SaveSettings(string strFilePath)
        {
            bool         bReturn             = false;
            string       strTemp             = strFilePath;
            XmlDocument  xmldocTemp          = new XmlDocument();
            MemoryStream DecryptedStream     = new MemoryStream();
            FileStream   EncryptedStream     = null;
            Rijndael     EncryptionAlgorithm = null;

            try
            {
                if (1 > strFilePath.Length)
                {
                    strTemp = m_strXMLFileName;
                }
                else
                {
                    strTemp = strFilePath;
                }

                EncryptedStream     = new FileStream(strTemp, FileMode.Create);
                EncryptionAlgorithm = Rijndael.Create();

                SecureDataStorage DataStorage = new SecureDataStorage(SecureDataStorage.DEFAULT_LOCATION);

                //Set the key and IV properties
                EncryptionAlgorithm.Key = DataStorage.RetrieveSecureData(SecureDataStorage.REPLICA_KEY_ID);
                EncryptionAlgorithm.IV  = DataStorage.RetrieveSecureData(SecureDataStorage.REPLICA_IV_ID);

                Save(DecryptedStream);

                //Need to rewind stream before encrypting
                DecryptedStream.Position = 0;

                //Encrypt the data and write to the file
                Encryption.EncryptData(EncryptionAlgorithm, DecryptedStream, EncryptedStream);

                if (null != xmldocTemp)
                {
                    //Need to rewind stream before loading
                    DecryptedStream.Position = 0;

                    xmldocTemp.Load(DecryptedStream);

                    if (null != xmldocTemp.SelectSingleNode(DEFAULT_XML_ROOT_NODE))
                    {
                        bReturn = true;
                    }

                    xmldocTemp = null;
                }
            }
            catch
            {
                bReturn = false;
            }
            finally
            {
                if (null != EncryptionAlgorithm)
                {
                    EncryptionAlgorithm.Dispose();
                }

                if (null != DecryptedStream)
                {
                    DecryptedStream.Close();
                }

                if (null != EncryptedStream)
                {
                    EncryptedStream.Close();
                }
            }

            return(bReturn);
        }