private static void WriteFileOnFileSystem(Stream inputStream, string fileName, string guid) { byte[] encryptionKey = FileEncryptor.GenerateEncryptionKey(guid.ToLower()); byte[] buffer = new byte[encryptionKey.Length]; using (var outputStream = new FileStream(fileName, FileMode.Create)) { var transferLength = inputStream.Length; var byteNo = 0L; while (transferLength > 0) { //Thread.Sleep(50); // For Debug inputStream.Read(buffer, 0, buffer.Length); var sendLength = (int)Math.Min(transferLength, buffer.Length); // encrypt for (var i = 0; i < sendLength; i++) { buffer[i] = (byte)(buffer[i] ^ encryptionKey[byteNo % encryptionKey.Length]); byteNo++; } outputStream.Write(buffer, 0, sendLength); transferLength -= sendLength; } } }
public void TestGetKey() { IBuffer iBuff = FileEncryptor.GetEncryptionKey("MPZtsFKrUjxT7CJBQdMHeL55", "d+WTC5HTMiI="); string buff = Convert.ToBase64String(iBuff.ToArray()); Assert.AreEqual("zxtE+siw7hDl7bhbpSC1WjWmlQU9YwyZVTLj2JxBGro=", buff); }
// Archiwizuje wskazany po ścieżce plik public void ArchiveFile(string path) { if (!IsOpen) { throw new Exception("Archiwum nieotwarte"); } if (!ArchiveKey.IsDerived) { throw new Exception("Klucz niewyprowadzony"); } if (!File.Exists(path)) { throw new Exception("Plik pod wskazaną lokalizacją nie istnieje"); } FileData file = FileData.Create(path); string plaintextName = file.NameStr; if (!FileNameUnique(plaintextName)) { throw new FileNamingException(plaintextName); } if (IsCompressed) { FileCompressor.CompressFile(file); } FileEncryptor.EncryptFile(file, ArchiveKey); SQLiteCommand command = new SQLiteCommand(Connection); command.CommandText = "INSERT INTO FileData(name_l, name, content_l, content, iv) VALUES" + "(" + "'" + Convert.ToString(file.NameLength) + "', " + "@Name, " + "'" + Convert.ToString(file.ContentLength) + "', " + "@Content, " + "@IV" + ")"; command.Parameters.Add(new SQLiteParameter("Name", file.Name)); command.Parameters.Add(new SQLiteParameter("Content", file.Content)); command.Parameters.Add(new SQLiteParameter("IV", file.IV)); command.ExecuteNonQuery(); command.CommandText = "SELECT last_insert_rowid();"; long lastRowId = (long)command.ExecuteScalar(); int fileId = (int)lastRowId; // Przechowanie pary id_pliku-nazwa_pliku IdFileNamePairs.Add(fileId, plaintextName); }
private void DecryptPassword() { string file = txtFilePath.Text; var password = txtBxPassword.Password; var salt = MasterConfigManager.getInstance().getPasswordSalt(); FileEncryptor.Decrypt(file, password, salt); listboxuseraccounts.ItemsSource = UserAccountsManager.getInstance().getUserAccounts(); }
// Wypakowuje z archiwum wskazany po identyfikatorze plik do wskazanego po ścieżce katalogu public void Extract(int id, string destPath) { if (!IsOpen) { throw new Exception("Archiwum nieotwarte"); } if (!ArchiveKey.IsDerived) { throw new Exception("Klucz niewyprowadzony"); } SQLiteCommand command = new SQLiteCommand(Connection); command.CommandText = "SELECT name_l, length(name), name, content_l, length(content), content, iv FROM FileData WHERE id='" + Convert.ToString(id) + "';"; SQLiteDataReader reader = command.ExecuteReader(); FileData file = null; while (reader.Read()) { int nameLength = reader.GetInt32(0); int nameBlobLength = reader.GetInt32(1); byte[] fileName = new byte[nameBlobLength]; reader.GetBytes(2, 0, fileName, 0, nameBlobLength); int contentLength = reader.GetInt32(3); int contentBlobLength = reader.GetInt32(4); byte[] content = new byte[contentBlobLength]; reader.GetBytes(5, 0, content, 0, contentBlobLength); byte[] iv = new byte[EncryptionKey.BlockLength]; reader.GetBytes(6, 0, iv, 0, EncryptionKey.BlockLength); file = FileData.Create(nameLength, fileName, contentLength, content, iv); } if (file != null) { FileEncryptor.DecryptFile(file, ArchiveKey); if (IsCompressed) { FileCompressor.DecompressFile(file); } File.WriteAllBytes(Path.Combine(destPath, file.NameStr), file.Content); } else { throw new Exception(string.Format("Nie udało się odczytać danych pliku o id={0}", id)); } }
private static bool Encrypt() { #if DEBUG { return(true); } #else return(FileEncryptor.EncryptFile(GetSettingsFileName, _key)); #endif }
public void TestEncrypt() { string response = FileEncryptor.EncryptData( "MPZtsFKrUjxT7CJBQdMHeL55", "d+WTC5HTMiI=", "LMbOhhdhBAz81yYlE8eAfQ==", "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec fringilla eu lacus sed ullamcorper." ); Assert.AreEqual("czIgppp/gijz+WtaHGTeh4ryjd1dOS7Pn6pJQa3VXZRnDL4DCdD68PBjLBjgZ7Li/LOhi20GwjFi6Y1YI5O6Zeaw6VzpH2BZAUtyBcsjZscIn93o99kPKG2ULnQJ2mRWWylAk7KsRUJAeDEqPG18wA==", response); }
public void Initialise() { _encryptionProvider = Aes.Create(); var ivMock = new Mock <IIV>(); ivMock.Setup(m => m.GenerateIV(It.IsAny <int>())).Returns(TestConstants.IvData); _iv = ivMock.Object; _key = Mock.Of <IKey>(); _fileEncryptor = new FileEncryptor(new Key("password"), _iv, _encryptionProvider); }
public bool validatePaswword(string password) { FileEncryptor.CreateHash(password, passwordSalt); string hash = Convert.ToBase64String(FileEncryptor.DES.Key); if (passwordHash == hash) { return(true); } else { return(false); } }
static async Task MainAsync(string[] args, CancellationToken token) { Console.WriteLine($"altCrypt [Alpha] ({DateTime.Now.Year})"); _args = new ArgsParser(args); string instructions = GetInstructions(); if (_args.IsError) { Console.WriteLine(instructions); return; } Console.WriteLine($"Parameters:\r\n{_args.ToString()}"); Console.WriteLine($"Started: {DateTime.Now}"); _encryptor = new FileEncryptor(new Key(_args.Key), new RandomIV(), _args.Algorithm); switch (_args.Command) { case Command.Encrypt: if (_args.Switches.HasFlag(Switch.Directory)) { await EncryptDirectoryAsync(); } else { await EncryptFileAsync(); } break; case Command.Decrypt: if (_args.Switches.HasFlag(Switch.Directory)) { await DecryptDirectoryAsync(); } else { await DecryptFileAsync(); } break; } Console.WriteLine($"Finished: {DateTime.Now}"); if (System.Diagnostics.Debugger.IsAttached) { Console.ReadLine(); } }
public void TestCreateSalt() { int length = 10; try { var result = FileEncryptor.CreateSalt(length); var bytes = Convert.FromBase64String(result); } catch { Assert.Fail("Salt value does not contain valid base64 characters"); } Assert.Pass("Salt value is valid, contains only base64 characters"); }
public void TestCreateHash() { string password = "******"; int length = 10; try { var salt = FileEncryptor.CreateSalt(length); var hash = FileEncryptor.CreateHash(password, salt); var hashBytes = Convert.FromBase64String(hash); } catch { Assert.Fail("Hash value does not contain valid base64 characters"); } Assert.Pass("Hash value is valid, contains only base64 characters"); }
public void TestCreateDES() { string key = "sfasdfasdfasdfasdf"; int length = 10; try { var salt = FileEncryptor.CreateSalt(length); var saltBytes = Convert.FromBase64String(salt); RijndaelManaged rijndaelManaged = FileEncryptor.CreateDES(key, saltBytes); Assert.NotNull(rijndaelManaged); } catch { Assert.Fail("Hash value does not contain valid base64 characters"); } }
public void LoadGameFromDisk() { base.Scenario.EnableLoadAndSave = false; if (!File.Exists("GameData/Save/" + this.LoadFileName)) { base.Scenario.EnableLoadAndSave = true; } else { this.Plugins.DateRunnerPlugin.Reset(); this.Plugins.GameRecordPlugin.Clear(); this.Plugins.GameRecordPlugin.RemoveDisableRects(); this.Plugins.AirViewPlugin.RemoveDisableRects(); string realPath = this.LoadFileName.Substring(0, this.LoadFileName.Length - 4) + ".mdb"; if (this.LoadFileName.EndsWith(".zhs")) { FileEncryptor.DecryptFile("GameData/Save/" + this.LoadFileName, "GameData/Save/" + realPath, GlobalVariables.cryptKey); } OleDbConnectionStringBuilder builder = new OleDbConnectionStringBuilder { DataSource = "GameData/Save/" + realPath, Provider = "Microsoft.Jet.OLEDB.4.0" }; base.Scenario.LoadSaveFileFromDatabase(builder.ConnectionString, this.LoadFileName); if (GlobalVariables.EncryptSave) { File.Delete("GameData/Save/" + realPath); } //this.mainMapLayer.jiazaibeijingtupian(); this.chushihuajianzhubiaotiheqizi(); this.gengxinyoucelan(); base.Scenario.EnableLoadAndSave = true; } }
public void LoadGameFromDisk(String fileName) { base.Scenario.EnableLoadAndSave = false; if (!File.Exists(fileName)) { base.Scenario.EnableLoadAndSave = true; } else { this.Plugins.DateRunnerPlugin.Reset(); this.Plugins.GameRecordPlugin.Clear(); this.Plugins.GameRecordPlugin.RemoveDisableRects(); this.Plugins.AirViewPlugin.RemoveDisableRects(); string realPath = fileName.Substring(0, fileName.Length - 4) + ".mdb"; if (this.LoadFileName.EndsWith(".zhs")) { FileEncryptor.DecryptFile(fileName, realPath, GlobalVariables.cryptKey); } OleDbConnectionStringBuilder builder = new OleDbConnectionStringBuilder { DataSource = realPath, Provider = "Microsoft.Jet.OLEDB.4.0" }; base.Scenario.LoadSaveFileFromDatabase(builder.ConnectionString, fileName); if (GlobalVariables.EncryptSave) { File.Delete(realPath); } this.ReloadScreenData(); base.Scenario.EnableLoadAndSave = true; } }
private void btnClickEncrypt(object sender, RoutedEventArgs e) { if (String.IsNullOrEmpty(MasterConfigManager.getInstance().getPasswordHash())) { System.Windows.MessageBox.Show("Master Password has not been set, please set master password first."); SetMasterPasswordWindow smpw = new SetMasterPasswordWindow(); smpw.ShowDialog(); return; } if (MasterConfigManager.getInstance().getIsFileEncrypted() == true) { System.Windows.MessageBox.Show("File is already encrypted."); return; } if (string.IsNullOrEmpty(txtFilePath.Text)) { System.Windows.MessageBox.Show("Please select a user accounts file first."); return; } string file = txtFilePath.Text; if (!File.Exists(file)) { System.Windows.MessageBox.Show("Specified user accounts file does not exist!"); return; } var password = txtBxPassword.Password; bool correctPassword = MasterConfigManager.getInstance().validatePaswword(password); if (!correctPassword) { System.Windows.MessageBox.Show("Password is not correct!"); return; } FileEncryptor.Encrypt(file, password, MasterConfigManager.getInstance().getPasswordSalt()); listboxuseraccounts.ItemsSource = null; lblStatus.Visibility = Visibility.Visible; }
public void TestSalt() { IBuffer iv = CryptographicBuffer.DecodeFromBase64String(FileEncryptor.GetRandomSalt()); Assert.AreEqual(8U, iv.Length); }
public void TestIv() { IBuffer iv = CryptographicBuffer.DecodeFromBase64String(FileEncryptor.GetInitializationVector()); Assert.AreEqual(16U, iv.Length); }
public void setPassword(string newPassword) { passwordSalt = FileEncryptor.CreateSalt(10); passwordHash = FileEncryptor.CreateHash(newPassword, passwordSalt); amcw.WriteToConfigFile(passwordHash, passwordSalt); }