Пример #1
0
        static byte[] Encrypt(byte[] key, byte[] iv, byte[] message, int offset, int length)
        {
            using (var aes = new AesCryptoServiceProvider()) {
                aes.Key = key;
                aes.IV  = iv;

                using (var cipherText = new MemoryStream()) using (var cryptoStream = new CryptoStream(cipherText, aes.CreateEncryptor(), CryptoStreamMode.Write)) {
                        cryptoStream.Write(message, offset, length);
                        cryptoStream.Close();

                        return(cipherText.ToArray());
                    }
            }
        }
Пример #2
0
        /// <summary>
        /// Encrypt or decrypt an input byte array
        /// </summary>
        /// <param name="inputBytes">byte array to be encrypted or decrypted</param>
        /// <param name="encrypt">true: encrypt; false: decrypt</param>
        /// <returns>Encrypted or decrypted byte array</returns>
        private byte[] CryptBytes(byte[] inputBytes, byte[] passcode, bool encrypt)
        {
            byte[] outputBytes = null;
            byte[] key         = null;
            byte[] iv          = null;

            int saltSize = 16;

            using (MemoryStream ms = new MemoryStream())
            {
                using (AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider())
                {
                    if (aesProvider.KeySize < 256)
                    {
                        aesProvider.KeySize = 256;
                    }

                    if (encrypt)
                    {
                        // 16-byte random salt
                        byte[] salt = GenerateRandomSalt(saltSize, saltSize);

                        GenerateKeyAndIV(passcode, salt, aesProvider.KeySize, aesProvider.BlockSize, out key, out iv);

                        using (ICryptoTransform cryptor = aesProvider.CreateEncryptor(key, iv))
                        {
                            using (CryptoStream cryptoStream = new CryptoStream(ms, cryptor, CryptoStreamMode.Write))
                            {
                                cryptoStream.Write(inputBytes, 0, inputBytes.Length);
                                cryptoStream.Close();

                                // put the salt in the begin of the output byte array
                                outputBytes = salt.Concat(ms.ToArray()).ToArray();
                            }
                        }
                    }
                    else
                    {
                        // get salt from input byte array
                        byte[] salt = new byte[saltSize];
                        Array.Copy(inputBytes, salt, saltSize);

                        GenerateKeyAndIV(passcode, salt, aesProvider.KeySize, aesProvider.BlockSize, out key, out iv);

                        using (ICryptoTransform cryptor = aesProvider.CreateDecryptor(key, iv))
                        {
                            int byteSize = inputBytes.Length - saltSize;
                            if (byteSize > 0)
                            {
                                byte[] encryptedBytes = new byte[byteSize];
                                Array.Copy(inputBytes, saltSize, encryptedBytes, 0, byteSize);

                                using (CryptoStream cryptoStream = new CryptoStream(ms, cryptor, CryptoStreamMode.Write))
                                {
                                    cryptoStream.Write(encryptedBytes, 0, inputBytes.Length);
                                    cryptoStream.Close();
                                    outputBytes = ms.ToArray();
                                }
                            }
                        }
                    }
                }
            }

            return(outputBytes);
        }
        /// <summary>
        ///     Encrypts the given file, using the private hashed hashedKey
        /// </summary>
        /// <param name="originalFile"></param>
        /// <param name="key"></param>
        /// <param name="deleteOriginalSafely"></param>
        public static FileInfo Encrypt(FileInfo originalFile, string key, bool deleteOriginalSafely = false)
        {
            if (originalFile == null)
            {
                throw new ArgumentNullException(nameof(originalFile));
            }
            if (!originalFile.Exists)
            {
                throw new ArgumentException($"{nameof(originalFile)} points to a non-existant file");
            }
            if (Directory.Exists(originalFile.FullName))
            {
                throw new ArgumentException($"{nameof(originalFile)} points to a folder, not a file");
            }
            // ready encryption hashedKey and info
            var info = new EncryptionInfo
            {
                Version             = Application.ProductVersion,
                HashAlgorithm       = typeof(SHA256CryptoServiceProvider),
                EncryptionAlgorithm = typeof(AesCryptoServiceProvider),
                KeySize             = 256,
                BlockSize           = 128,
                SaltSize            = 128
            };

            byte[] hashedKey;
            EncryptKey(key, info, out hashedKey);

            // hash original file
            var hash    = Hash(originalFile, info.HashAlgorithm);
            var newFile = Core.GetNonCollidingFile(originalFile.FullName + Settings.Default.Extension);

            // encrypt original file with info header in the start
            using (var tempFiles = new TempFileGenerator())
                using (var crypter = new AesCryptoServiceProvider())
                {
                    // load hashedKey and IV into cryptography service
                    crypter.Key = hashedKey;
                    crypter.GenerateIV();
                    //Debug.Assert(crypter.ValidKeySize(256));

                    // create temporary files
                    var zippedFile = tempFiles.CreateFile();

                    // zip original file into temporary zipped file
                    using (var zippedFs = zippedFile.OpenWrite())
                        using (var zipper = new GZipStream(zippedFs, CompressionMode.Compress))
                            using (var originalFs = originalFile.OpenRead())
                                originalFs.CopyTo(zipper);
                    //progressBar.BeginInvoke(new Action(() => { progressBar.Increment(5); }));

                    // add Json header to final file with a text stream
                    using (var newFs = newFile.CreateText())
                    {
                        info.OriginalHash = hash;
                        info.Iv           = crypter.IV;
                        newFs.Write(JsonConvert.SerializeObject(info));
                    }

                    // encrypt zipped file into final file, as an append
                    using (var zippedFs = zippedFile.OpenRead())
                        using (
                            var cs = new CryptoStream(zippedFs, crypter.CreateEncryptor(), CryptoStreamMode.Read))
                            using (var newFs = newFile.Open(FileMode.Open, FileAccess.ReadWrite))
                            {
                                newFs.Seek(0, SeekOrigin.End);
                                cs.CopyTo(newFs);
                            }

                    // delete hashed key
                    Core.ShallowEraseList(hashedKey);

                    // safely delete the zipped file, as it shouldn't stay in the OS like that
                    SafeOverwriteFile(zippedFile);
                    zippedFile.Delete();
                }

            // safe deleting of the original file
            if (!deleteOriginalSafely)
            {
                return(newFile);
            }
            SafeOverwriteFile(originalFile);
            originalFile.Delete();
            return(newFile);
        }
Пример #4
0
        public static void CreateUser(object obj)
        {
            string account, pwd, name, email, title;

            object[] args = (object[])obj;
            account = (string)args[0];
            pwd     = (string)args[1];
            name    = (string)args[2];
            email   = (string)args[3];
            title   = (string)args[4];
            MainForm form = (MainForm)args[5];

            form.UpdateText("Check if user already exist");
            User user = (from u in db.User where u.UID.Equals(account) select u).FirstOrDefault();

            form.UpdateLog("Check if user already exist");
            if (user != null)
            {
                form.UpdateLog("User already exist");
            }
            else
            {
                form.UpdateText("Create new account");
                AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
                form.UpdateLog("Create new account");

                form.UpdateText("Encrypt password");
                byte[]             key     = Encoding.UTF8.GetBytes(pwd);
                Rfc2898DeriveBytes rfcKey  = new Rfc2898DeriveBytes(key, salt, 16);
                byte[]             keyData = rfcKey.GetBytes(16);
                aes.Key = keyData;

                string iv            = Convert.ToBase64String(aes.IV);
                byte[] dataByteArray = Encoding.UTF8.GetBytes(account);

                string encrypt = "";
                using (MemoryStream ms = new MemoryStream())
                    using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(dataByteArray, 0, dataByteArray.Length);
                        cs.FlushFinalBlock();
                        encrypt = Convert.ToBase64String(ms.ToArray());
                    }
                form.UpdateLog("Encrypt password");
                user           = new User();
                user.UID       = account;
                user.Password  = encrypt;
                user.IV        = iv;
                user.Name      = name;
                user.Email     = email;
                user.Title     = title;
                user.Authority = 0;

                form.UpdateText("Update database");
                db.User.Add(user);
                db.SaveChanges();
                form.UpdateLog("Update database");

                form.UpdateText("Create user [ " + account + " ] successful");
                form.UpdateLog("Create user [ " + account + " ] successful");
            }
        }
Пример #5
0
        // Encrypt the data in the input stream into the output stream.
        public static void CryptStream(string password, Stream in_stream, Stream out_stream, bool encrypt)
        {
            // Make an AES service provider.
            AesCryptoServiceProvider aes_provider = new AesCryptoServiceProvider();

            // Find a valid key size for this provider.
            int key_size_bits = 0;

            for (int i = 1024; i > 1; i--)
            {
                if (aes_provider.ValidKeySize(i))
                {
                    key_size_bits = i;
                    break;
                }
            }
            Debug.Assert(key_size_bits > 0);
            Console.WriteLine("Key size: " + key_size_bits);

            // Get the block size for this provider.
            int block_size_bits = aes_provider.BlockSize;

            // Generate the key and initialization vector.
            byte[] key  = null;
            byte[] iv   = null;
            byte[] salt = { 0x0, 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0xF1, 0xF0, 0xEE, 0x21, 0x22, 0x45 };
            MakeKeyAndIV(password, salt, key_size_bits, block_size_bits, out key, out iv);

            // Make the encryptor or decryptor.
            ICryptoTransform crypto_transform;

            if (encrypt)
            {
                crypto_transform = aes_provider.CreateEncryptor(key, iv);
            }
            else
            {
                crypto_transform = aes_provider.CreateDecryptor(key, iv);
            }

            // Attach a crypto stream to the output stream.
            // Closing crypto_stream sometimes throws an
            // exception if the decryption didn't work
            // (e.g. if we use the wrong password).
            try
            {
                using (CryptoStream crypto_stream = new CryptoStream(out_stream, crypto_transform, CryptoStreamMode.Write))
                {
                    // Encrypt or decrypt the file.
                    const int block_size = 1024;
                    byte[]    buffer     = new byte[block_size];
                    int       bytes_read;
                    while (true)
                    {
                        // Read some bytes.
                        bytes_read = in_stream.Read(buffer, 0, block_size);
                        if (bytes_read == 0)
                        {
                            break;
                        }

                        // Write the bytes into the CryptoStream.
                        crypto_stream.Write(buffer, 0, bytes_read);
                    }
                } // using crypto_stream
            }
            catch
            {
            }

            crypto_transform.Dispose();
        }
Пример #6
0
 public byte[] Encrypt(byte[] inputBuffer)
 {
     return(_aes.CreateEncryptor().TransformFinalBlock(inputBuffer, 0, inputBuffer.Length));
 }
Пример #7
0
        /// <summary>
        /// Saves current game information. Remove save file if the saving process was incorrect.
        /// </summary>
        public void SaveGame()
        {
            if (game.Status != GameStatus.OnGoing)
            {
                return;
            }

            SaveFile save = game.SaveGame();

            try
            {
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    // Serialize the SaveFile.
                    DataContractSerializer serializer = new DataContractSerializer(typeof(SaveFile));
                    serializer.WriteObject(memoryStream, save);
                    memoryStream.Position = 0L;

                    using (StreamReader memoryStreamReader = new StreamReader(memoryStream))

                        // Save to .xml and encrypt with AES.
                        try
                        {
                            using (Stream fileStream = new FileStream(FILE_NAME, FileMode.Create, FileAccess.Write, FileShare.None))
                            {
                                AesCryptoServiceProvider aesCryptoService = new AesCryptoServiceProvider();

                                using (ICryptoTransform cryptoTransform = aesCryptoService.CreateEncryptor(
                                           EncryptionValues.EncryptionKey,
                                           EncryptionValues.EncryptionInitializationVector))

                                    using (CryptoStream cryptoStream = new CryptoStream(fileStream, cryptoTransform, CryptoStreamMode.Write))

                                        using (StreamWriter cryptoStreamWriter = new StreamWriter(cryptoStream))
                                        {
                                            string dataToEncrypt = memoryStreamReader.ReadToEnd();
                                            cryptoStreamWriter.Write(dataToEncrypt);

                                            cryptoStreamWriter.Flush();
                                        }

                                aesCryptoService.Dispose();
                            }
                        }
                        catch (FileNotFoundException exception)
                        {
                            view.AskUserForInput($"{ConsoleMessages.FileNotFoundException} {exception.Message}");
                        }
                    catch (ArgumentNullException exception)
                    {
                        view.AskUserForInput($"{ConsoleMessages.ArgumentNullException} {exception.Message}");
                    }
                    catch (ArgumentException exception)
                    {
                        view.AskUserForInput($"{ConsoleMessages.ArgumentException} {exception.Message}");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"{ConsoleMessages.SaveExcepton} {ex.Message}");
                RemoveSaveFile();
                Console.ReadKey();
            }
        }
Пример #8
0
        /// <summary>
        /// 根据指定的密钥使用AES-128-CBC加密字符串
        /// </summary>
        /// <param name="OriginText">要加密的内容</param>
        /// <param name="Key">密钥</param>
        /// <returns></returns>
        public static async Task <string> EncryptAsync(this string OriginText, string Key)
        {
            if (string.IsNullOrEmpty(OriginText))
            {
                throw new ArgumentNullException(nameof(OriginText), "Parameter could not be null or empty");
            }

            if (string.IsNullOrEmpty(Key))
            {
                throw new ArgumentNullException(nameof(Key), "Parameter could not be null or empty");
            }

            try
            {
                using (SecureString Secure = SecureAccessProvider.GetStringEncryptionAesIV(Package.Current))
                {
                    IntPtr Bstr = Marshal.SecureStringToBSTR(Secure);
                    string IV   = Marshal.PtrToStringBSTR(Bstr);

                    try
                    {
                        using (AesCryptoServiceProvider AES = new AesCryptoServiceProvider
                        {
                            KeySize = 128,
                            Key = Key.Length > 16 ? Encoding.UTF8.GetBytes(Key.Substring(0, 16)) : Encoding.UTF8.GetBytes(Key.PadRight(16, '0')),
                            Mode = CipherMode.CBC,
                            Padding = PaddingMode.PKCS7,
                            IV = Encoding.UTF8.GetBytes(IV)
                        })
                        {
                            using (MemoryStream EncryptStream = new MemoryStream())
                            {
                                using (ICryptoTransform Encryptor = AES.CreateEncryptor())
                                    using (CryptoStream TransformStream = new CryptoStream(EncryptStream, Encryptor, CryptoStreamMode.Write))
                                    {
                                        using (StreamWriter Writer = new StreamWriter(TransformStream))
                                        {
                                            await Writer.WriteAsync(OriginText).ConfigureAwait(false);
                                        }
                                    }

                                return(Convert.ToBase64String(EncryptStream.ToArray()));
                            }
                        }
                    }
                    finally
                    {
                        Marshal.ZeroFreeBSTR(Bstr);
                        unsafe
                        {
                            fixed(char *ClearPtr = IV)
                            {
                                for (int i = 0; i < IV.Length; i++)
                                {
                                    ClearPtr[i] = '\0';
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                return(null);
            }
        }
Пример #9
0
        public ActionResult Index(SymmetricModel model)
        {
            if (model.Action == "encrypt")
            {
                var    plainTextAsBytes = Encoding.Unicode.GetBytes(model.PlainText);
                var    cryptoProvider   = new AesCryptoServiceProvider();
                byte[] masterKey;

                if (!string.IsNullOrWhiteSpace(model.Key))
                {
                    if (!string.IsNullOrWhiteSpace(model.IV))
                    {
                        cryptoProvider.Key = Convert.FromBase64String(model.Key);
                        cryptoProvider.IV  = Convert.FromBase64String(model.IV);
                    }
                    else
                    {
                        throw new Exception("If you provide a key or IV you must provide both.");
                    }
                }
                else if (!string.IsNullOrEmpty(model.IV))
                {
                    throw new Exception("If you provide a key or IV you must provide both.");
                }

                masterKey = cryptoProvider.Key;
                var encryptionKey = DeriveKey("encryption", masterKey, cryptoProvider.KeySize / 8);
                var signingKey    = DeriveKey("signature", masterKey, 64);

                ICryptoTransform cryptoTransform =
                    cryptoProvider.CreateEncryptor(encryptionKey, cryptoProvider.IV);

                var outputStream = new MemoryStream();
                var cryptoStream = new CryptoStream(
                    outputStream,
                    cryptoTransform,
                    CryptoStreamMode.Write);

                cryptoStream.Write(plainTextAsBytes, 0, plainTextAsBytes.Length);
                cryptoStream.FlushFinalBlock();

                byte[] cipherTextAsBytes = outputStream.ToArray();

                var signingAlgorithm = new HMACSHA256(signingKey);
                var signature        = signingAlgorithm.ComputeHash(cipherTextAsBytes);

                model.PlainText  = string.Empty;
                model.CipherText = Convert.ToBase64String(cipherTextAsBytes);
                model.Key        = Convert.ToBase64String(masterKey);
                model.IV         = Convert.ToBase64String(cryptoProvider.IV);
                model.Signature  = Convert.ToBase64String(signature);
            }
            else if (model.Action == "decrypt")
            {
                var    cipherTextAsBytes = Convert.FromBase64String(model.CipherText);
                var    cryptoProvider    = new AesCryptoServiceProvider();
                byte[] masterKey;

                cryptoProvider.Key = Convert.FromBase64String(model.Key);
                cryptoProvider.IV  = Convert.FromBase64String(model.IV);

                masterKey = cryptoProvider.Key;
                var encryptionKey = DeriveKey("encryption", masterKey, cryptoProvider.KeySize / 8);
                var signingKey    = DeriveKey("signature", masterKey, 64);

                var signingAlgorithm = new HMACSHA256(signingKey);
                var signature        = signingAlgorithm.ComputeHash(cipherTextAsBytes);

                if (!HashCompare(signature, Convert.FromBase64String(model.Signature)))
                {
                    throw new Exception("Invalid Signature.");
                }

                ICryptoTransform cryptoTransform =
                    cryptoProvider.CreateDecryptor(encryptionKey, cryptoProvider.IV);

                var outputStream = new MemoryStream();
                var cryptoStream = new CryptoStream(
                    outputStream,
                    cryptoTransform,
                    CryptoStreamMode.Write);

                cryptoStream.Write(cipherTextAsBytes, 0, cipherTextAsBytes.Length);
                cryptoStream.FlushFinalBlock();

                byte[] plainTextAsBytes = outputStream.ToArray();
                model.PlainText  = Encoding.Unicode.GetString(plainTextAsBytes);
                model.CipherText = string.Empty;
            }

            ModelState.Clear();

            return(View(model));
        }
Пример #10
0
        private void personSendBtn_Click(object sender, EventArgs e)
        {
            bool person1To2 = int.Parse(((Button)sender).Tag.ToString()) == 1;

            string messageToSend = person1To2 ? txt_Giden_Mesaj_Kul_1.Text : txt_Giden_Mesaj_Kul_2.Text;

            if (person1PublicKey == null || person1PublicKey.Length <= 0)
            {
                GenerateKeys();
            }

            // Gönderiliyor

            using (Aes aes = new AesCryptoServiceProvider())
            {
                aes.Key = commonKey;

                if (IV == null || IV.Length <= 0)
                {
                    IV = aes.IV;
                }
                else
                {
                    aes.IV = IV;
                }

                ECDiffieHellmanCng_Class.txt_Ortak_Anahtar = Convert.ToBase64String(IV);
                txt_Baslatma_Vektoru_IV.Text = Convert.ToBase64String(IV);

                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        byte[] plainTextMessage = Encoding.UTF8.GetBytes(messageToSend);
                        cs.Write(plainTextMessage, 0, plainTextMessage.Length);
                        cs.Close();

                        if (person1To2)
                        {
                            encryptedMessage1 = ms.ToArray();
                            txt_Sifreli_Gelen_Mesaj_kul_2.Text = Convert.ToBase64String(encryptedMessage1);
                        }
                        else
                        {
                            encryptedMessage2 = ms.ToArray();
                            txt_Sifreli_Gelen_Mesaj_kul_1.Text = Convert.ToBase64String(encryptedMessage2);
                        }
                    }
                }
            }

            // Alınıyor

            using (Aes aes = new AesCryptoServiceProvider())
            {
                aes.Key = commonKey;
                aes.IV  = IV;

                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        if (person1To2)
                        {
                            cs.Write(encryptedMessage1, 0, encryptedMessage1.Length);
                        }
                        else
                        {
                            cs.Write(encryptedMessage2, 0, encryptedMessage2.Length);
                        }

                        cs.Close();

                        string receivedMessage = Encoding.UTF8.GetString(ms.ToArray());

                        if (person1To2)
                        {
                            txt_Gelen_Mesaj_Kul_2.Text = receivedMessage;
                        }
                        else
                        {
                            txt_Gelen_Mesaj_Kul_1.Text = receivedMessage;
                        }
                    }
                }
            }
        }
Пример #11
0
        bool IEncryptionDriver.EncryptInit(int session, int alg, IntPtr algParam, int algParamLen, int hKey)
        {
            try
            {
                SessionData ctx = ((SessionDriver)this.Hal.Session).GetSessionCtx(session);

                KeyData        kd  = null;
                CryptokiObject obj = ctx.ObjectCtx.GetObject(hKey);

                if (obj == null)
                {
                    return(false);
                }

                if (obj.Type == CryptokiObjectType.Key)
                {
                    kd = obj.Data as KeyData;
                }
                else if (obj.Type == CryptokiObjectType.Cert)
                {
                    X509Certificate2 cert = obj.Data as X509Certificate2;

                    AsymmetricAlgorithm encAlg = cert.PublicKey.Key;

                    kd = new KeyData(null, encAlg);
                }
                else
                {
                    return(false);
                }

                byte[] keyData = kd.KeyBytes;
                byte[] IV      = null;

                if (algParam != IntPtr.Zero)
                {
                    IV = new byte[algParamLen];

                    Marshal.Copy(algParam, IV, 0, algParamLen);
                }

                ctx.EncryptCtx.CryptoAlgorithm = (AlgorithmType)alg;

                switch ((AlgorithmType)alg)
                {
                case AlgorithmType.DES3_CBC_PAD:
                {
                    TripleDESCryptoServiceProvider des3 = new TripleDESCryptoServiceProvider();
                    des3.Padding = PaddingMode.PKCS7;
                    ctx.EncryptCtx.CryptoObject    = des3;
                    ctx.EncryptCtx.CryptoTransform = des3.CreateEncryptor(keyData, IV);
                }
                break;

                case AlgorithmType.DES3_CBC:
                {
                    TripleDESCryptoServiceProvider des3 = new TripleDESCryptoServiceProvider();
                    des3.Padding = PaddingMode.None;
                    ctx.EncryptCtx.CryptoObject    = des3;
                    ctx.EncryptCtx.CryptoTransform = des3.CreateEncryptor(keyData, IV);
                }
                break;

                case AlgorithmType.AES_CBC_PAD:
                {
                    AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
                    aes.Padding = PaddingMode.PKCS7;
                    aes.Mode    = CipherMode.CBC;
                    ctx.EncryptCtx.CryptoObject    = aes;
                    ctx.EncryptCtx.CryptoTransform = aes.CreateEncryptor(keyData, IV);
                }
                break;

                case AlgorithmType.AES_ECB_PAD:
                {
                    AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
                    aes.Padding = PaddingMode.PKCS7;
                    aes.Mode    = CipherMode.ECB;
                    ctx.EncryptCtx.CryptoObject    = aes;
                    ctx.EncryptCtx.CryptoTransform = aes.CreateEncryptor(keyData, IV);
                }
                break;

                case AlgorithmType.AES_CBC:
                {
                    AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
                    aes.Padding = PaddingMode.None;
                    aes.Mode    = CipherMode.CBC;
                    ctx.EncryptCtx.CryptoObject    = aes;
                    ctx.EncryptCtx.CryptoTransform = aes.CreateEncryptor(keyData, IV);
                }
                break;

                case AlgorithmType.AES_ECB:
                {
                    AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
                    aes.Padding = PaddingMode.None;
                    aes.Mode    = CipherMode.ECB;
                    ctx.EncryptCtx.CryptoObject    = aes;
                    ctx.EncryptCtx.CryptoTransform = aes.CreateEncryptor(keyData, IV);
                }
                break;

                case AlgorithmType.RSA_PKCS:
                    if (keyData == null)
                    {
                        ctx.EncryptCtx.CryptoObject = kd.KeyCsp as IDisposable;
                    }
                    else
                    {
                        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                        ctx.EncryptCtx.CryptoObject = rsa;
                        rsa.ImportCspBlob(keyData);
                        ctx.EncryptCtx.CryptoTransform = null;
                    }
                    break;

                case AlgorithmType.DSA:
                case AlgorithmType.DSA_SHA1:
                    if (keyData == null)
                    {
                        ctx.EncryptCtx.CryptoObject = kd.KeyCsp as IDisposable;
                    }
                    else
                    {
                        DSACryptoServiceProvider dsa = new DSACryptoServiceProvider();
                        ctx.EncryptCtx.CryptoObject    = dsa;
                        ctx.EncryptCtx.CryptoTransform = null;
                        dsa.ImportCspBlob(keyData);
                    }
                    break;

                default:
                    return(false);
                }
            }
            catch (Exception e)
            {
                Debug.Print(e.ToString());
                return(false);
            }

            return(true);
        }
Пример #12
0
        public async Task<FileSystemStorageFile> EncryptAsync(string OutputDirectory, string Key, int KeySize, CancellationToken CancelToken = default)
        {
            if (string.IsNullOrWhiteSpace(OutputDirectory))
            {
                throw new ArgumentNullException(nameof(OutputDirectory), "Argument could not be null");
            }

            if (KeySize != 256 && KeySize != 128)
            {
                throw new InvalidEnumArgumentException("AES密钥长度仅支持128或256任意一种");
            }

            if (string.IsNullOrEmpty(Key))
            {
                throw new ArgumentNullException(nameof(Key), "Parameter could not be null or empty");
            }

            int KeyLengthNeed = KeySize / 8;

            byte[] KeyArray = Key.Length > KeyLengthNeed
                               ? Encoding.UTF8.GetBytes(Key.Substring(0, KeyLengthNeed))
                               : Encoding.UTF8.GetBytes(Key.PadRight(KeyLengthNeed, '0'));

            string EncryptedFilePath = System.IO.Path.Combine(OutputDirectory, $"{System.IO.Path.GetFileNameWithoutExtension(Name)}.sle");

            if (await CreateAsync(EncryptedFilePath, StorageItemTypes.File, CreateOption.GenerateUniqueName) is FileSystemStorageFile EncryptedFile)
            {
                using (FileStream EncryptFileStream = await EncryptedFile.GetFileStreamFromFileAsync(AccessMode.Write))
                {
                    string IV = SecureAccessProvider.GetFileEncryptionAesIV(Package.Current);

                    using (AesCryptoServiceProvider AES = new AesCryptoServiceProvider
                    {
                        KeySize = KeySize,
                        Key = KeyArray,
                        Mode = CipherMode.CBC,
                        Padding = PaddingMode.Zeros,
                        IV = Encoding.UTF8.GetBytes(IV)
                    })
                    {
                        using (FileStream OriginFileStream = await GetFileStreamFromFileAsync(AccessMode.Read))
                        using (ICryptoTransform Encryptor = AES.CreateEncryptor())
                        {
                            byte[] ExtraInfoPart1 = Encoding.UTF8.GetBytes($"${KeySize}|{System.IO.Path.GetExtension(Path)}$");
                            await EncryptFileStream.WriteAsync(ExtraInfoPart1, 0, ExtraInfoPart1.Length, CancelToken);

                            byte[] PasswordConfirm = Encoding.UTF8.GetBytes("PASSWORD_CORRECT");
                            byte[] PasswordConfirmEncrypted = Encryptor.TransformFinalBlock(PasswordConfirm, 0, PasswordConfirm.Length);
                            await EncryptFileStream.WriteAsync(PasswordConfirmEncrypted, 0, PasswordConfirmEncrypted.Length, CancelToken);

                            using (CryptoStream TransformStream = new CryptoStream(EncryptFileStream, Encryptor, CryptoStreamMode.Write))
                            {
                                await OriginFileStream.CopyToAsync(TransformStream, 2048, CancelToken);
                            }
                        }
                    }
                }

                await EncryptedFile.RefreshAsync();

                return EncryptedFile;
            }
            else
            {
                return null;
            }
        }
Пример #13
0
 /* Good1() changes the "if" so that both branches use the GoodSink */
 private void Good1()
 {
     if (IO.StaticReturnsTrueOrFalse())
     {
         string text           = "asdf";
         byte[] byteCipherText = null;
         using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider())
         {
             int    blockSize            = aes.BlockSize;
             byte[] initializationVector = new byte[blockSize / 8];
             /* FIX: using cryptographically secure pseudo-random number as initialization vector */
             using (RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider())
             {
                 provider.GetBytes(initializationVector);
             }
             // Create an encryptor to perform the stream transform.
             ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, initializationVector);
             // Create the streams used for encryption.
             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(text);
                     }
                     byteCipherText = msEncrypt.ToArray();
                 }
             }
         }
         IO.WriteLine(IO.ToHex(byteCipherText)); /* Write encrypted data to console */
     }
     else
     {
         string text           = "asdf";
         byte[] byteCipherText = null;
         using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider())
         {
             int    blockSize            = aes.BlockSize;
             byte[] initializationVector = new byte[blockSize / 8];
             /* FIX: using cryptographically secure pseudo-random number as initialization vector */
             using (RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider())
             {
                 provider.GetBytes(initializationVector);
             }
             // Create an encryptor to perform the stream transform.
             ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, initializationVector);
             // Create the streams used for encryption.
             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(text);
                     }
                     byteCipherText = msEncrypt.ToArray();
                 }
             }
         }
         IO.WriteLine(IO.ToHex(byteCipherText)); /* Write encrypted data to console */
     }
 }
Пример #14
0
        private void button2_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                SaveFileDialog sfd = new SaveFileDialog();

                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        byte[] AES_KEY =
                        {
                            0xB4, 0xEB, 0x7F, 0xB9,
                            0xA9, 0xAC, 0x05, 0x92,
                            0xAB, 0x8E, 0x42, 0xAB,
                            0xCC, 0x61, 0xD0, 0xC0
                        };

                        byte[] HMAC_KEY =
                        {
                            0x82, 0xF4, 0x1A, 0x4F,
                            0x03, 0x45, 0x65, 0x01,
                            0x2F, 0x73, 0x9C, 0x4D,
                            0x8E, 0x63, 0xA9, 0x1F,
                            0xB9, 0x2B, 0x9D, 0x4E,
                            0xE1, 0x11, 0x91, 0x47,
                            0xD4, 0x3C, 0xC6, 0x88,
                            0x3F, 0xC7, 0xFC, 0x70
                        };

                        BinaryReader reader = new BinaryReader(new FileStream(ofd.FileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite));
                        BinaryWriter writer = new BinaryWriter(new FileStream(sfd.FileName, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite));

                        byte[] ProfileID = HexStringToByteArray(textBox1.Text);

                        if (reader.ReadUInt32() != 0x73736D63)
                        {
                            throw new Exception("Invalid File");
                        }

                        uint ReadSize = BSwapUint(reader.ReadUInt32());

                        byte[] Hash        = reader.ReadBytes(0x20);
                        uint   DataSizeEnc = BSwapUint(reader.ReadUInt32());
                        byte[] AES_IV      = reader.ReadBytes(0x10);

                        uint   DataSizeDec = DecryptDataSize(AES_IV, DataSizeEnc);
                        byte[] DataBuffer  = reader.ReadBytes((int)(DataSizeDec));

                        XorAes(ref AES_KEY, ProfileID, 1);

                        AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
                        aes.Mode    = CipherMode.CBC;
                        aes.Padding = PaddingMode.None;

                        byte[] Encrypted = aes.CreateEncryptor(AES_KEY, AES_IV).TransformFinalBlock(DataBuffer, 0, DataBuffer.Length);

                        XorHmac(ref HMAC_KEY, ProfileID, 0);
                        HMACSHA256 hmac = new HMACSHA256(HMAC_KEY);

                        byte[] Tmp = new byte[0x14];
                        Buffer.BlockCopy(BitConverter.GetBytes(BSwapUint(DataSizeEnc)), 0, Tmp, 0, 4);
                        Buffer.BlockCopy(AES_IV, 0, Tmp, 4, 0x10);

                        hmac.TransformBlock(Tmp, 0, 0x14, null, 0);
                        hmac.TransformFinalBlock(Encrypted, 0, Encrypted.Length);

                        writer.Write(0x73736D63);
                        writer.Write(BSwapUint(ReadSize));
                        writer.Write(hmac.Hash);
                        writer.Write(BSwapUint(DataSizeEnc));
                        writer.Write(AES_IV);
                        writer.Write(Encrypted);

                        writer.Flush();
                        writer.Close();
                        reader.Close();
                    }
                    catch (Exception x)
                    {
                        MessageBox.Show(x.Message);
                    }
                }
            }
        }
Пример #15
0
        public string Encrypt(EncoderType type, string encrypt)
        {
            string ret = "";

            byte[] inputByteArray = Encoding.UTF8.GetBytes(encrypt);
            byte[] rgbKey         = Convert.FromBase64String(Key);
            byte[] rgbIV          = Convert.FromBase64String(IV);
            switch (type)
            {
            case EncoderType.AES:
                using (AesCryptoServiceProvider csp = new AesCryptoServiceProvider())
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (CryptoStream cs = new CryptoStream(ms, csp.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write))
                        {
                            cs.Write(inputByteArray, 0, inputByteArray.Length);
                            cs.FlushFinalBlock();
                            ret = Convert.ToBase64String(ms.ToArray());
                        }
                    }
                }
                break;

            case EncoderType.DES:
                using (DESCryptoServiceProvider csp = new DESCryptoServiceProvider())
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (CryptoStream cs = new CryptoStream(ms, csp.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write))
                        {
                            cs.Write(inputByteArray, 0, inputByteArray.Length);
                            cs.FlushFinalBlock();
                            ret = Convert.ToBase64String(ms.ToArray());
                        }
                    }
                }
                break;

            case EncoderType.RC2:
                using (RC2CryptoServiceProvider csp = new RC2CryptoServiceProvider())
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (CryptoStream cs = new CryptoStream(ms, csp.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write))
                        {
                            cs.Write(inputByteArray, 0, inputByteArray.Length);
                            cs.FlushFinalBlock();
                            ret = Convert.ToBase64String(ms.ToArray());
                        }
                    }
                }
                break;

            case EncoderType.TripleDES:
                using (TripleDESCryptoServiceProvider csp = new TripleDESCryptoServiceProvider())
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (CryptoStream cs = new CryptoStream(ms, csp.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write))
                        {
                            cs.Write(inputByteArray, 0, inputByteArray.Length);
                            cs.FlushFinalBlock();
                            ret = Convert.ToBase64String(ms.ToArray());
                        }
                    }
                }
                break;

            case EncoderType.RSA:
                using (RSACryptoServiceProvider csp = new RSACryptoServiceProvider())
                {
                    csp.FromXmlString(Key);
                    ret = Convert.ToBase64String(csp.Encrypt(inputByteArray, false));
                }
                break;

            case EncoderType.MD5:
                using (MD5CryptoServiceProvider csp = new MD5CryptoServiceProvider())
                {
                    ret = BitConverter.ToString(csp.ComputeHash(inputByteArray)).Replace("-", string.Empty);
                }
                break;

            case EncoderType.SHA1:
                using (SHA1CryptoServiceProvider csp = new SHA1CryptoServiceProvider())
                {
                    ret = BitConverter.ToString(csp.ComputeHash(inputByteArray)).Replace("-", string.Empty);
                }
                break;

            case EncoderType.SHA256:
                using (SHA256CryptoServiceProvider csp = new SHA256CryptoServiceProvider())
                {
                    ret = BitConverter.ToString(csp.ComputeHash(inputByteArray)).Replace("-", string.Empty);
                }
                break;

            case EncoderType.SHA384:
                using (SHA384CryptoServiceProvider csp = new SHA384CryptoServiceProvider())
                {
                    ret = BitConverter.ToString(csp.ComputeHash(inputByteArray)).Replace("-", string.Empty);
                }
                break;

            case EncoderType.SHA512:
                using (SHA512CryptoServiceProvider csp = new SHA512CryptoServiceProvider())
                {
                    ret = BitConverter.ToString(csp.ComputeHash(inputByteArray)).Replace("-", string.Empty);
                }
                break;
            }
            return(ret);
        }
        public HttpResponseMessage AddFifty([FromUri] string encryptedInteger, string encryptedSymKey, string encryptedIV)
        {
            IEnumerable <string> key;

            Request.Headers.TryGetValues("ApiKey", out key);

            string APIKey = key.First();

            database.createLog("User requested /Protected/AddFifty", APIKey);

            string[] split            = encryptedInteger.Split('-');
            byte[]   asciiByteMessage = new byte[split.Length];
            for (int i = 0; i < split.Length; i++)
            {
                asciiByteMessage[i] = Convert.ToByte(split[i], 16);
            }

            byte[] integer = WebApiConfig.RSA.Decrypt(asciiByteMessage, false);

            split            = encryptedSymKey.Split('-');
            asciiByteMessage = new byte[split.Length];
            for (int i = 0; i < split.Length; i++)
            {
                asciiByteMessage[i] = Convert.ToByte(split[i], 16);
            }

            byte[] symKey = WebApiConfig.RSA.Decrypt(asciiByteMessage, false);

            split            = encryptedIV.Split('-');
            asciiByteMessage = new byte[split.Length];
            for (int i = 0; i < split.Length; i++)
            {
                asciiByteMessage[i] = Convert.ToByte(split[i], 16);
            }

            byte[] iv = WebApiConfig.RSA.Decrypt(asciiByteMessage, false);

            string temp = System.Text.Encoding.ASCII.GetString(integer);

            int addFifty = Convert.ToInt32(temp);

            addFifty += 50;

            AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider();

            aesProvider.Key = symKey;
            aesProvider.IV  = iv;
            byte[]           temp1key  = aesProvider.Key;
            byte[]           temp2     = aesProvider.IV;
            ICryptoTransform encryptor = aesProvider.CreateEncryptor();

            byte[] encryptedAddFifty;

            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter sw = new StreamWriter(cs))
                    {
                        sw.Write(addFifty);
                    }
                    encryptedAddFifty = ms.ToArray();
                }
            }

            return(Request.CreateResponse(HttpStatusCode.OK, BitConverter.ToString(encryptedAddFifty)));
        }
 /// <summary>
 /// Start encrypting stream
 /// </summary>
 /// <param name="inputStream">Stream to encrypt</param>
 /// <param name="cryptoStreamMode">Streaming mode</param>
 /// <returns></returns>
 public CryptoStream EncryptStream(Stream inputStream, CryptoStreamMode cryptoStreamMode)
 {
     return(new CryptoStream(inputStream, aes.CreateEncryptor(), cryptoStreamMode));
 }
Пример #18
0
        // Note that extension methods must be defined in a non-generic static class.

        // Encrypt or decrypt the data in in_bytes[] and return the result.
        public static byte[] CryptBytes(string password, byte[] in_bytes, bool encrypt)
        {
            // Make an AES service provider.
            AesCryptoServiceProvider aes_provider = new AesCryptoServiceProvider();

            // Find a valid key size for this provider.
            int key_size_bits = 0;

            for (int i = 1024; i > 1; i--)
            {
                if (aes_provider.ValidKeySize(i))
                {
                    key_size_bits = i;
                    break;
                }
            }
            Debug.Assert(key_size_bits > 0);
            Console.WriteLine("Key size: " + key_size_bits);

            // Get the block size for this provider.
            int block_size_bits = aes_provider.BlockSize;

            // Generate the key and initialization vector.
            byte[] key  = null;
            byte[] iv   = null;
            byte[] salt = { 0x0, 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0xF1, 0xF0, 0xEE, 0x21, 0x22, 0x45 };
            MakeKeyAndIV(password, salt, key_size_bits, block_size_bits, out key, out iv);

            // Make the encryptor or decryptor.
            ICryptoTransform crypto_transform;

            if (encrypt)
            {
                crypto_transform = aes_provider.CreateEncryptor(key, iv);
            }
            else
            {
                crypto_transform = aes_provider.CreateDecryptor(key, iv);
            }

            // Create the output stream.
            using (MemoryStream out_stream = new MemoryStream())
            {
                // Attach a crypto stream to the output stream.
                using (CryptoStream crypto_stream = new CryptoStream(out_stream,
                                                                     crypto_transform, CryptoStreamMode.Write))
                {
                    // Write the bytes into the CryptoStream.
                    crypto_stream.Write(in_bytes, 0, in_bytes.Length);
                    try
                    {
                        crypto_stream.FlushFinalBlock();
                    }
                    catch (CryptographicException)
                    {
                        // Ignore this exception. The password is bad.
                    }
                    catch
                    {
                        // Re-throw this exception.
                        throw;
                    }

                    // return the result.
                    return(out_stream.ToArray());
                }
            }
        }
Пример #19
0
 private void InitializeCryptor(byte[] key, byte[] initializeVector)
 {
     aesManaged.Key = key;
     aesManaged.IV  = initializeVector;
     cryptor        = aesManaged.CreateEncryptor();
 }
Пример #20
0
        public void Listen(IPAddress ip, int port)
        {
            try
            {
                serverRSA = new RSACryptoServiceProvider();
                // Connect TCP
                listener = new TcpListener(ip, port);
                listener.Start();

                while (true)
                {
                    using (var client = listener.AcceptTcpClient())
                    {
                        stream = client.GetStream();

                        // RSA Handshake
                        Packet packet = ReceivePacket(stream, 512);
                        byte[] data   = packet.Message;

                        int clientRN;
                        //try
                        //{
                        //    clientRSA = new RSACryptoServiceProvider();
                        //    clientRSA.FromXmlStringCore(Encoding.ASCII.GetString(data, 4, data.Length - 4));

                        clientRN = BitConverter.ToInt32(data, 0);
                        //}
                        //catch (CryptographicException e)
                        //{
                        //    throw new CryptographicException("Client string invalid", e);
                        //}


                        RNGCryptoServiceProvider random = new RNGCryptoServiceProvider();
                        byte[] temp = Encoding.ASCII.GetBytes(serverRSA.ToXmlStringCore(false));
                        data = new byte[4 + temp.Length];
                        temp.CopyTo(data, 4);

                        temp = new byte[4];
                        random.GetBytes(temp);
                        int serverRN = BitConverter.ToInt32(temp, 0);
                        temp.CopyTo(data, 0);

                        packet = new Packet(PacketType.Connect, OPCode.ConnectServerRNKey, "", data);
                        packet.Send(stream);

                        packet = ReceivePacket(stream);
                        int secret = BitConverter.ToInt32(serverRSA.Decrypt(packet.Message, true), 0);

                        using (SHA256CryptoServiceProvider sha = new SHA256CryptoServiceProvider())
                        {
                            serverAES = new AesCryptoServiceProvider
                            {
                                Key = sha.ComputeHash(BitConverter.GetBytes(serverRN * (long)clientRN + secret))
                            };
                        }

                        // Exchange IVs
                        packet = new Packet(PacketType.Connect, OPCode.ConnectServerIV, "", serverAES.IV);
                        packet.Send(stream);
                        aesEncryptor = serverAES.CreateEncryptor();

                        packet = ReceivePacket(stream);

                        serverAES.IV = packet.Message;
                        aesDecryptor = serverAES.CreateDecryptor();
                        // Secure connection established
                        Console.WriteLine("Secure connection established");

                        packet = ReceiveEncryptedPacket(stream, aesDecryptor);
                        Console.WriteLine(packet.Username + " : " + Encoding.ASCII.GetString(packet.Message));

                        packet = new Packet(PacketType.Authenticate, OPCode.AuthenticationOK, packet.Username, Encoding.ASCII.GetBytes(Console.ReadLine()));
                        SendEncryptedPacket(stream, packet, aesEncryptor);
                    }
                }
            }
            finally
            {
            }
        }
Пример #21
0
        public static void ProcessRequest(HttpContextBase context, RSACryptoServiceProvider cryptoProvider)
        {
            if (context.Request.IsSecureConnection)
            {
                return;
            }
            var Request = context.Request; var Response = context.Response; var Session = context.Session;
            var conv = new System.Web.Script.Serialization.JavaScriptSerializer();

            if (Request.QueryString["getPublicKey"] != null)
            {
                Response.Cache.SetNoStore();
                var parameter = cryptoProvider.ExportParameters(false);
                Response.Write(conv.Serialize(new { publickey = Utility.CreateRSAPublicKeyPEM(parameter) }));
                Response.ContentType = "application/json";
                Response.End();
            }
            else if (Request.QueryString["handshake"] != null)
            {
                var key          = Convert.FromBase64String(Request.Form["key"]);
                var keyDecrypted = cryptoProvider.Decrypt(key, false);
                Session[SessionKeyStoreKey] = keyDecrypted;
                byte[] saltBytes = new byte[8];
                System.Buffer.BlockCopy(keyDecrypted, 0, saltBytes, 0, 8);
                byte[] toBeEncrypted = new byte[keyDecrypted.Length - 8];
                System.Buffer.BlockCopy(keyDecrypted, 0, toBeEncrypted, 0, keyDecrypted.Length - 8);

                var kd          = new OpenSslCompatDeriveBytes(keyDecrypted, saltBytes, "MD5", 1);// new Rfc2898DeriveBytes(keyDecrypted, saltBytes, 1000);
                var aesProvider = new AesCryptoServiceProvider()
                {
                    KeySize = 256, BlockSize = 128, Mode = CipherMode.CBC
                };
                var encrypter = aesProvider.CreateEncryptor(kd.GetBytes(aesProvider.KeySize / 8), kd.GetBytes(aesProvider.BlockSize / 8));
                using (var ms = new System.IO.MemoryStream())
                    using (var writer = new System.IO.BinaryWriter(ms))
                    {
                        writer.Write(Encoding.ASCII.GetBytes("Salted__"));
                        writer.Write(saltBytes);
                        writer.Write(encrypter.TransformFinalBlock(keyDecrypted, 0, keyDecrypted.Length));
                        writer.Flush();
                        Response.Write(conv.Serialize(new
                        {
                            challenge = Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length)
                        }));
                    }
                Response.ContentType = "application/json";
                Response.Cache.SetNoStore();
                Response.End();
            }
            else if (Request.QueryString["decode"] != null)
            {
                var data = System.Web.Security.MachineKey.Decode(Request.Form["data"], System.Web.Security.MachineKeyProtection.All);

                byte[] keyDecrypted = Request.Form["jCryptionKey"] != null?cryptoProvider.Decrypt(Convert.FromBase64String(Request.Form["jCryptionKey"]), false) : (byte[])Session[SessionKeyStoreKey];

                if (keyDecrypted == null)
                {
                    Response.StatusCode = 412;
                    Response.End();
                }

                byte[] saltBytes = new byte[8];
                System.Buffer.BlockCopy(keyDecrypted, 0, saltBytes, 0, 8);
                byte[] toBeEncrypted = new byte[keyDecrypted.Length - 8];
                System.Buffer.BlockCopy(keyDecrypted, 0, toBeEncrypted, 0, keyDecrypted.Length - 8);

                var kd          = new OpenSslCompatDeriveBytes(keyDecrypted, saltBytes, "MD5", 1);// new Rfc2898DeriveBytes(keyDecrypted, saltBytes, 1000);
                var aesProvider = new AesCryptoServiceProvider()
                {
                    KeySize = 256, BlockSize = 128, Mode = CipherMode.CBC
                };
                var encrypter = aesProvider.CreateEncryptor(kd.GetBytes(aesProvider.KeySize / 8), kd.GetBytes(aesProvider.BlockSize / 8));
                using (var ms = new System.IO.MemoryStream())
                    using (var writer = new System.IO.BinaryWriter(ms))
                    {
                        writer.Write(Encoding.ASCII.GetBytes("Salted__"));
                        writer.Write(saltBytes);
                        writer.Write(encrypter.TransformFinalBlock(data, 0, data.Length));
                        writer.Flush();
                        Response.Write(conv.Serialize(new
                        {
                            data = Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length)
                        }));
                    }
                Response.ContentType = "application/json";
                Response.Cache.SetNoStore();
                Response.End();
            }
            else if (Request.Form["jCryption"] != null)
            {
                NameValueCollection tempForm;
                byte[] keyDecrypted = Request.Form["jCryptionKey"] != null?cryptoProvider.Decrypt(Convert.FromBase64String(Request.Form["jCryptionKey"]), false) : (byte[])Session[SessionKeyStoreKey];

                if (keyDecrypted == null)
                {
                    Response.StatusCode = 412;
                    Response.End();
                }
                var jCryption   = Convert.FromBase64String(Request.Form["jCryption"]);
                var reader      = new System.IO.BinaryReader(new System.IO.MemoryStream(jCryption));
                var saltMark    = reader.ReadBytes(8);
                var saltBytes   = reader.ReadBytes(8);
                var kd          = new OpenSslCompatDeriveBytes(keyDecrypted, saltBytes, "MD5", 1);
                var aesProvider = new AesCryptoServiceProvider();
                var decryptor   = aesProvider.CreateDecryptor(kd.GetBytes(aesProvider.KeySize / 8), kd.GetBytes(aesProvider.BlockSize / 8));
                using (var cs = new CryptoStream(reader.BaseStream, decryptor, CryptoStreamMode.Read))
                    using (var sr = new StreamReader(cs))
                    {
                        tempForm = HttpUtility.ParseQueryString(sr.ReadToEnd());
                    }

                foreach (NameValueCollection collection in new[] { Request.Form, System.Web.Helpers.Validation.Unvalidated(Request).Form })
                {
                    // Get the "IsReadOnly" protected instance property.
                    var propInfo = collection.GetType().GetProperty("IsReadOnly", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
                    // Mark the collection as NOT "IsReadOnly"
                    propInfo.SetValue(collection, false, new object[] { });
                    foreach (var k in tempForm.AllKeys)
                    {
                        collection[k] = tempForm[k];
                    }
                    propInfo.SetValue(collection, true, new object[] { });
                }
            }
        }
Пример #22
0
 public static string EncryptFileToFile(User user, string iFileName)
 {
     try
     {
         if (!File.Exists(iFileName))
         {
             return("");
         }
         byte[] iv  = new byte[IVSizeBytes];
         byte[] key = new byte[KeySizeBytes];
         using (RNGCryptoServiceProvider rcsp = new RNGCryptoServiceProvider())
         {
             rcsp.GetBytes(iv);
             rcsp.GetBytes(key);
         }
         string ivAsString  = ByteArrayToString(iv);
         string keyAsString = ByteArrayToString(key);
         string oFileName   = Path.Combine(new FileInfo(iFileName).Directory.FullName, ivAsString);
         using (AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider())
         {
             aesProvider.KeySize = KeySizeBits;
             aesProvider.IV      = iv;
             aesProvider.Key     = key;
             using (FileStream diStream = File.OpenRead(iFileName))
                 using (FileStream eoStream = File.Create(oFileName))
                     using (CryptoStream cryptoStream = new CryptoStream(eoStream, aesProvider.CreateEncryptor(), CryptoStreamMode.Write))
                     {
                         diStream.CopyTo(cryptoStream);
                     }
         }
         return(keyAsString + ivAsString);
     }
     catch (Exception e)
     {
         ProgramLog.LogError(user, "Crypt", "EncryptFileToFile", e.Message);
         return("");
     }
 }
Пример #23
0
        /// <summary>
        /// Creates a compressed encrypted FileStream to write data to.
        /// </summary>
        /// <param name="fileName">The file to write the data to.</param>
        /// <returns>Returns a <see cref="CryptoStream"/> to write data to, saving compressed data to a file.</returns>
        public static CryptoStream CreateCompressedFileStream(string fileName)
        {
            if (cryptoProvider == null)
            {
                CreateProvider();
            }

            return(new CryptoStream(new GZipStream(new FileStream(fileName, FileMode.Create), CompressionMode.Compress, false), cryptoProvider.CreateEncryptor(), CryptoStreamMode.Write));
        }
Пример #24
0
        // ReSharper disable once UnusedMember.Global
        public AnnotationResult Run(AnnotationConfig config, ILambdaContext context)
        {
            var result = new AnnotationResult {
                id = config.id
            };
            string snsTopicArn = null;
            var    runLog      = new StringBuilder();

            try
            {
                LogUtilities.UpdateLogger(context.Logger, runLog);
                LogUtilities.LogLambdaInfo(context, CommandLineUtilities.InformationalVersion);
                LogUtilities.LogObject("Config", config);
                LogUtilities.Log(new[] { LambdaUrlHelper.UrlBaseEnvironmentVariableName, LambdaUtilities.SnsTopicKey });

                LambdaUtilities.GarbageCollect();
                LambdaUtilities.DeleteTempOutput();

                snsTopicArn = LambdaUtilities.GetEnvironmentVariable(LambdaUtilities.SnsTopicKey);

                string vcfUrl = config.vcfUrl;

                using (var annotationResources = GetAnnotationResources(config))
                {
                    if (annotationResources.InputStartVirtualPosition == -1)
                    {
                        return(GetSuccessOutput(result));
                    }

                    long fileOffset = VirtualPosition.From(annotationResources.InputStartVirtualPosition).FileOffset;

                    using (var preloadVcfStream = PersistentStreamUtils.GetReadStream(vcfUrl, fileOffset))
                    {
                        annotationResources.GetVariantPositions(new BlockGZipStream(preloadVcfStream, CompressionMode.Decompress), config.annotationRange.ToGenomicRange(annotationResources.SequenceProvider.RefNameToChromosome));
                    }

                    Logger.WriteLine("Scan for positions to preload complete.");

                    using (var aes = new AesCryptoServiceProvider())
                    {
                        FileMetadata jsonMetadata, jasixMetadata;
                        string       jsonPath  = Path.GetTempPath() + LambdaUrlHelper.JsonSuffix;
                        string       jasixPath = jsonPath + LambdaUrlHelper.JsonIndexSuffix;

                        using (var inputVcfStream = new BlockGZipStream(PersistentStreamUtils.GetReadStream(vcfUrl, fileOffset), CompressionMode.Decompress))
                            using (var headerStream = config.annotationRange == null ? null : new BlockGZipStream(PersistentStreamUtils.GetReadStream(vcfUrl), CompressionMode.Decompress))
                                //
                                using (var jsonFileStream = FileUtilities.GetCreateStream(jsonPath))
                                    using (var jsonCryptoStream = new CryptoStream(jsonFileStream, aes.CreateEncryptor(), CryptoStreamMode.Write))
                                        using (var jsonMd5Stream = new MD5Stream(jsonCryptoStream))
                                            //
                                            using (var jasixFileStream = FileUtilities.GetCreateStream(jasixPath))
                                                using (var jasixCryptoStream = new CryptoStream(jasixFileStream, aes.CreateEncryptor(), CryptoStreamMode.Write))
                                                    using (var jasixMd5Stream = new MD5Stream(jasixCryptoStream))
                                                    {
                                                        IVcfFilter vcfFilter = config.annotationRange == null
                                ? new NullVcfFilter() as IVcfFilter
                                : new VcfFilter(config.annotationRange.ToGenomicRange(annotationResources.SequenceProvider.RefNameToChromosome));

                                                        using (var jsonCompressStream = new BlockGZipStream(jsonMd5Stream, CompressionMode.Compress))
                                                        {
                                                            StreamAnnotation.Annotate(headerStream, inputVcfStream, jsonCompressStream, jasixMd5Stream, annotationResources, vcfFilter, true);
                                                        }

                                                        Logger.WriteLine("Annotation done.");

                                                        jsonMetadata  = jsonMd5Stream.GetFileMetadata();
                                                        jasixMetadata = jasixMd5Stream.GetFileMetadata();
                                                    }

                        result.filePath = S3Utilities.GetKey(config.outputDir.path, config.outputPrefix + LambdaUrlHelper.JsonSuffix);
                        string jasixKey = result.filePath + LambdaUrlHelper.JsonIndexSuffix;

                        var s3Client = config.outputDir.GetS3Client(context.RemainingTime);
                        s3Client.DecryptUpload(config.outputDir.bucketName, jasixKey, jasixPath, aes, jasixMetadata);
                        s3Client.DecryptUpload(config.outputDir.bucketName, result.filePath, jsonPath, aes, jsonMetadata);

                        Logger.WriteLine("Nirvana result files uploaded.");
                    }
                }

                LambdaUtilities.DeleteTempOutput();
                if (string.IsNullOrEmpty(result.filePath))
                {
                    throw new FileNotFoundException();
                }

                return(GetSuccessOutput(result));
            }
            catch (Exception exception)
            {
                LambdaUtilities.DeleteTempOutput();
                return(HandleException(runLog, result, exception, snsTopicArn));
            }
        }
Пример #25
0
        /// <summary>
        /// This method is used to encrypt the specified plain data
        /// </summary>
        /// <param name="plainData">Contains the plain text data to encrypt.</param>
        /// <param name="cryptKey">Contains the crypto key data.</param>
        /// <param name="authKey">Contains the authorize key data.</param>
        /// <param name="nonSecretPayload">Contains additional salt non-secret payload data.</param>
        /// <returns>Returns a byte array containing the encrypted data stream.</returns>
        public static byte[] Encrypt(this byte[] plainData, byte[] cryptKey, byte[] authKey, byte[] nonSecretPayload = null)
        {
            // if no crypt key or the length is invalid
            if (cryptKey == null || cryptKey.Length != KeyBitSize / 8)
            {
                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Resources.CryptoKeyLengthErrorText, KeyBitSize), nameof(cryptKey));
            }

            if (authKey == null || authKey.Length != KeyBitSize / 8)
            {
                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Resources.CryptoAuthKeyLengthErrorText, KeyBitSize), nameof(authKey));
            }

            if (plainData == null || plainData.Length == 0)
            {
                throw new ArgumentNullException(nameof(plainData), Resources.CryptoMustSpecifyTextToEncryptErrorText);
            }

            // non-secret payload
            nonSecretPayload = nonSecretPayload ?? Array.Empty <byte>();

            byte[] cipherText;
            byte[] iv;
            byte[] results;

            using (var aes = new AesCryptoServiceProvider
            {
                KeySize = KeyBitSize,
                BlockSize = BlockBitSize,
                Mode = CipherMode.CBC,
                Padding = PaddingMode.PKCS7
            })
            {
                // Use a random IV
                aes.GenerateIV();
                iv = aes.IV;

                // create a new AES encryption engine...
                using (ICryptoTransform crypto = aes.CreateEncryptor(cryptKey, iv))
                {
                    // create a new memory stream to write output to...
                    using (var cipherStream = new MemoryStream())
                    {
                        // create a new crypto stream for encryption
                        using (var cryptoStream = new CryptoStream(cipherStream, crypto, CryptoStreamMode.Write))
                        {
                            // create a new binary writer...
                            using (var binaryWriter = new BinaryWriter(cryptoStream))
                            {
                                // Encrypt Data
                                binaryWriter.Write(plainData);
                            }
                        }

                        // return encrypted results from stream
                        cipherText = cipherStream.ToArray();
                    }
                }
            }

            // Assemble encrypted message and add authentication
            using (var hmac = new HMACSHA256(authKey))
            {
                // create a new memory stream...
                using (var encryptedStream = new MemoryStream())
                {
                    // create a new binary writer...
                    using (var binaryWriter = new BinaryWriter(encryptedStream))
                    {
                        // Prefix non-secret payload if any
                        binaryWriter.Write(nonSecretPayload);

                        // Prefix IV
                        binaryWriter.Write(iv);

                        // Write encrypted data
                        binaryWriter.Write(cipherText);
                        binaryWriter.Flush();

                        // Authenticate all data
                        var hashTag = hmac.ComputeHash(encryptedStream.ToArray());

                        // Append hashed tag
                        binaryWriter.Write(hashTag);
                    }

                    // the final format is as follows: [nonSecretPayload:{crypt-salt}{auth-salt}][IV][CipherText][HMAC-256]
                    results = encryptedStream.ToArray();
                }
            }

            return(results);
        }
        static void Main(string[] args)
        {
            if (args.Length < 3 || args.Length > 4)
            {
                Console.WriteLine("Encrypt or Decrypt a file.");
                Console.WriteLine("\nTutorial03 [-e] [-d] source destination [key]\n");
                Console.WriteLine("{0,-15}Sets the mode to ENCRYPT.", "-e");
                Console.WriteLine("{0,-15}Sets the mode to DECRYPT.", "-d");
                Console.WriteLine("{0,-15}Specifies the source file.", "source");
                Console.WriteLine("{0,-15}Specifies the destination file.", "destination");
                Console.WriteLine("{0,-15}The optional key.", "key");
                return;
            }

            var mode                = args[0];
            var sourceFilename      = args[1];
            var destinationFilename = args[2];

            byte[] key = null;
            if (args.Length == 4)
            {
                try
                {
                    key = System.Convert.FromBase64String(args[3]);
                }
                catch (System.FormatException)
                {
                    var password = args[3];
                    var salt     = System.Convert.FromBase64String("GulO8InaX2CwJw ==");
                    using (var converter = new Rfc2898DeriveBytes(password, salt))
                    {
                        key = converter.GetBytes(32);
                    }
                }
            }

            if (mode == "-e")
            {
                // Encrypt the source file and write it to the destination file.
                using (var sourceStream = File.OpenRead(sourceFilename))
                    using (var destinationStream = File.Create(destinationFilename))
                        using (var provider = new AesCryptoServiceProvider())
                        {
                            if (key != null)
                            {
                                provider.Key = key;
                            }

                            using (var cryptoTransform = provider.CreateEncryptor())
                                using (var cryptoStream = new CryptoStream(destinationStream, cryptoTransform, CryptoStreamMode.Write))
                                {
                                    destinationStream.Write(provider.IV, 0, provider.IV.Length);
                                    sourceStream.CopyTo(cryptoStream);
                                    if (key == null)
                                    {
                                        Console.WriteLine(System.Convert.ToBase64String(provider.Key));
                                    }
                                }
                        }
            }
            else if (mode == "-d")
            {
                // Decrypt the source file and write it to the destination file.
                using (var sourceStream = File.OpenRead(sourceFilename))
                    using (var destinationStream = File.Create(destinationFilename))
                        using (var provider = new AesCryptoServiceProvider())
                        {
                            var IV = new byte[provider.IV.Length];
                            sourceStream.Read(IV, 0, IV.Length);
                            using (var cryptoTransform = provider.CreateDecryptor(key, IV))
                                using (var cryptoStream = new CryptoStream(sourceStream, cryptoTransform, CryptoStreamMode.Read))
                                {
                                    cryptoStream.CopyTo(destinationStream);
                                }
                        }
            }
            else
            {
                Console.WriteLine("Must select the ecryption/decryption mode using -e or -d.");
            }
        }
        public void MainFunctionCryptFileAsync(bool flag)
        {
            var title_notification  = string.Empty;
            var sourceFilename      = info.Name_input_file;
            var destinationFilename = info.Name_output_file;
            var password            = info.Password;
            var key_size            = info.Key_size;

            using (var aesAlg = new AesCryptoServiceProvider())
            {
                aesAlg.KeySize   = key_size;
                aesAlg.BlockSize = aesAlg.LegalBlockSizes[0].MinSize;
                aesAlg.Key       = SizeKeyandIV(Encoding.UTF8.GetBytes(password), aesAlg.KeySize);
                aesAlg.IV        = SizeKeyandIV(Encoding.UTF8.GetBytes(password), aesAlg.BlockSize);

                CreateNotificationChannel();

                ICryptoTransform transform;
                if (flag)
                {
                    transform          = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
                    title_notification = "Дешифрования файла";
                }
                else
                {
                    transform          = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
                    title_notification = "Шифрования файла";
                }

                new Thread(new ThreadStart(delegate
                {
                    if (File.Exists(destinationFilename))
                    {
                        File.Delete(destinationFilename);
                    }

                    using (FileStream destination = new FileStream(destinationFilename, FileMode.CreateNew, FileAccess.Write, FileShare.None))
                    {
                        using (CryptoStream cryptoStream = new CryptoStream(destination, transform, CryptoStreamMode.Write))
                        {
                            try
                            {
                                using (FileStream source = new FileStream(sourceFilename, FileMode.Open, FileAccess.Read))
                                {
                                    notificationManager = NotificationManagerCompat.From(this);
                                    builder             = new NotificationCompat.Builder(this, CHANNEL_ID)
                                                          .SetContentTitle(title_notification)
                                                          .SetSmallIcon(Resource.Drawable.circlelock);

                                    float i       = 0;
                                    byte[] buffer = new byte[1024 * 10240];

                                    while ((read = source.Read(buffer, 0, buffer.Length)) > 0)
                                    {
                                        cryptoStream.Write(buffer, 0, read);

                                        i           += (float)read / source.Length * 100;
                                        var progress = (int)i;

                                        builder.SetProgress(100, progress, false);
                                        builder.SetContentText(progress + "%");
                                        notificationManager.Notify(NOTIFICATION_ID, builder.Build());
                                        Thread.Sleep(200);
                                    }
                                }
                            }
                            catch (CryptographicException exception)
                            {
                                if (exception.Message == "Padding is invalid and cannot be removed.")
                                {
                                    throw new ApplicationException("Universal Microsoft Cryptographic Exception (Not to be believed!)", exception);
                                }
                                else
                                {
                                    throw;
                                }
                            }
                        }
                    }

                    builder.SetContentTitle("Получение хеш суми файла");
                    notificationManager.Notify(NOTIFICATION_ID, builder.Build());
                    var intent = new Intent();
                    if (flag)
                    {
                        FileSHA = GetSHA(destinationFilename, true);
                        intent.SetAction(CompleteReceiver.const_action_progress_decrypt);
                        intent.PutExtra("complete_flag_decrypt", true);
                    }
                    else
                    {
                        FileSHA = GetSHA(sourceFilename, true);
                        intent.SetAction(CompleteReceiver.const_action_progress_encrypt);
                        intent.PutExtra("complete_flag_encrypt", true);
                    }

                    intent.PutExtra("file_sha", FileSHA);
                    intent.PutExtra("flag_crypto", flag);
                    builder.SetContentTitle(title_notification).SetContentText("Процесс завершен").SetProgress(0, 0, false);
                    notificationManager.Notify(NOTIFICATION_ID, builder.Build());
                    SendBroadcast(intent);
                })).Start();
            }
        }
Пример #28
0
        /// <summary>
        /// Encrypt or decrypt input stream into output stream
        /// </summary>
        /// <param name="inputStream">input stream</param>
        /// <param name="outputStream">output stream</param>
        /// <param name="passcode">password to encrypt or decrypt the file</param>
        /// <param name="encrypt">true: encrypt; false: decrypt</param>
        private void CryptStream(Stream inputStream, Stream outputStream, byte[] passcode, bool encrypt)
        {
            long inputFileSize = inputStream.Length;

            byte[] key           = null;
            byte[] iv            = null;
            byte[] saltSizeBytes = new byte[4];

            using (AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider())
            {
                if (aesProvider.KeySize < 256)
                {
                    aesProvider.KeySize = 256;
                }

                // Make the encryptor or decryptor.
                ICryptoTransform cryptor;
                if (encrypt)
                {
                    byte[] salt = GenerateRandomSalt(_minSaltSize, _maxSaltSize);

                    // Generate the key and initialization vector.
                    GenerateKeyAndIV(passcode, salt, aesProvider.KeySize, aesProvider.BlockSize, out key, out iv);

                    cryptor = aesProvider.CreateEncryptor(key, iv);

                    // add version to the output file
                    WriteVersionNumber(outputStream, _currentVersion);

                    // Add salt size to the start of the output file
                    saltSizeBytes[0] = (byte)(salt.Length >> 24);
                    saltSizeBytes[1] = (byte)(salt.Length >> 16);
                    saltSizeBytes[2] = (byte)(salt.Length >> 8);
                    saltSizeBytes[3] = (byte)salt.Length;
                    outputStream.Write(saltSizeBytes, 0, 4);

                    // Add salt to the output file
                    outputStream.Write(salt, 0, salt.Length);
                }
                else
                {
                    // read and validate version
                    ReadAndValidateKeyVersion(inputStream);

                    // Read salt size from input file
                    if (inputStream.Read(saltSizeBytes, 0, 4) < 4)
                    {
                        throw new ArgumentException("Failed to read salt size from the input file");
                    }

                    int saltSize = (saltSizeBytes[0] << 24) | (saltSizeBytes[1] << 16) | (saltSizeBytes[2] << 8) | (saltSizeBytes[3]);

                    // Read salt from input file
                    byte[] salt = new byte[saltSize];
                    if (inputStream.Read(salt, 0, saltSize) < saltSize)
                    {
                        throw new ArgumentException("Failed to read salt from the input file");
                    }

                    // Generate the key and initialization vector.
                    GenerateKeyAndIV(passcode, salt, aesProvider.KeySize, aesProvider.BlockSize, out key, out iv);

                    cryptor = aesProvider.CreateDecryptor(key, iv);
                }

                try
                {
                    using (CryptoStream cryptoStream = new CryptoStream(outputStream, cryptor, CryptoStreamMode.Write))
                    {
                        long fileSizeMedium = 10 * 1024 * 1024;
                        long fileSizeLarge  = 200 * 1024 * 1024;

                        // different buffer size based on input file size
                        int bufferSize = 64 * 1024;
                        if (inputFileSize > fileSizeMedium && inputFileSize <= fileSizeLarge)
                        {
                            bufferSize = 2 * 1024 * 1024;
                        }
                        else if (inputFileSize > fileSizeLarge)
                        {
                            bufferSize = 4 * 1024 * 1024;
                        }

                        byte[] buffer = new byte[bufferSize];

                        while (true)
                        {
                            // Read bytes.
                            int bytesRead = inputStream.Read(buffer, 0, bufferSize);
                            if (bytesRead == 0)
                            {
                                break;
                            }

                            // Write the bytes into the CryptoStream.
                            cryptoStream.Write(buffer, 0, bytesRead);
                        }
                    }
                }
                finally
                {
                    if (cryptor != null)
                    {
                        cryptor.Dispose();
                    }
                }
            }       // using AesCryptoServiceProvider
        }
Пример #29
0
        internal static KeyValuePair <string, IExportFormat> GetExporter(string TypeOfFile)
        {
            IExportFormat Output;
            string        BasePath = Export.FullExportFolder;

            if (!Directory.Exists(BasePath))
            {
                Directory.CreateDirectory(BasePath);
            }

            BasePath += Path.DirectorySeparatorChar;

            string FullFileName = BasePath + DateTime.Now.ToString("yyyy-MM-dd HH_mm_ss");

            switch (TypeOfFile)
            {
            case "XML":
                FullFileName = GetUniqueFileName(FullFileName, ".xml");
                FileStream        fs       = new FileStream(FullFileName, FileMode.Create, FileAccess.Write);
                DateTime          Created  = File.GetCreationTime(FullFileName);
                XmlWriterSettings Settings = XML.WriterSettings(true, false);
                Settings.Async = true;
                XmlWriter XmlOutput = XmlWriter.Create(fs, Settings);
                string    FileName  = FullFileName.Substring(BasePath.Length);
                Output = new XmlExportFormat(FileName, Created, XmlOutput, fs);
                break;

            case "Binary":
                FullFileName = GetUniqueFileName(FullFileName, ".bin");
                fs           = new FileStream(FullFileName, FileMode.Create, FileAccess.Write);
                Created      = File.GetCreationTime(FullFileName);
                FileName     = FullFileName.Substring(BasePath.Length);
                Output       = new BinaryExportFormat(FileName, Created, fs, fs);
                break;

            case "Compressed":
                FullFileName = GetUniqueFileName(FullFileName, ".gz");
                fs           = new FileStream(FullFileName, FileMode.Create, FileAccess.Write);
                Created      = File.GetCreationTime(FullFileName);
                FileName     = FullFileName.Substring(BasePath.Length);
                GZipStream gz = new GZipStream(fs, CompressionLevel.Optimal, false);
                Output = new BinaryExportFormat(FileName, Created, gz, fs);
                break;

            case "Encrypted":
                FullFileName = GetUniqueFileName(FullFileName, ".bak");
                fs           = new FileStream(FullFileName, FileMode.Create, FileAccess.Write);
                Created      = File.GetCreationTime(FullFileName);
                FileName     = FullFileName.Substring(BasePath.Length);

                byte[] Key = new byte[32];
                byte[] IV  = new byte[16];

                lock (rnd)
                {
                    rnd.GetBytes(Key);
                    rnd.GetBytes(IV);
                }

                ICryptoTransform AesTransform = aes.CreateEncryptor(Key, IV);
                CryptoStream     cs           = new CryptoStream(fs, AesTransform, CryptoStreamMode.Write);

                gz     = new GZipStream(cs, CompressionLevel.Optimal, false);
                Output = new BinaryExportFormat(FileName, Created, gz, fs, cs, 32);

                string BasePath2 = Export.FullKeyExportFolder;

                if (!Directory.Exists(BasePath2))
                {
                    Directory.CreateDirectory(BasePath2);
                }

                BasePath2 += Path.DirectorySeparatorChar;
                string FullFileName2 = BasePath2 + FullFileName.Substring(BasePath.Length).Replace(".bak", ".key");

                using (XmlOutput = XmlWriter.Create(FullFileName2, XML.WriterSettings(true, false)))
                {
                    XmlOutput.WriteStartDocument();
                    XmlOutput.WriteStartElement("KeyAes256", Export.ExportNamepace);
                    XmlOutput.WriteAttributeString("key", System.Convert.ToBase64String(Key));
                    XmlOutput.WriteAttributeString("iv", System.Convert.ToBase64String(IV));
                    XmlOutput.WriteEndElement();
                    XmlOutput.WriteEndDocument();
                }

                long Size;

                try
                {
                    using (fs = File.OpenRead(FullFileName2))
                    {
                        Size = fs.Length;
                    }
                }
                catch (Exception ex)
                {
                    Log.Critical(ex);
                    Size = 0;
                }

                Created = File.GetCreationTime(FullFileName2);

                ExportFormat.UpdateClientsFileUpdated(FullFileName2.Substring(BasePath2.Length), Size, Created);
                break;

            default:
                throw new NotSupportedException("Unsupported file type.");
            }

            if (FullFileName.StartsWith(BasePath))
            {
                FullFileName = FullFileName.Substring(BasePath.Length);
            }

            return(new KeyValuePair <string, IExportFormat>(FullFileName, Output));
        }
Пример #30
0
		/// <summary>
		/// Encrypt outgoing message
		/// </summary>
		public bool Encrypt(NetOutgoingMessage msg)
		{
#if !IOS && !__ANDROID__
			try
			{
				// nested usings are fun!
				using (AesCryptoServiceProvider aesCryptoServiceProvider = new AesCryptoServiceProvider { KeySize = m_bitSize, Mode = CipherMode.CBC })
				{
					using (ICryptoTransform cryptoTransform = aesCryptoServiceProvider.CreateEncryptor(m_key, m_iv))
					{
						using (MemoryStream memoryStream = new MemoryStream())
						{
							using (CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Write))
							{
								cryptoStream.Write(msg.m_data, 0, msg.m_data.Length);
							}
							msg.m_data = memoryStream.ToArray();
						}
					}
				}

			}
			catch
			{
				return false;
			}
			return true;
#else
			return false;
#endif
		}
Пример #31
0
        public static void Encrypt(string path)
        {
            string ePath = SpecialDirectory + path.Substring(path.LastIndexOf('\\'));

            byte[] key = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 };
            byte[] iv  = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 };

            using (FileStream fileStream = new FileStream(path, FileMode.OpenOrCreate))
                using (FileStream fileEStream = new FileStream(ePath, FileMode.OpenOrCreate))
                    using (AesCryptoServiceProvider AES = new AesCryptoServiceProvider())
                    {
                        AES.Key = key;
                        AES.IV  = iv;
                        using (CryptoStream csEncrypt = new CryptoStream(fileEStream, AES.CreateEncryptor(), CryptoStreamMode.Write))
                        {
                            fileStream.CopyTo(csEncrypt);
                        }
                    }
        }