Beispiel #1
0
 internal CryptoServiceProvider(EnumCryptoProvider Alg, EnumCryptoAction Action)
 {
     _algorithm = Alg;
     _Action    = Action;
 }
Beispiel #2
0
        public void CifrarDescifrarArchivo(string InFileName, string OutFileName, EnumCryptoAction EnumAction)
        {
            if (!File.Exists(InFileName))
            {
                throw new Exception("No se ha encontrado el archivo.");
            }
            try
            {
                if (_key != null && _IV != null)
                {
                    FileStream fsIn  = new FileStream(InFileName, FileMode.Open, FileAccess.Read);
                    FileStream fsOut = new FileStream(OutFileName, FileMode.OpenOrCreate, FileAccess.Write);
                    fsOut.SetLength(0);

                    byte[] _bytKey       = MakeKeyByteArray();
                    byte[] _bytIV        = MakeIVByteArray();
                    byte[] _bytebuffer   = new byte[4096];
                    long   fileLength    = fsIn.Length;
                    long   bytesProcesed = 0;
                    int    bytesInBlock  = 0;


                    CryptoServiceProvider _cryptoProvider = new CryptoServiceProvider((CryptoServiceProvider.EnumCryptoProvider)_algorithm, (CryptoServiceProvider.EnumCryptoAction)EnumAction);

                    ICryptoTransform _transform    = _cryptoProvider.GetServiceProvider(_bytKey, _bytIV);
                    CryptoStream     _cryptoStream = null;
                    switch (EnumAction)
                    {
                    case EnumCryptoAction.Encrypt:
                        _cryptoStream = new CryptoStream(fsOut, _transform, CryptoStreamMode.Write);
                        break;

                    case EnumCryptoAction.Desencrypt:
                        _cryptoStream = new CryptoStream(fsOut, _transform, CryptoStreamMode.Write);
                        break;
                    }

                    while (bytesProcesed < fileLength)
                    {
                        bytesInBlock = fsIn.Read(_bytebuffer, 0, 4096);
                        _cryptoStream.Write(_bytebuffer, 0, bytesInBlock);
                        bytesProcesed += Convert.ToInt64(bytesInBlock);
                    }

                    if (_cryptoStream != null)
                    {
                        _cryptoStream.Close();
                    }
                    fsIn.Close();
                    fsOut.Close();
                }
                else
                {
                    throw new Exception("Error al inicializar la clave y el vector.");
                }
            }
            catch
            {
                throw;
            }
        }