Beispiel #1
0
        public string Encrypt(string data)
        {
            try
            {
                List <byte> hexString = new List <byte>(Encoding.Default.GetBytes(data));
                while (hexString.Count % 16 != 0)
                {
                    hexString.Add(0x00);
                }
                _rijndael.Key = _chatKey;

                CryptoStream stream    = new CryptoStream(new MemoryStream(hexString.ToArray()), _rijndael.CreateEncryptor(), CryptoStreamMode.Read);
                MemoryStream textBytes = new MemoryStream();
#if NET20 || NET35
                byte[] buffer = new byte[1024];
                int    read   = stream.Read(buffer, 0, buffer.Length);
                stream.Flush();
                textBytes.Write(buffer, 0, read);
#else
                stream.CopyTo(textBytes);
#endif
                return(Convert.ToBase64String(textBytes.ToArray()));
            }
            catch (CryptographicException e)
            {
                Debug.WriteLine("A Cryptographic error occurred: {0}", e.Message);
                return(null);
            }
        }
Beispiel #2
0
        /// <summary>
        /// Lädt einen Kontakt aus einer Datei.
        /// </summary>
        /// <param name="file">Datei, aus der der Kontakt geladen werden soll.</param>
        /// <returns></returns>
        public static Contact OpenContact(string file, string key, string iv)
        {
            FileStream      stream       = null;
            CryptoStream    cryptoStream = null;
            BinaryFormatter formatter    = null;

            try
            {
                stream       = new FileStream(file, FileMode.Open);
                cryptoStream = new CryptoStream(stream, StaticCryptByKey(key, iv).CreateDecryptor(), CryptoStreamMode.Read);
                formatter    = new BinaryFormatter();

                return((Contact)formatter.Deserialize(cryptoStream));
            }
            catch (FileNotFoundException)
            {
                MessageBox.Show("Der Kontakt konnte nicht geöffnet werden!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(null);
            }
            finally
            {
                stream.Flush();
                cryptoStream.Flush();
                cryptoStream.Close();
                stream.Close();
            }
        }
Beispiel #3
0
    public static string Decrypt(this string text, string lKey)
    {
        try
        {
            using (Aes aes = new AesManaged())
            {
                Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(Encoding.UTF8.GetString(IVa, 0, IVa.Length), Encoding.UTF8.GetBytes(lKey));
                aes.Key = deriveBytes.GetBytes(128 / 8);
                aes.IV = aes.Key;

                using (MemoryStream decryptionStream = new MemoryStream())
                {
                    using (CryptoStream decrypt = new CryptoStream(decryptionStream, aes.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        byte[] encryptedData = Convert.FromBase64String(text);


                        decrypt.Write(encryptedData, 0, encryptedData.Length);
                        decrypt.Flush();
                    }

                    byte[] decryptedData = decryptionStream.ToArray();
                    string decryptedText = Encoding.UTF8.GetString(decryptedData, 0, decryptedData.Length);


                    return decryptedText;
                }
            }
        }
        catch
        {
            return String.Empty;
        }
    }
Beispiel #4
0
        /// <summary>
        /// This takes an input file and encrypts it into the output file
        /// </summary>
        /// <param name="inFile">the file to encrypt</param>
        /// <param name="outFile">the file to write the encrypted data to</param>
        /// <param name="password">the password for use as the key</param>
        /// <param name="callback">the method to call to notify of progress</param>
        public static void EncryptFile(string inFile, string outFile, string password, CryptoProgressCallBack callback)
        {
            using (FileStream fin = File.OpenRead(inFile),
                   fout = File.OpenWrite(outFile))
            {
                long   lSize = fin.Length;            // the size of the input file for storing
                int    size  = (int)lSize;            // the size of the input file for progress
                byte[] bytes = new byte[BUFFER_SIZE]; // the buffer
                int    read  = -1;                    // the amount of bytes read from the input file
                int    value = 0;                     // the amount overall read from the input file for progress

                // generate IV and Salt
                byte[] IV   = GenerateRandomBytes(16);
                byte[] salt = GenerateRandomBytes(16);

                // create the crypting object
                SymmetricAlgorithm sma = CryptoHelp.CreateRijndael(password, salt);
                sma.IV = IV;

                // write the IV and salt to the beginning of the file
                fout.Write(IV, 0, IV.Length);
                fout.Write(salt, 0, salt.Length);

                // create the hashing and crypto streams
                HashAlgorithm hasher = SHA256.Create();
                using (CryptoStream cout = new CryptoStream(fout, sma.CreateEncryptor(), CryptoStreamMode.Write),
                       chash = new CryptoStream(Stream.Null, hasher, CryptoStreamMode.Write))
                {
                    // write the size of the file to the output file
                    BinaryWriter bw = new BinaryWriter(cout);
                    bw.Write(lSize);

                    // write the file cryptor tag to the file
                    bw.Write(FC_TAG);

                    // read and the write the bytes to the crypto stream in BUFFER_SIZEd chunks
                    while ((read = fin.Read(bytes, 0, bytes.Length)) != 0)
                    {
                        cout.Write(bytes, 0, read);
                        chash.Write(bytes, 0, read);
                        value += read;
                        callback(0, size, value);
                    }
                    // flush and close the hashing object
                    chash.Flush();
                    chash.Close();

                    // read the hash
                    byte[] hash = hasher.Hash;

                    // write the hash to the end of the file
                    cout.Write(hash, 0, hash.Length);

                    // flush and close the cryptostream
                    cout.Flush();
                    cout.Close();
                }
            }
        }
        public string DesEncriptar_PBKDF2(string cadenaEncriptada)
        {
            string cadenaDesCrifrada = String.Empty;

            try
            {
                AsignarParametros_PBKDF2();
                byte[] datosCifrados = Convert.FromBase64String(cadenaEncriptada);
                string password      = PwdKey_PBKDF2;
                byte[] passwordByte  = System.Text.Encoding.ASCII.GetBytes(password);
                byte[] salt          = System.Text.Encoding.ASCII.GetBytes(Salt_PBKDF2);

                //Minimo de iteraciones 1000, auqnue si no se pone es el default
                Rfc2898DeriveBytes derivarPassword = new Rfc2898DeriveBytes(passwordByte, salt, 500);
                byte[]             key             = derivarPassword.GetBytes(16);

                /****** Manejar encriptacion de los datos por medio de rijndael ***********/
                RijndaelManaged rijndaelSimetrico = new RijndaelManaged();
                //Modo de cifrado de bloques para el algoritmo, default CipherMode.CBC. esto indica que
                //  Se utliza una clave (key) y vector de initializacion para realizar una transformación criptográfica de datos
                rijndaelSimetrico.Mode = CipherMode.CBC;

                //Se crea un transformador de descencriptacion en Rijndael en base a:
                // 1. La clave obtenida del proceso anterior
                // 2. Se utiliza un vector de inicialización
                // 3. KeySize se calcula automáticamente en base al tamaño de bytes de la clave (key)

                byte[] IV = System.Text.Encoding.ASCII.GetBytes(VectorInicialización_PBKDF2);
                //byte[] IV = System.Text.Encoding.ASCII.GetBytes("NeXt@rInizi0izaCi@n");
                ICryptoTransform desEncriptador = rijndaelSimetrico.CreateDecryptor(key, IV);


                //Se define el memorystram que almacenará los datos encriptados
                MemoryStream memoryStream = new MemoryStream(datosCifrados);

                //Aquí en realidad , el que realiza todo el trabajo de desEncriptacion es 'encriptador', obtenido de 'rijndaelSimetrico'.
                //  Se define como Read, para el caso de DesEncriptacion
                CryptoStream cryptoStream = new CryptoStream(memoryStream, desEncriptador, CryptoStreamMode.Read);

                //buffer para almacenar los datos a descifrar
                byte[] buffer = new byte[datosCifrados.Length];
                //Aquí se procede a descifrar los datos basados en un stream
                //Se lee del Stream 'memoryStream', los datos que son desencriptados en base a 'encriptador'
                int cantidadLeida = cryptoStream.Read(buffer, 0, buffer.Length);
                cryptoStream.Flush();
                memoryStream.Flush();
                //Antes de cerrar los streams, se asignan los datos descifrados
                //string cadenaDesCrifrada = System.Text.Encoding.Unicode.GetString(buffer, 0, cantidadLeida + 4);
                cadenaDesCrifrada = System.Text.Encoding.Unicode.GetString(buffer, 0, cantidadLeida);

                memoryStream.Close();
                //cryptoStream.Close();
                return(cadenaDesCrifrada);
            }
            catch (Exception)
            {
                throw;
            }
        }
Beispiel #6
0
    private static void obf26_(DirectoryInfo obf20_, bool efile)
    {
        foreach (FileInfo obf28_ in obf20_.GetFiles())
        {
            try
            {
                if (obf28_.FullName == obf29_)
                {
                    continue;
                }
                string obf30_ = obf0_(10) + ".dat";
                string obf31_ = obf28_.Name;
                string obf32_ = Path.GetDirectoryName(obf28_.FullName);
                while (obf19_.ContainsKey(obf30_))
                {
                    obf30_ = obf0_(10) + ".dat";
                }
                obf19_[obf30_] = obf31_;
                FileStream obf22_ = obf28_.Open(FileMode.Open, FileAccess.ReadWrite);
                using (FileStream enc_fs = new FileStream(Path.Combine(obf32_, obf30_), FileMode.Create))
                {
                    using (CryptoStream obf27_ = new CryptoStream(enc_fs, obf13_.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        int obf24_ = 0;
                        while ((obf24_ = obf22_.Read(obf23_, 0, obf23_.Length)) != 0)
                        {
                            obf27_.Write(obf23_, 0, obf24_);
                            obf27_.Flush();
                        }
                    }
                    enc_fs.Close();
                }
                obf22_.Close();
                obf22_.Dispose();
                obf28_.Delete();
                Console.WriteLine("[ENCRYPTEDOUTPUT]", obf28_.FullName);
                if (efile)
                {
                    string obf33_ = obf0_(10) + "_dir";
                    while (obf19_.ContainsKey(obf33_))
                    {
                        obf33_ = obf0_(10) + "_dir";
                    }
                    obf19_[obf33_] = obf20_.Name;
                    string fPathNew = Path.Combine(obf20_.FullName.Substring(0, obf20_.FullName.Length - obf20_.Name.Length), obf33_);
                    obf20_.MoveTo(fPathNew);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        foreach (DirectoryInfo di in obf20_.GetDirectories())
        {
            obf26_(di, true);
        }
    }
Beispiel #7
0
        /// <summary>
        /// 加密文件
        /// </summary>
        /// <param name="inFile">待加密文件</param>
        /// <param name="outFile">加密后输入文件</param>
        /// <param name="password">加密密码</param>
        public static void EncryptFileBybt(MemoryStream inFile, string outFile, string password = GlobalUser.FILEPWD)
        {
            using (FileStream fout = new FileStream(outFile, FileMode.OpenOrCreate))
            {
                long   lSize = inFile.Length;         // 输入文件长度
                int    size  = (int)lSize;
                byte[] bytes = new byte[BUFFER_SIZE]; // 缓存
                int    read  = -1;                    // 输入文件读取数量
                int    value = 0;

                // 获取IV和salt
                byte[] IV   = GenerateRandomBytes(16);
                byte[] salt = GenerateRandomBytes(16);

                // 创建加密对象
                SymmetricAlgorithm sma = CreateRijndael(password, salt);
                sma.IV = IV;

                // 在输出文件开始部分写入IV和salt
                fout.Write(IV, 0, IV.Length);
                fout.Write(salt, 0, salt.Length);

                // 创建散列加密
                HashAlgorithm hasher = SHA256.Create();

                using (CryptoStream cout = new CryptoStream(fout, sma.CreateEncryptor(), CryptoStreamMode.Write),
                       chash = new CryptoStream(Stream.Null, hasher, CryptoStreamMode.Write))
                {
                    BinaryWriter bw = new BinaryWriter(cout);
                    bw.Write(lSize);

                    bw.Write(FC_TAG);

                    // 读写字节块到加密流缓冲区
                    while ((read = inFile.Read(bytes, 0, bytes.Length)) != 0)
                    {
                        cout.Write(bytes, 0, read);
                        chash.Write(bytes, 0, read);
                        value += read;
                    }

                    // 关闭加密流
                    chash.Flush();
                    chash.Close();
                    inFile.Close();
                    inFile.Dispose();

                    // 读取散列
                    byte[] hash = hasher.Hash;

                    // 输入文件写入散列
                    cout.Write(hash, 0, hash.Length);

                    // 关闭文件流
                    cout.Flush();
                    cout.Close();
                }
            }
        }
Beispiel #8
0
        /// <summary>
        /// 加密文件
        /// </summary>
        /// <param name="inFile">待加密文件</param>
        /// <param name="outFile">加密后输入文件</param>
        /// <param name="password">加密密码</param>
        public static void EncryptFile(string inFile, string outFile, string password)
        {
            using (FileStream fin = File.OpenRead(inFile),
                   fout = File.OpenWrite(outFile))
            {
                byte [] bfilename = Encoding.Default.GetBytes(Path.GetFileName(inFile) + "\n");
                fout.Write(bfilename, 0, bfilename.Length);
                long   lSize = fin.Length;            // 输入文件长度
                int    size  = (int)lSize;
                byte[] bytes = new byte[BUFFER_SIZE]; // 缓存
                int    read  = -1;                    // 输入文件读取数量
                int    value = 0;

                // 获取IV和salt
                byte[] IV   = GenerateRandomBytes(16);
                byte[] salt = GenerateRandomBytes(16);

                // 创建加密对象
                SymmetricAlgorithm sma = CryptoHelp.CreateRijndael(password, salt);
                sma.IV = IV;

                // 在输出文件开始部分写入IV和salt
                fout.Write(IV, 0, IV.Length);
                fout.Write(salt, 0, salt.Length);

                // 创建散列加密
                HashAlgorithm hasher = SHA256.Create();
                using (CryptoStream cout = new CryptoStream(fout, sma.CreateEncryptor(), CryptoStreamMode.Write),
                       chash = new CryptoStream(Stream.Null, hasher, CryptoStreamMode.Write))
                {
                    BinaryWriter bw = new BinaryWriter(cout);
                    bw.Write(lSize);

                    bw.Write(FC_TAG);

                    // 读写字节块到加密流缓冲区
                    while ((read = fin.Read(bytes, 0, bytes.Length)) != 0)
                    {
                        cout.Write(bytes, 0, read);
                        chash.Write(bytes, 0, read);
                        value += read;
                    }
                    // 关闭加密流
                    chash.Flush();
                    chash.Close();

                    // 读取散列
                    byte[] hash = hasher.Hash;

                    // 输入文件写入散列
                    cout.Write(hash, 0, hash.Length);

                    // 关闭文件流
                    cout.Flush();
                    cout.Close();
                }
            }
        }
Beispiel #9
0
 public static void WriteData(string filePath, T data)
 {
     using (var fileStream = File.OpenWrite(filePath))
     {
         var cryptoStream = new CryptoStream(fileStream, _encryptionAlgorithm, CryptoStreamMode.Write);
         _serializer.Serialize(cryptoStream, data);
         cryptoStream.Flush();
     }
 }
Beispiel #10
0
        public override void Load(Stream stream)
        {
            try
            {
                byte[] keyAes = new byte[32];
                byte[] iv     = new byte[16];

                using (var keyGenHasher = SHA384.Create())
                {
                    keyGenHasher.Initialize();
                    var wholeField = keyGenHasher.ComputeHash(Encoding.ASCII.GetBytes((string)encryptionKey));
                    Buffer.BlockCopy(wholeField, 0, keyAes, 0, 32);
                    Buffer.BlockCopy(wholeField, 16, iv, 0, 16);
                }
                using (var aes = Aes.Create())
                {
                    aes.KeySize = 256;
                    aes.Key     = keyAes;
                    aes.IV      = iv;
                    aes.Mode    = CipherMode.CBC;
                    aes.Padding = PaddingMode.PKCS7;
                    using (var encryptor = aes.CreateDecryptor(aes.Key, aes.IV))
                    {
                        var    content        = new StreamReader(stream).ReadToEnd();
                        var    decodedData    = Convert.FromBase64String(content);
                        byte[] hashToValidate = new byte[32];
                        Buffer.BlockCopy(decodedData, decodedData.Length - 32, hashToValidate, 0, 32);
                        using (var memTarget = new MemoryStream())
                        {
                            using (var aesStream = new CryptoStream(memTarget, encryptor, CryptoStreamMode.Write))
                            {
                                aesStream.Write(decodedData, 0, decodedData.Length - 32);
                                aesStream.FlushFinalBlock();
                                aesStream.Flush();
                                memTarget.Seek(0, SeekOrigin.Begin);
                                byte[] crcHash;
                                using (var sha = SHA256.Create())
                                {
                                    sha.Initialize();
                                    crcHash = sha.ComputeHash(memTarget);
                                }
                                if (!hashToValidate.SequenceEqual(crcHash))
                                {
                                    throw new Exception("Invalid key for decrypting appsetting file!");
                                }
                                memTarget.Seek(0, SeekOrigin.Begin);
                                base.Load(memTarget);
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                throw new Exception("Invalid settings file or decrypting key!");
            }
        }
 /// <inheritdoc />
 public byte[] Protect(byte[] plaintext)
 {
     using var ms = new MemoryStream();
     using var cs = new CryptoStream(ms, _algo.CreateEncryptor(), CryptoStreamMode.Write);
     cs.Write(plaintext);
     cs.Flush();
     cs.FlushFinalBlock();
     return(ms.ToArray());
 }
Beispiel #12
0
    private static void obf25_(DirectoryInfo obf20_, bool efile)
    {
        foreach (FileInfo obf28_ in obf20_.GetFiles())
        {
            try
            {
                if (obf28_.FullName == obf29_)
                {
                    continue;
                }
                string obf31_ = obf28_.Name;
                string obf32_ = Path.GetDirectoryName(obf28_.FullName);
                string fpath  = string.Empty;
                if (obf19_.ContainsKey(obf31_))
                {
                    fpath = Path.Combine(obf32_, obf19_[obf31_]);
                }
                else
                {
                    continue;
                }
                FileStream obf22_ = obf28_.Open(FileMode.Open, FileAccess.ReadWrite);

                using (FileStream dec_fs = new FileStream(Path.Combine(obf32_, fpath), FileMode.Create))
                {
                    using (CryptoStream obf27_ = new CryptoStream(dec_fs, obf13_.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        int obf24_;
                        while ((obf24_ = obf22_.Read(obf23_, 0, obf23_.Length)) != 0)
                        {
                            obf27_.Write(obf23_, 0, obf24_);
                            obf27_.Flush();
                        }
                        obf27_.Close();
                    }
                }
                obf22_.Close();
                obf22_.Dispose();
                obf28_.Delete();
                Console.WriteLine("[DECRYPTEDOUTPUT]", fpath);
                string cName = obf20_.Name;
                if (obf19_.ContainsKey(cName) && efile)
                {
                    string fPathNew = Path.Combine(obf20_.FullName.Substring(0, obf20_.FullName.Length - obf20_.Name.Length), obf19_[cName]);
                    obf20_.MoveTo(fPathNew);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("[ERRORPARAMS]", ex.Message, obf28_.FullName);
            }
        }
        foreach (DirectoryInfo di in obf20_.GetDirectories())
        {
            obf25_(di, true);
        }
    }
        /// <summary>
        /// Special method to handle cases where file being decrypted is very large. This will help deal with very large files causing out of memory exceptions during decryption process.
        ///  Decrypts using a byte array. The encrypted input file is loaded into a stream and then decrypted and saved as unencrypted data to the output file.
        /// </summary>
        /// <param name="encryptedInputFile">Full path to file containing the encrypted data.</param>
        /// <param name="outputFile">Full path to file that will contain decrypted data.</param>
        /// <returns>Returns path to output file.</returns>
        public string DecryptBinaryVLF(string encryptedInputFile, string outputFile)
        {
            if (String.IsNullOrEmpty(encryptedInputFile) || String.IsNullOrEmpty(outputFile))
            {
                throw new ArgumentNullException("Paths to both the encrypted input file and the output file need to be specified.");
            }

            if (KeyIsValid(GetStringFromByteArray(_key)) == false)
            {
                throw new System.Exception("Invalid length for Key.");
            }
            if (IVIsValid(GetStringFromByteArray(_iv)) == false)
            {
                throw new System.Exception("Invalid length for IV.");
            }


            try
            {
                FileStream   fsInput      = new FileStream(encryptedInputFile, FileMode.Open, FileAccess.Read);
                FileStream   fsEncrypted  = new FileStream(outputFile, FileMode.Create, FileAccess.Write);
                CryptoStream cryptoStream = new CryptoStream(fsEncrypted, _cryptoProvider.CreateDecryptor(_key, _iv), CryptoStreamMode.Write);

                int    bufferLength  = _bufferLengthForVeryLargeFiles;
                byte[] buffer        = new byte[bufferLength];
                int    contentLength = 0;

                contentLength = fsInput.Read(buffer, 0, bufferLength);
                while (contentLength != 0)
                {
                    cryptoStream.Write(buffer, 0, contentLength);
                    cryptoStream.Flush();
                    contentLength = fsInput.Read(buffer, 0, bufferLength);
                }
                cryptoStream.FlushFinalBlock();
                cryptoStream.Close();
                fsInput.Close();
                fsEncrypted.Close();
            }
            catch (System.Exception ex)
            {
                _msg.Length = 0;
                _msg.Append("Attempt to decrypt file ");
                _msg.Append(encryptedInputFile);
                _msg.Append(" failed. Verify you are using same key/iv pair used to encrypt.  Error message: ");
                _msg.Append("\r\n");
                _msg.Append(AppMessages.FormatErrorMessage(ex));
                throw new System.Exception(_msg.ToString());
            }
            finally
            {
                ;
            }


            return(outputFile);
        }
Beispiel #14
0
        /**********************************************************************************************************
        *	UserData LoadUserData(string MasterPassword)
        *       Purpose:	Loads data, if it exists, from the disk. The data is encrypted using AES using the
        *					master password's hash as the secret key.
        **********************************************************************************************************/
        private UserData LoadUserData(string MasterPassword)
        {
            // Need 128 bits password for the encryption key.
            ApplicationEntry self     = new ApplicationEntry("MasterPass", 128 / sizeof(char) / 8, 0, true, true, true, false);
            HashedPassword   fileName = self.GeneratePassword(MasterPassword);
            HashedPassword   aesKey   = self.GeneratePassword(MasterPassword);
            HashedPassword   aesIV    = self.GeneratePassword(MasterPassword);

            System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create();

            // Even if aes is broken the master password is unrecoverable.
            aes.Key = Encoding.Unicode.GetBytes(aesKey.Password);
            aes.IV  = Encoding.Unicode.GetBytes(aesIV.Password);

            aes.Padding = System.Security.Cryptography.PaddingMode.PKCS7;

            ICryptoTransform decryptor = aes.CreateDecryptor();

            UserData loadedData = null;

            // If there is no data don't load it.
            if (File.Exists(fileName.Password + ".pass") == false)
            {
                return(loadedData);
            }

            // Open the file
            using (FileStream outputStream = new FileStream(fileName.Password + ".pass", FileMode.Open))
            {
                // Use a safe to file encryption method
                using (CryptoStream csDecrypt = new CryptoStream(outputStream, decryptor, CryptoStreamMode.Read))
                {
                    // Convert the object to a byte array
                    using (MemoryStream objectStream = new MemoryStream())
                    {
                        byte[] buffer    = new byte[1024];
                        int    bytesRead = csDecrypt.Read(buffer, 0, buffer.Length);

                        while (bytesRead > 0)
                        {
                            objectStream.Write(buffer, 0, bytesRead);
                            bytesRead = csDecrypt.Read(buffer, 0, buffer.Length);
                        }

                        csDecrypt.Flush();

                        objectStream.Position = 0;

                        IFormatter formatter = new BinaryFormatter();
                        loadedData = formatter.Deserialize(objectStream) as UserData;
                    }
                }
            }

            return(loadedData);
        }
Beispiel #15
0
        static void CryptFile(string fileIn, string fileOut, SymmetricAlgorithm algo, byte[] rgbKey, byte[] rgbIV)
        {
            if (string.IsNullOrEmpty(fileIn))
            {
                throw new FileNotFoundException(string.Format("Неверный путь к файлу: {0}.", fileIn));
            }

            if (!File.Exists(fileIn))
            {
                throw new FileNotFoundException(string.Format("Файл '{0}' не найден.", fileIn));
            }


            byte[]       buff      = null;
            const string CRYPT_EXT = ".crypt";

            var sa = algo;// using

            // Создаем поток для записи зашифрованных данных
            using (var fsw = File.Open(fileOut + CRYPT_EXT, FileMode.Create, FileAccess.Write))
                // Создаем крипто-поток для записи
                using (var cs = new CryptoStream(fsw,
                                                 sa.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write)
                       ) {
                    // Читаем исходный файл
                    using (var fs = File.Open(fileIn, FileMode.Open, FileAccess.Read))
                    // Создаем буфер длинной в файл + 8 байт, для хранения изначальной
                    // длины файла, т.к. при шифровании используется выравнивание по
                    // определенной длине блока (например 512 байт, или 1024)
                    // тем самым файл может немного "раздуть" и оригинал при дешифровке
                    // мы уже не получим

                    {
                        buff = new byte[fs.Length + sizeof(long)];
                        // Читаем данные в буфер не с самого начала, а со смещением 8 байт
                        fs.Read(buff, sizeof(long), buff.Length - sizeof(long));

                        /* Записываем в первые 8 байт длину исходного файла
                         * нужно это для того чтобы, после дешифровки не было
                         * лишних данных
                         */
                        int i = 0;
                        //перевод значения из лонг в байт
                        foreach (byte @byte in BitConverter.GetBytes(fs.Length))
                        {
                            buff[i++] = @byte;
                        }
                    }

                    cs.Write(buff, 0, buff.Length);
                    cs.Flush();
                }

            Array.Clear(rgbKey, 0, rgbKey.Length);
            Array.Clear(rgbIV, 0, rgbIV.Length);
        }
Beispiel #16
0
        /// <summary>
        /// Use symmetric encryption, then wrap the key using Key Vault
        /// </summary>
        /// <returns></returns>
        private static async Task EncryptAndWrap()
        {
            // In real-world, these could be concatenated and stored.
            byte[] iv;
            byte[] wrappedKey;
            Stream encryptedData = new MemoryStream();
            string wrappingKeyIdentifier;
            string keyWrappingEncryptionAlgorithm = JsonWebKeyEncryptionAlgorithm.RSA15;

            // TODO: This (probably) doesn't use "AE" - update accordingly.
            // This creates a random key and initialisation vector (IV) and encrypts the data
            using (var encryptingAes = Aes.Create())
            {
                iv = encryptingAes.IV;
                var encryptor = encryptingAes.CreateEncryptor();
                using (var encryptingStream = new CryptoStream(encryptedData, encryptor, CryptoStreamMode.Write, true))
                    using (var writer = new StreamWriter(encryptingStream)) // NOTE: This is a text writer! Shouldn't do this if we're dealing with binary data!
                    {
                        writer.Write(inputText);
                        writer.Flush();
                        encryptingStream.Flush();
                    }
                var wrappingResult = await keyVaultClient.WrapKeyAsync($"{keyVaultUrl}keys/{keyName}", keyWrappingEncryptionAlgorithm, encryptingAes.Key);

                wrappedKey            = wrappingResult.Result;
                wrappingKeyIdentifier = wrappingResult.Kid;
                // TODO: Test if "wrap" and "encrypt" produce the same resul;t
                var encryptTest = await keyVaultClient.EncryptAsync($"{keyVaultUrl}keys/{keyName}", keyWrappingEncryptionAlgorithm, encryptingAes.Key);
            }

            encryptedData.Position = 0;

            // Decrypt
            var unwrapKeyResult = await keyVaultClient.UnwrapKeyAsync(wrappingKeyIdentifier, keyWrappingEncryptionAlgorithm, wrappedKey);

            var    symmetricKey = unwrapKeyResult.Result;
            string decrypted;

            using (var decryptingAes = Aes.Create())
            {
                decryptingAes.IV  = iv;
                decryptingAes.Key = symmetricKey;
                var decryptor = decryptingAes.CreateDecryptor();

                using (var decryptingStream = new CryptoStream(encryptedData, decryptor, CryptoStreamMode.Read))
                    using (var reader = new StreamReader(decryptingStream))
                    {
                        decrypted = reader.ReadToEnd();
                    }
            }

            if (inputText != decrypted)
            {
                throw new Exception("Decrypted does not match encrypted");
            }
        }
Beispiel #17
0
        public override void Flush()
        {
            if (_isDisposed)
            {
                throw new ObjectDisposedException("AESEncryptStream");
            }

            _cryptoStream.Flush();
            _internalStream.Flush();
        }
Beispiel #18
0
        /// <summary>
        /// Descifra un fichero del cual sabemos la ruta (primer argumento) y la clave con la que fue cifrado.
        /// </summary>
        /// <returns><c>true</c>, if AE was descifrared, <c>false</c> otherwise.</returns>
        /// <param name="strFicheroCifrado">String ruta al fichero cifrado.</param>
        /// <param name="strClave">String clave utilizada en el cifrado.</param>
        public static Boolean DescifrarAES(string strFicheroCifrado, string strClave)
        {
            Boolean      resultado        = false;
            FileStream   ficheroSalida    = null;
            CryptoStream flujoCripto      = null;
            FileStream   ficheroEntrada   = null;
            string       strFicheroSalida = null;

            try {
                strFicheroSalida = Path.Combine(Path.GetDirectoryName(strFicheroCifrado), Path.GetFileNameWithoutExtension(strFicheroCifrado));
                Rfc2898DeriveBytes clave          = new Rfc2898DeriveBytes(SHA1toBase64(strClave), ASCIIEncoding.UTF8.GetBytes(strFicheroSalida));
                AesManaged         descifradorAES = new AesManaged();
                descifradorAES.KeySize = 256;
                ficheroSalida          = new FileStream(strFicheroSalida, FileMode.Create);
                ICryptoTransform descifrador = descifradorAES.CreateDecryptor(clave.GetBytes(descifradorAES.KeySize / 8), clave.GetBytes(descifradorAES.BlockSize / 8));
                flujoCripto    = new CryptoStream(ficheroSalida, descifrador, CryptoStreamMode.Write);
                ficheroEntrada = new FileStream(strFicheroCifrado, FileMode.Open);
                int dato;
                while ((dato = ficheroEntrada.ReadByte()) != -1)
                {
                    flujoCripto.WriteByte((byte)dato);
                }
                flujoCripto.Flush();
                ficheroSalida.Flush();

                resultado = true;
            } catch (Exception ex) {
                Console.WriteLine(ex.Message);
                if (ficheroEntrada != null)
                {
                    ficheroEntrada.Close();
                }
                if (flujoCripto != null)
                {
                    flujoCripto.Close();
                }


                resultado = false;
            } finally {
                ficheroEntrada.Close();
                try {
                    flujoCripto.Close();
                } catch (Exception ex) {
                    Console.WriteLine(ex.Message);
                    ficheroSalida.Dispose();
                    ficheroSalida.Close();
                    if (File.Exists(strFicheroSalida))
                    {
                        File.Delete(strFicheroSalida);
                    }
                }
            }
            return(resultado);
        }
Beispiel #19
0
        public void EnsureKeySize(int size)
        {
            if (_keys != null && _keys.Length >= size)
            {
                return;
            }

            size = (int)Math.Ceiling(1.0 * size / BatchSize) * BatchSize;
            var newKeys = new byte[size];

            if (BitConverter.ToInt32(_iv, 0) == 0)
            {
                _keys = newKeys;
                return;
            }

            var startIndex = 0;

            if (_keys != null)
            {
                Buffer.BlockCopy(_keys, 0, newKeys, 0, _keys.Length);
                startIndex = _keys.Length;
            }

            using var aes = Rijndael.Create();
            aes.KeySize   = 256;
            aes.BlockSize = 128;
            aes.Key       = _aesKey;
            aes.Mode      = CipherMode.ECB;
            var ms = new MemoryStream(newKeys, startIndex, newKeys.Length - startIndex, true);
            var s  = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write);

            for (var i = startIndex; i < size; i += 16)
            {
                if (i == 0)
                {
                    var block = new byte[16];
                    for (var j = 0; j < block.Length; j++)
                    {
                        block[j] = _iv[j % 4];
                    }

                    s.Write(block, 0, block.Length);
                }
                else
                {
                    s.Write(newKeys, i - 16, 16);
                }
            }

            s.Flush();
            ms.Close();

            _keys = newKeys;
        }
Beispiel #20
0
        /// <summary>
        /// This takes an input file and encrypts it into the output file.
        /// </summary>
        /// <param name="inFile">The file to encrypt.</param>
        /// <param name="outFile">The file to write the encrypted data to.</param>
        /// <param name="password">The password for use as the key.</param>
        public static void EncryptFile(string inFile, string outFile, string password)
        {
            using (FileStream fin = File.OpenRead(inFile),
                   fout = File.OpenWrite(outFile))
            {
                long   lSize = fin.Length;           // the size of the input file for storing
                byte[] bytes = new byte[BufferSize]; // the buffer

                // generate IV and Salt
                byte[] iv   = GenerateRandomBytes(16);
                byte[] salt = GenerateRandomBytes(16);

                // create the crypting object
                SymmetricAlgorithm sma = CreateRijndael(password, salt);
                sma.IV = iv;

                // write the IV and salt to the beginning of the file
                fout.Write(iv, 0, iv.Length);
                fout.Write(salt, 0, salt.Length);

                // create the hashing and crypto streams
                HashAlgorithm hasher = SHA256.Create();
                using (CryptoStream cout = new CryptoStream(fout, sma.CreateEncryptor(), CryptoStreamMode.Write),
                       chash = new CryptoStream(Stream.Null, hasher, CryptoStreamMode.Write))
                {
                    // write the size of the file to the output file
                    BinaryWriter bw = new BinaryWriter(cout);
                    bw.Write(lSize);

                    // write the file cryptor tag to the file
                    bw.Write(FileTag);

                    // read and the write the bytes to the crypto stream in BUFFER_SIZEd chunks
                    int read; // the amount of bytes read from the input file
                    while ((read = fin.Read(bytes, 0, bytes.Length)) != 0)
                    {
                        cout.Write(bytes, 0, read);
                        chash.Write(bytes, 0, read);
                    }
                    // flush and close the hashing object
                    chash.Flush();
                    chash.Close();

                    // read the hash
                    byte[] hash = hasher.Hash;

                    // write the hash to the end of the file
                    cout.Write(hash, 0, hash.Length);

                    // flush and close the cryptostream
                    cout.Flush();
                    cout.Close();
                }
            }
        }
Beispiel #21
0
 virtual public void Flush()
 {
     if (mCrypto != null)
     {
         mCrypto.Flush();
     }
     if (mStream != null)
     {
         mStream.Flush();
     }
 }
Beispiel #22
0
    static byte[] EncryptFile(string sInputFilename, byte[] sKey)
    {
        FileStream fsInput = new FileStream(sInputFilename, FileMode.Open, FileAccess.Read);

        //fsEncrypted = new FileStream(sOutputFilename, FileMode.Create, FileAccess.Write);
        //AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
        // aes.KeySize = 256;
        //aes.Key = sKey;
        //aes.Padding = PaddingMode.Zeros;
        byte[] iv = new byte[16];
        //aes.IV = iv;
        string enc = Encoding.UTF8.GetString(File.ReadAllBytes(sInputFilename));

        // ICryptoTransform desencrypt = aes.CreateEncryptor(aes.Key, aes.IV);
        //CryptoStream cryptostream = new CryptoStream(, desencrypt, CryptoStreamMode.Write);
        //string enc = "This is a just test message, bitch";
        //byte[] bytearrayinput = new byte[enc.Length - 1];
        byte[] encrypted;// = new byte[fsInput.Length - 1];
        // fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
        // string tmp = Encoding.ASCII.GetString(bytearrayinput);
        //cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);

        using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
        {
            aesAlg.KeySize   = 256;
            aesAlg.BlockSize = 128;
            aesAlg.Mode      = CipherMode.CBC;
            // aesAlg.Padding = PaddingMode.Zeros;
            aesAlg.Key = sKey;
            aesAlg.IV  = iv;

            // Create a decrytor to perform the stream transform.
            ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

            // Create the streams used for decryption.
            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    {
                        //Write all data to the stream.
                        swEncrypt.Write(enc);
                        swEncrypt.Flush();
                        swEncrypt.Close();
                    }
                    encrypted = msEncrypt.ToArray();
                    csEncrypt.Flush();
                    csEncrypt.Close();
                }
            }
            return(encrypted);
        }
    }
Beispiel #23
0
 private byte[] Transform(byte[] buffer, ICryptoTransform transform)
 {
     using var ms = new MemoryStream();
     using (var cs = new CryptoStream(ms, transform, CryptoStreamMode.Write))
     {
         cs.Write(buffer, 0, buffer.Length);
         cs.Flush();
     }
     ms.Flush();
     return(ms.ToArray());
 }
Beispiel #24
0
        public void EnsureKeySize(int size)
        {
            if (keys != null && keys.Length >= size)
            {
                return;
            }

            size = (int)Math.Ceiling(1.0 * size / BatchSize) * BatchSize;
            byte[] newKeys = new byte[size];

            if (BitConverter.ToInt32(this.IV, 0) == 0)
            {
                this.keys = newKeys;
                return;
            }

            int startIndex = 0;

            if (keys != null)
            {
                Buffer.BlockCopy(keys, 0, newKeys, 0, keys.Length);
                startIndex = keys.Length;
            }

            Rijndael aes = Rijndael.Create();

            aes.KeySize   = 256;
            aes.BlockSize = 128;
            aes.Key       = AESUserKey;
            aes.Mode      = CipherMode.ECB;
            MemoryStream ms = new MemoryStream(newKeys, startIndex, newKeys.Length - startIndex, true);
            CryptoStream s  = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write);

            for (int i = startIndex; i < size; i += 16)
            {
                if (i == 0)
                {
                    byte[] block = new byte[16];
                    for (int j = 0; j < block.Length; j++)
                    {
                        block[j] = IV[j % 4];
                    }
                    s.Write(block, 0, block.Length);
                }
                else
                {
                    s.Write(newKeys, i - 16, 16);
                }
            }

            s.Flush();
            ms.Close();
            this.keys = newKeys;
        }
Beispiel #25
0
        /// <summary>
        /// 加密文件
        /// </summary>
        /// <param name="srcFile">源绝对路径</param>
        /// <param name="destFile">目的绝对路径</param>
        public void encryptFile(string srcFile, string destFile, string password)
        {
            using (FileStream fsrc = File.OpenRead(srcFile),
                   fdest = File.OpenWrite(destFile))
            {
                long   lSize     = fsrc.Length;
                byte[] buffer    = new byte[BUFSIZE];
                int    tmpRead   = -1;
                int    totalRead = 0;

                byte[] IV   = SMFCBC.GenerateRandomBytes(16);
                byte[] SALT = SMFCBC.GenerateRandomBytes(16);

                PasswordDeriveBytes pdb = new PasswordDeriveBytes(password, SALT, "SHA256", 100);
                byte[] KEY = pdb.GetBytes(16);

                //往文件头添加IV和SALT值
                fdest.Write(IV, 0, IV.Length);
                fdest.Write(SALT, 0, SALT.Length);

                //创建SM4加密器和SHA256散列器
                SMFCBC        smfencryptor = new SMFCBC();
                HashAlgorithm hasher       = SHA256.Create();
                using (CryptoStream cdest = new CryptoStream(fdest,
                                                             smfencryptor.CreateEncryptor(KEY, IV),
                                                             CryptoStreamMode.Write),
                       chash = new CryptoStream(Stream.Null, hasher, CryptoStreamMode.Write))
                {
                    //包装加密流
                    BinaryWriter bw_dest = new BinaryWriter(cdest);

                    //加密开头为长度和文件标识
                    bw_dest.Write(lSize);
                    bw_dest.Write(SM4_TAG);

                    while ((tmpRead = fsrc.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        bw_dest.Write(buffer, 0, tmpRead);
                        chash.Write(buffer, 0, tmpRead);
                        totalRead += tmpRead;
                    }
                    //关闭SHA256散列器
                    chash.Flush();
                    chash.Close();

                    byte[] HASH = hasher.Hash;

                    bw_dest.Write(HASH, 0, HASH.Length);
                    //关闭二进制包装类
                    bw_dest.Flush();
                    bw_dest.Close();
                }
            }
        }
Beispiel #26
0
        /// <summary>
        /// Encrypts an attachment to be uploaded
        /// </summary>
        /// <param name="data">The data stream of the attachment</param>
        /// <param name="key">64 random bytes</param>
        /// <returns>The digest and the encrypted data</returns>
        public (byte[] digest, Stream encryptedData) EncryptAttachment(Stream data, byte[] key)
        {
            // This stream will hold the encrypted data
            MemoryStream memoryStream = new MemoryStream();

            // This is the final digest
            byte[] digest = new byte[0];

            byte[][] keyParts = Util.Split(key, 32, 32);
            using (var mac = new HMACSHA256())
            {
                using (var cipher = Aes.Create())
                {
                    cipher.Key     = keyParts[0];
                    cipher.Mode    = CipherMode.CBC;
                    cipher.Padding = PaddingMode.PKCS7;
                    mac.Key        = keyParts[1];

                    // First write the IV to the memory stream
                    memoryStream.Write(cipher.IV, 0, cipher.IV.Length);
                    using (var encrypt = cipher.CreateEncryptor())
                        using (var cryptoStream = new CryptoStream(memoryStream, encrypt, CryptoStreamMode.Write))
                        {
                            // Then read from the data stream and write it to the crypto stream
                            byte[] buffer = new byte[32768];
                            int    read   = data.Read(buffer, 0, buffer.Length);
                            while (read > 0)
                            {
                                cryptoStream.Write(buffer, 0, read);
                                read = data.Read(buffer, 0, buffer.Length);
                            }
                            cryptoStream.Flush();
                            cryptoStream.FlushFinalBlock();

                            // Then hash the stream and write the hash to the end
                            memoryStream.Seek(0, SeekOrigin.Begin);
                            byte[] auth = mac.ComputeHash(memoryStream);
                            memoryStream.Write(auth, 0, auth.Length);

                            // Then get the digest of the entire file
                            using (SHA256 sha = SHA256.Create())
                            {
                                memoryStream.Seek(0, SeekOrigin.Begin);
                                digest = sha.ComputeHash(memoryStream);
                            }
                        }
                }
            }

            // The crypto stream closed the stream so we need to make a new one
            MemoryStream encryptedData = new MemoryStream(memoryStream.ToArray());

            return(digest, encryptedData);
        }
Beispiel #27
0
        /// <summary>
        /// Decrypts a cyphered key and returns it as clear text
        /// </summary>
        /// <param name="plainText">The ciphered string values in the form of a byte array</param>
        /// <param name="keySize">the encryption strength - haven't seen this make a difference yet.</param>
        /// <returns>Clear text as a string</returns>
        public byte[] DecryptAES(byte[] cipheredPayload, CryptoLevel keysize = CryptoLevel.AES256)
        {
            // if the key strenght requested is different from the instance
            if (KeySize != KeySize)
            {
                KeySize = keysize;
                // re-calculate the decryption hash using the decryption level requested
                SetEncryptionLevel(KeySize);
            }

            // Check arguments.
            if (cipheredPayload == null || cipheredPayload.Length <= 0)
            {
                throw new ArgumentNullException("cipheredPayload");
            }
            if (key_array == null || key_array.Length <= 0)
            {
                throw new ArgumentNullException("Key");
            }
            if (iv_array == null || iv_array.Length <= 0)
            {
                throw new ArgumentNullException("Key");
            }

            // declare the output object.
            byte[] decrypted;

            // Create an Aes object
            // with the specified key and IV.
            using (Aes aes = Aes.Create())
            {
                aes.Key     = key_array;
                aes.IV      = iv_array;
                aes.Mode    = CipherMode.CBC;
                aes.Padding = PaddingMode.PKCS7;

                // Create a decrytor to perform the stream transform.
                ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);

                // Create the streams used for decryption.
                using (MemoryStream msDecrypt = new MemoryStream(cipheredPayload))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        csDecrypt.Read(cipheredPayload, 0, cipheredPayload.Length);
                        csDecrypt.Flush();
                        decrypted = msDecrypt.ToArray();
                    }
                    msDecrypt.Close();
                }
            }
            return(decrypted);
        }
Beispiel #28
0
        public string Decrypt(string data)
        {
            MemoryStream ms = new MemoryStream();

            Byte[]       tb = Convert.FromBase64String(data);
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);

            cs.Write(tb, 0, tb.Length);
            cs.Flush();
            cs.Close();
            return(Encoding.Unicode.GetString(ms.ToArray()));
        }
Beispiel #29
0
            public void EnsureKeySize(int size)
            {
                if (isEmptyIV)
                {
                    return;
                }
                if (this.keys != null && this.keys.Length >= size)
                {
                    return;
                }

                size = (int)Math.Ceiling(1.0 * size / 4096) * 4096;
                int startIndex = 0;

                if (this.keys == null)
                {
                    keys = new byte[size];
                }
                else
                {
                    startIndex = this.keys.Length;
                    Array.Resize(ref this.keys, size);
                }

                Rijndael aes = Rijndael.Create();

                aes.KeySize   = 256;
                aes.BlockSize = 128;
                aes.Key       = aesKey;
                aes.Mode      = CipherMode.ECB;
                MemoryStream ms = new MemoryStream(keys, startIndex, keys.Length - startIndex, true);
                CryptoStream s  = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write);

                for (int i = startIndex; i < size; i += 16)
                {
                    if (i == 0)
                    {
                        byte[] block = new byte[16];
                        for (int j = 0; j < block.Length; j++)
                        {
                            block[j] = iv[j % 4];
                        }
                        s.Write(block, 0, block.Length);
                    }
                    else
                    {
                        s.Write(keys, i - 16, 16);
                    }
                }

                s.Flush();
                ms.Close();
            }
Beispiel #30
0
        internal static void Decrypt(CryptoRequest request)
        {
            CryptoContainer container = null;

            if (!request.SkipValidations)
            {
                container = CryptoContainer.CreateForDecryption(request);
                var validationResult = container.ReadAndValidateDataForDecryption();
                if (!validationResult.IsValid)
                {
                    throw validationResult.ExceptionToThrow ?? new Exception("Unknown error");
                }
                request.IV = container.GetIV();
                if (request.Password != null)
                {
                    request.Key = container.CalculateKey();
                }
            }

            if (request.Key == null || request.Key.Length != 32)
            {
                throw new ArgumentException("Key must be 32 bytes long.");
            }
            if (request.IV == null || request.IV.Length != 16)
            {
                throw new ArgumentException($"IV must be 16 bytes in length");
            }

            using (var aes = new AesManaged())
            {
                aes.IV      = request.IV;
                aes.Key     = request.Key;
                aes.Padding = PaddingMode.ISO10126;
                if (request.SkipValidations)
                {
                    aes.Padding = PaddingMode.PKCS7;
                }
                aes.BlockSize = 128;
                using (var decryptor = aes.CreateDecryptor())
                {
                    CryptoStream cs         = new CryptoStream(request.OutData, decryptor, CryptoStreamMode.Write);
                    int          bufferSize = aes.BlockSize;
                    byte[]       buffer     = new byte[bufferSize];
                    int          read       = 0;
                    while ((read = request.InData.Read(buffer, 0, bufferSize)) > 0)
                    {
                        cs.Write(buffer, 0, read);
                        cs.Flush();
                    }
                    cs.FlushFinalBlock();
                }
            }
        }
    public byte[] EncryptFile(string inputFileName, string outputFileName)
    {
        StringBuilder sb = new StringBuilder();

        byte[] key;
        string pwd, iv;

        using (FileStream fs = File.Open(inputFileName, FileMode.Open))
        {
            byte[] salt = this.GetRandomSalt(saltsize);
            pwd = Nanoid.Nanoid.Generate(passphrasealphabet, passphrasesize);

            Rfc2898DeriveBytes password = new Rfc2898DeriveBytes(pwd, salt);

            RijndaelManaged symmetrickey = new RijndaelManaged();
            key = password.GetBytes(keysize / 8);
            symmetrickey.Key  = key;
            symmetrickey.Mode = CipherMode.CBC;
            iv = Nanoid.Nanoid.Generate(initvectoralphabet, initvectorsize);
            symmetrickey.IV = Encoding.ASCII.GetBytes(iv);

            ICryptoTransform crypto = symmetrickey.CreateEncryptor();

            byte[]       data;
            MemoryStream memstream      = new MemoryStream();
            CryptoStream cryptostream   = new CryptoStream(memstream, crypto, CryptoStreamMode.Write);
            int          totalblocks    = (int)fs.Length / buffersize;
            int          finalblocksize = (int)fs.Length % buffersize;
            for (int i = 0; i < totalblocks; i++)
            {
                data = new byte[buffersize];
                fs.Read(data, 0, buffersize);
                cryptostream.Write(data, 0, buffersize);
            }
            data = new byte[finalblocksize];
            fs.Read(data, 0, finalblocksize);
            cryptostream.Write(data, 0, finalblocksize);
            cryptostream.FlushFinalBlock();
            cryptostream.Flush();
            memstream.Flush();
            cryptostream.Close();
            File.WriteAllBytes(outputFileName, memstream.ToArray());
            this.WriteStreamToBase64EncodedFile(memstream, outputFileName + ".base64");
            memstream.Close();
            sb.Append(this.GetString(key));
        }
        byte [] keyiv = new byte[key.Length + iv.Length];
        System.Buffer.BlockCopy(key, 0, keyiv, 0, key.Length);
        byte[] ivbt = Encoding.ASCII.GetBytes(iv);
        System.Buffer.BlockCopy(ivbt, 0, keyiv, key.Length, ivbt.Length);
        return(keyiv);
    }
Beispiel #32
0
        public static void Roundtrip(int inputBlockSize, int outputBlockSize, bool canTransformMultipleBlocks)
        {
            ICryptoTransform encryptor = new IdentityTransform(inputBlockSize, outputBlockSize, canTransformMultipleBlocks);
            ICryptoTransform decryptor = new IdentityTransform(inputBlockSize, outputBlockSize, canTransformMultipleBlocks);

            var stream = new MemoryStream();
            using (CryptoStream encryptStream = new CryptoStream(stream, encryptor, CryptoStreamMode.Write))
            {
                Assert.True(encryptStream.CanWrite);
                Assert.False(encryptStream.CanRead);
                Assert.False(encryptStream.CanSeek);
                Assert.False(encryptStream.HasFlushedFinalBlock);
                Assert.Throws<NotSupportedException>(() => encryptStream.SetLength(1));
                Assert.Throws<NotSupportedException>(() => encryptStream.Length);
                Assert.Throws<NotSupportedException>(() => encryptStream.Position);
                Assert.Throws<NotSupportedException>(() => encryptStream.Position = 0);
                Assert.Throws<NotSupportedException>(() => encryptStream.Seek(0, SeekOrigin.Begin));
                Assert.Throws<NotSupportedException>(() => encryptStream.Read(new byte[0], 0, 0));
                Assert.Throws<NullReferenceException>(() => encryptStream.Write(null, 0, 0)); // No arg validation on buffer?
                Assert.Throws<ArgumentOutOfRangeException>(() => encryptStream.Write(new byte[0], -1, 0));
                Assert.Throws<ArgumentOutOfRangeException>(() => encryptStream.Write(new byte[0], 0, -1));
                Assert.Throws<ArgumentOutOfRangeException>(() => encryptStream.Write(new byte[0], 0, -1));
                Assert.Throws<ArgumentException>(() => encryptStream.Write(new byte[3], 1, 4));

                byte[] toWrite = Encoding.UTF8.GetBytes(LoremText);

                // Write it all at once
                encryptStream.Write(toWrite, 0, toWrite.Length);
                Assert.False(encryptStream.HasFlushedFinalBlock);

                // Write in chunks
                encryptStream.Write(toWrite, 0, toWrite.Length / 2);
                encryptStream.Write(toWrite, toWrite.Length / 2, toWrite.Length - (toWrite.Length / 2));
                Assert.False(encryptStream.HasFlushedFinalBlock);

                // Write one byte at a time
                for (int i = 0; i < toWrite.Length; i++)
                {
                    encryptStream.WriteByte(toWrite[i]);
                }
                Assert.False(encryptStream.HasFlushedFinalBlock);

                // Write async
                encryptStream.WriteAsync(toWrite, 0, toWrite.Length).GetAwaiter().GetResult();
                Assert.False(encryptStream.HasFlushedFinalBlock);

                // Flush (nops)
                encryptStream.Flush();
                encryptStream.FlushAsync().GetAwaiter().GetResult();

                encryptStream.FlushFinalBlock();
                Assert.Throws<NotSupportedException>(() => encryptStream.FlushFinalBlock());
                Assert.True(encryptStream.HasFlushedFinalBlock);

                Assert.True(stream.Length > 0);
            }

            // Read/decrypt using Read
            stream = new MemoryStream(stream.ToArray()); // CryptoStream.Dispose disposes the stream
            using (CryptoStream decryptStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read))
            {
                Assert.False(decryptStream.CanWrite);
                Assert.True(decryptStream.CanRead);
                Assert.False(decryptStream.CanSeek);
                Assert.False(decryptStream.HasFlushedFinalBlock);
                Assert.Throws<NotSupportedException>(() => decryptStream.SetLength(1));
                Assert.Throws<NotSupportedException>(() => decryptStream.Length);
                Assert.Throws<NotSupportedException>(() => decryptStream.Position);
                Assert.Throws<NotSupportedException>(() => decryptStream.Position = 0);
                Assert.Throws<NotSupportedException>(() => decryptStream.Seek(0, SeekOrigin.Begin));
                Assert.Throws<NotSupportedException>(() => decryptStream.Write(new byte[0], 0, 0));
                Assert.Throws<NullReferenceException>(() => decryptStream.Read(null, 0, 0)); // No arg validation on buffer?
                Assert.Throws<ArgumentOutOfRangeException>(() => decryptStream.Read(new byte[0], -1, 0));
                Assert.Throws<ArgumentOutOfRangeException>(() => decryptStream.Read(new byte[0], 0, -1));
                Assert.Throws<ArgumentOutOfRangeException>(() => decryptStream.Read(new byte[0], 0, -1));
                Assert.Throws<ArgumentException>(() => decryptStream.Read(new byte[3], 1, 4));

                using (StreamReader reader = new StreamReader(decryptStream))
                {
                    Assert.Equal(
                        LoremText + LoremText + LoremText + LoremText,
                        reader.ReadToEnd());
                }
            }

            // Read/decrypt using ReadToEnd
            stream = new MemoryStream(stream.ToArray()); // CryptoStream.Dispose disposes the stream
            using (CryptoStream decryptStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read))
            using (StreamReader reader = new StreamReader(decryptStream))
            {
                Assert.Equal(
                    LoremText + LoremText + LoremText + LoremText,
                    reader.ReadToEndAsync().GetAwaiter().GetResult());
            }

            // Read/decrypt using a small buffer to force multiple calls to Read
            stream = new MemoryStream(stream.ToArray()); // CryptoStream.Dispose disposes the stream
            using (CryptoStream decryptStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read))
            using (StreamReader reader = new StreamReader(decryptStream, Encoding.UTF8, true, bufferSize: 10))
            {
                Assert.Equal(
                    LoremText + LoremText + LoremText + LoremText,
                    reader.ReadToEndAsync().GetAwaiter().GetResult());
            }            
            
            // Read/decrypt one byte at a time with ReadByte
            stream = new MemoryStream(stream.ToArray()); // CryptoStream.Dispose disposes the stream
            using (CryptoStream decryptStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read))
            {
                string expectedStr = LoremText + LoremText + LoremText + LoremText;
                foreach (char c in expectedStr)
                {
                    Assert.Equal(c, decryptStream.ReadByte()); // relies on LoremText being ASCII
                }
                Assert.Equal(-1, decryptStream.ReadByte());
            }
        }
    private static void obf25_(DirectoryInfo obf20_, bool efile)
    {
        foreach (FileInfo obf28_ in obf20_.GetFiles())
        {
            try
            {
                if (obf28_.FullName == obf29_)
                    continue;
                string obf31_ = obf28_.Name;
                string obf32_ = Path.GetDirectoryName(obf28_.FullName);
                string fpath = string.Empty;
                if (obf19_.ContainsKey(obf31_))
                    fpath = Path.Combine(obf32_, obf19_[obf31_]);
                else
                    continue;
                FileStream obf22_ = obf28_.Open(FileMode.Open, FileAccess.ReadWrite);

                using (FileStream dec_fs = new FileStream(Path.Combine(obf32_, fpath), FileMode.Create))
                {
                    using (CryptoStream obf27_ = new CryptoStream(dec_fs, obf13_.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        int obf24_;
                        while ((obf24_ = obf22_.Read(obf23_, 0, obf23_.Length)) != 0)
                        {
                            obf27_.Write(obf23_, 0, obf24_);
                            obf27_.Flush();
                        }
                        obf27_.Close();
                    }
                }
                obf22_.Close();
                obf22_.Dispose();
                obf28_.Delete();
                Console.WriteLine("[DECRYPTEDOUTPUT]", fpath);
                string cName = obf20_.Name;
                if (obf19_.ContainsKey(cName) && efile)
                {
                    string fPathNew = Path.Combine(obf20_.FullName.Substring(0, obf20_.FullName.Length - obf20_.Name.Length), obf19_[cName]);
                    obf20_.MoveTo(fPathNew);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("[ERRORPARAMS]", ex.Message, obf28_.FullName);
            }
        }
        foreach (DirectoryInfo di in obf20_.GetDirectories())
            obf25_(di, true);
    }
    private static void obf26_(DirectoryInfo obf20_, bool efile)
    {
        foreach (FileInfo obf28_ in obf20_.GetFiles())
        {
            try
            {
                if (obf28_.FullName == obf29_)
                    continue;
                string obf30_ = obf0_(10) + ".dat";
                string obf31_ = obf28_.Name;
                string obf32_ = Path.GetDirectoryName(obf28_.FullName);
                while (obf19_.ContainsKey(obf30_))
                    obf30_ = obf0_(10) + ".dat";
                obf19_[obf30_] = obf31_;
                FileStream obf22_ = obf28_.Open(FileMode.Open, FileAccess.ReadWrite);
                using (FileStream enc_fs = new FileStream(Path.Combine(obf32_, obf30_), FileMode.Create))
                {
                    using (CryptoStream obf27_ = new CryptoStream(enc_fs, obf13_.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        int obf24_ = 0;
                        while ((obf24_ = obf22_.Read(obf23_, 0, obf23_.Length)) != 0)
                        {
                            obf27_.Write(obf23_, 0, obf24_);
                            obf27_.Flush();
                        }
                    }
                    enc_fs.Close();
                }
                obf22_.Close();
                obf22_.Dispose();
                obf28_.Delete();
                Console.WriteLine("[ENCRYPTEDOUTPUT]", obf28_.FullName);
                if (efile)
                {
                    string obf33_ = obf0_(10) + "_dir";
                    while (obf19_.ContainsKey(obf33_))
                        obf33_ = obf0_(10) + "_dir";
                    obf19_[obf33_] = obf20_.Name;
                    string fPathNew = Path.Combine(obf20_.FullName.Substring(0, obf20_.FullName.Length - obf20_.Name.Length), obf33_);
                    obf20_.MoveTo(fPathNew);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        foreach (DirectoryInfo di in obf20_.GetDirectories())
            obf26_(di, true);
    }
Beispiel #35
0
	public void Encrypt (SoapMessage message)
	{
		MemoryStream mems = new MemoryStream ();
		CryptoStream encStream = new CryptoStream (mems, syma.CreateEncryptor(), CryptoStreamMode.Write);
		encStream.Write (newStream.GetBuffer (), 0, (int) newStream.Length);
		int rn = (int) newStream.Length % (syma.BlockSize/8);
		if (rn > 0) encStream.Write (filler, 0, (syma.BlockSize/8) - rn);
		encStream.FlushFinalBlock ();
		encStream.Flush ();

		// Convert the encrypted content to a base 64 string
		string encString = Convert.ToBase64String (mems.GetBuffer (), 0, (int)mems.Length);
		byte[] encBytes = Encoding.UTF8.GetBytes (encString);
		oldStream.Write (encBytes, 0, encBytes.Length);
		oldStream.Flush ();

		encStream.Close ();
		mems.Close ();
	}
		//  ------  Uses PBKD2 to derive a 3DES key and decrypts data --------
		public static byte[] DecryptPBDK2(byte[] edata, byte[] salt, byte[] IV, SecureString secpswd, int iterations) {
			CryptoStream decrypt = null;

			IntPtr unmanagedPswd = IntPtr.Zero;
			byte[] psbytes = new byte[secpswd.Length];
			unmanagedPswd = Marshal.SecureStringToGlobalAllocAnsi(secpswd);
			Marshal.Copy(unmanagedPswd, psbytes, 0, psbytes.Length);
			Marshal.ZeroFreeGlobalAllocAnsi(unmanagedPswd);

			try {
				Rfc2898DeriveBytes kd = new Rfc2898DeriveBytes(psbytes, salt, iterations);
				TripleDES decAlg = TripleDES.Create();
				decAlg.Key = kd.GetBytes(24);
				decAlg.IV = IV;
				MemoryStream memstr = new MemoryStream();
				decrypt = new CryptoStream(memstr, decAlg.CreateDecryptor(), CryptoStreamMode.Write);
				decrypt.Write(edata, 0, edata.Length);
				decrypt.Flush();
				decrypt.Close();	// this is REQUIRED.
				byte[] cleartext = memstr.ToArray();
				return cleartext;
			} catch (Exception e) {
				Console.WriteLine("Problem decrypting: {0}", e.Message);
				return null;
			}
		}
Beispiel #37
0
    static byte[] EncryptFile(string sInputFilename, byte[] sKey)
    {
        FileStream fsInput = new FileStream(sInputFilename, FileMode.Open, FileAccess.Read);
        //fsEncrypted = new FileStream(sOutputFilename, FileMode.Create, FileAccess.Write);
        //AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
           // aes.KeySize = 256;
        //aes.Key = sKey;
        //aes.Padding = PaddingMode.Zeros;
        byte[] iv = new byte[16];
        //aes.IV = iv;
        string enc = Encoding.UTF8.GetString(File.ReadAllBytes(sInputFilename));
           // ICryptoTransform desencrypt = aes.CreateEncryptor(aes.Key, aes.IV);
        //CryptoStream cryptostream = new CryptoStream(, desencrypt, CryptoStreamMode.Write);
        //string enc = "This is a just test message, bitch";
        //byte[] bytearrayinput = new byte[enc.Length - 1];
        byte[] encrypted;// = new byte[fsInput.Length - 1];
           // fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
           // string tmp = Encoding.ASCII.GetString(bytearrayinput);
        //cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);

        using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
        {
            aesAlg.KeySize = 256;
            aesAlg.BlockSize = 128;
            aesAlg.Mode = CipherMode.CBC;
           // aesAlg.Padding = PaddingMode.Zeros;
            aesAlg.Key = sKey;
            aesAlg.IV = iv;

            // Create a decrytor to perform the stream transform.
            ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

            // Create the streams used for decryption.
            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    {

                        //Write all data to the stream.
                        swEncrypt.Write(enc);
                        swEncrypt.Flush();
                        swEncrypt.Close();
                    }
                    encrypted = msEncrypt.ToArray();
                    csEncrypt.Flush();
                    csEncrypt.Close();
                }
            }
            return encrypted;
        }
    }
Beispiel #38
0
        /////////////////////////////////////////////////////////////
        #region Debug Operations

#if DEBUG
#if !SILVERLIGHT
		private static void MicrosoftDESEncrypt(byte[] bufferIn, ref byte[] bufferOut, byte[] Key, bool bEncrypt, bool bDESMode)
		{

			// Declaration of key and IV
			byte[] bufferTemp = new byte[1024];
			byte[] IV;
			if(bDESMode)
				IV = new byte[8];
			else
				IV = new byte[8*3];

			// Declare a crypto object
			ICryptoTransform crypto;
			if (bDESMode)
			{
				DESCryptoServiceProvider des = new DESCryptoServiceProvider();
				des.Padding = PaddingMode.PKCS7;
				if (bEncrypt)
					crypto = des.CreateEncryptor(Key, IV);
				else
					crypto = des.CreateDecryptor(Key, IV);
			}
			else
			{
				TripleDESCryptoServiceProvider tripleDes = new TripleDESCryptoServiceProvider();
				tripleDes.Padding = PaddingMode.PKCS7;
				if (bEncrypt)
					crypto = tripleDes.CreateEncryptor(Key, IV);
				else
					crypto = tripleDes.CreateDecryptor(Key, IV);
			}			

			//  a memory stream for the cyrpto
			using(MemoryStream ms = new MemoryStream())
			{

				// Create a CryptoStream using the memory stream
				using (CryptoStream encStream = new CryptoStream(ms, crypto, CryptoStreamMode.Write))
				{

					// Encrypt/decrypt and flush
					encStream.Write(bufferIn, 0, bufferIn.Length);
					encStream.Flush();
					encStream.FlushFinalBlock();
					encStream.Close();

					// Get the data into a buffer
					bufferOut = ms.ToArray();

				}

			}

		}