public static string CompressionLevelToString(Ionic.Zlib.CompressionLevel value) { switch (value) { case Ionic.Zlib.CompressionLevel.BestCompression: return("BestCompression"); case Ionic.Zlib.CompressionLevel.BestSpeed: return("BestSpeed"); case Ionic.Zlib.CompressionLevel.Default: return("Default"); case Ionic.Zlib.CompressionLevel.Level2: return("Level2"); case Ionic.Zlib.CompressionLevel.Level3: return("Level3"); case Ionic.Zlib.CompressionLevel.Level4: return("Level4"); case Ionic.Zlib.CompressionLevel.Level5: return("Level5"); case Ionic.Zlib.CompressionLevel.Level7: return("Level7"); case Ionic.Zlib.CompressionLevel.Level8: return("Level8"); case Ionic.Zlib.CompressionLevel.None: return("None"); default: return("Default"); } }
/// <summary> /// Create zip from directory /// </summary> /// <param name="dirToZip"> /// The name of the directory to create the zip from /// </param> /// <param name="zipName"> /// The name of the archive to you want to add your files to /// </param> /// <param name="compression"> /// Specifies what type of compression to use - defaults to Optimal /// </param> /// <param name="includeRoot"> /// /// </param> public static void SimpleZip(string dirToZip, string zipName, Ionic.Zlib.CompressionLevel compression = Ionic.Zlib.CompressionLevel.BestSpeed, bool includeRoot = false) { using (ZipFile zip = new ZipFile()) { zip.CompressionLevel = compression; zip.AddDirectory(dirToZip); zip.Save(zipName); } }
public WorkItem(int size, Ionic.Zlib.CompressionLevel compressLevel, CompressionStrategy strategy) { buffer = new byte[size]; // alloc 5 bytes overhead for every block (margin of safety= 2) int n = size + ((size / 32768) + 1) * 5 * 2; compressed = new byte[n]; status = (int)Status.None; compressor = new ZlibCodec(); compressor.InitializeDeflate(compressLevel, false); compressor.OutputBuffer = compressed; compressor.InputBuffer = buffer; }
private void SaveSharedStringHandler(ZipOutputStream stream, Ionic.Zlib.CompressionLevel compressionLevel, string fileName) { //Packaging.ZipPackagePart stringPart; //if (_package.Package.PartExists(SharedStringsUri)) //{ // stringPart=_package.Package.GetPart(SharedStringsUri); //} //else //{ // stringPart = _package.Package.CreatePart(SharedStringsUri, @"application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml", _package.Compression); //Part.CreateRelationship(UriHelper.GetRelativeUri(WorkbookUri, SharedStringsUri), Packaging.TargetMode.Internal, ExcelPackage.schemaRelationships + "/sharedStrings"); //} //StreamWriter sw = new StreamWriter(stringPart.GetStream(FileMode.Create, FileAccess.Write)); //Init Zip stream.CompressionLevel = compressionLevel; stream.PutNextEntry(fileName); StreamWriter sw = new StreamWriter(stream); sw.Write("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?><sst xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\" count=\"{0}\" uniqueCount=\"{0}\">", _sharedStrings.Count); foreach (string t in _sharedStrings.Keys) { SharedStringItem ssi = _sharedStrings[t]; if (ssi.isRichText) { sw.Write("<si>"); ExcelEncodeString(sw, t); sw.Write("</si>"); } else { if (t.Length > 0 && (t[0] == ' ' || t[t.Length - 1] == ' ' || t.Contains(" ") || t.Contains("\t"))) { sw.Write("<si><t xml:space=\"preserve\">"); } else { sw.Write("<si><t>"); } ExcelEncodeString(sw, ExcelEscapeString(t)); sw.Write("</t></si>"); } } sw.Write("</sst>"); sw.Flush(); Part.CreateRelationship(UriHelper.GetRelativeUri(WorkbookUri, SharedStringsUri), Packaging.TargetMode.Internal, ExcelPackage.schemaRelationships + "/sharedStrings"); }
/// <summary> /// Multiple files or directories is encrypted by AES (exactly Rijndael) to use password string. /// 複数のファイル、またはディレクトリをAES(正確にはRijndael)を使って指定のパスワードで暗号化する /// </summary> /// <param name="FilePath">File path or directory path is encrypted</param> /// <param name="OutFilePath">Output encryption file name</param> /// <param name="Password">Encription password string</param> /// <returns>Encryption success(true) or failed(false)</returns> public Tuple <bool, int> Encrypt( object sender, DoWorkEventArgs e, string[] FilePaths, string OutFilePath, string Password, byte[] PasswordBinary, string NewArchiveName) { byte[] bufferPassword; byte[] bufferKey = new byte[32]; _AtcFilePath = OutFilePath; BackgroundWorker worker = sender as BackgroundWorker; //----------------------------------- // Header data is starting. // Progress event handler ArrayList MessageList = new ArrayList(); MessageList.Add(READY_FOR_ENCRYPT); MessageList.Add(Path.GetFileName(OutFilePath)); worker.ReportProgress(0, MessageList); _FileList = new List <string>(); byte[] byteArray = null; using (FileStream outfs = new FileStream(OutFilePath, FileMode.Create, FileAccess.Write)) { // 自己実行形式ファイル(Self-executable file) if (_fExecutable == true) { ExeOutFileSize = rawData.Length; outfs.Write(rawData, 0, (int)ExeOutFileSize); } _StartPos = outfs.Seek(0, SeekOrigin.End); byteArray = new byte[16]; // Plain text header byteArray = BitConverter.GetBytes(DATA_SUB_VERSION); outfs.Write(byteArray, 0, 1); byteArray = null; byteArray = BitConverter.GetBytes(RESERVED_DATA); outfs.Write(byteArray, 0, 1); byteArray = null; byteArray = BitConverter.GetBytes(charMissTypeLimits); outfs.Write(byteArray, 0, 1); byteArray = null; byteArray = BitConverter.GetBytes(fBrocken); outfs.Write(byteArray, 0, 1); byteArray = null; byteArray = Encoding.ASCII.GetBytes(STRING_TOKEN_NORMAL); outfs.Write(byteArray, 0, 16); byteArray = null; byteArray = BitConverter.GetBytes(DATA_FILE_VERSION); outfs.Write(byteArray, 0, 4); byteArray = null; byteArray = BitConverter.GetBytes(TYPE_ALGORISM); outfs.Write(byteArray, 0, 4); // Reserve cipher text header size after encrypting. byteArray = null; byteArray = BitConverter.GetBytes(_AtcHeaderSize); outfs.Write(byteArray, 0, 4); // Cipher text header. using (MemoryStream ms = new MemoryStream()) { byteArray = Encoding.ASCII.GetBytes("Passcode:AttacheCase\n"); ms.Write(byteArray, 0, byteArray.Length); DateTime dt = DateTime.Now; byteArray = Encoding.ASCII.GetBytes("LastDateTime:" + dt.ToString("yyyy/MM/dd HH:mm:ss\n")); ms.Write(byteArray, 0, byteArray.Length); int FileNumber = 0; string ParentPath; ArrayList FileInfoList = new ArrayList(); //---------------------------------------------------------------------- // Put together files in one ( Save as the name ). // 複数ファイルを一つにまとめる(ファイルに名前をつけて保存) if (NewArchiveName != "") { // Now time DateTime dtNow = new DateTime(); FileInfoList.Add("Fn_0:" + // File number NewArchiveName + "\\\t" + // File name "0" + "\t" + // File size "16" + "\t" + // File attribute dtNow.Date.Subtract(new DateTime(1, 1, 1)).TotalDays + "\t" + // Last write date dtNow.TimeOfDay.TotalSeconds + "\t" + // Last write time dtNow.Date.Subtract(new DateTime(1, 1, 1)).TotalDays + "\t" + // Creation date dtNow.TimeOfDay.TotalSeconds); // Creation time FileNumber++; } //---------------------------------------------------------------------- // When encrypt multiple files // 複数のファイルを暗号化する場合 foreach (string FilePath in FilePaths) { ParentPath = Path.GetDirectoryName(FilePath) + "\\"; if ((worker.CancellationPending == true)) { e.Cancel = true; return(Tuple.Create(false, USER_CANCELED)); } //---------------------------------------------------------------------- // 暗号化リストを生成(ファイル) // Create file to encrypt list ( File ) //---------------------------------------------------------------------- if (File.Exists(FilePath) == true) { ArrayList Item = GetFileInfo(ParentPath, FilePath); FileInfoList.Add("Fn_" + FileNumber.ToString() + ":" + // File number //Item[0] + "\t" + // TypeFlag ( Directory: 0, file: 1 ) //Item[1] + "\t" + // Absolute file path Item[2] + "\t" + // Relative file path Item[3].ToString() + "\t" + // File size Item[4].ToString() + "\t" + // File attribute Item[5].ToString() + "\t" + // Last write date Item[6].ToString() + "\t" + // Last write time Item[7].ToString() + "\t" + // Creation date Item[8].ToString()); // Creation time // files only if (Convert.ToInt32(Item[0]) == 1) { // Files list for encryption _FileList.Add(Item[1].ToString()); // Absolute file path // Total file size _TotalFileSize += Convert.ToInt64(Item[3]); } FileNumber++; } //---------------------------------------------------------------------- // 暗号化リストを生成(ディレクトリ) // Create file to encrypt list ( Directory ) //---------------------------------------------------------------------- else { // Directory _FileList.Add(FilePath); // Absolute file path foreach (ArrayList Item in GetFileList(ParentPath, FilePath)) { if ((worker.CancellationPending == true)) { e.Cancel = true; return(Tuple.Create(false, USER_CANCELED)); } if (NewArchiveName != "") { Item[2] = NewArchiveName + "\\" + Item[2]; } FileInfoList.Add("Fn_" + FileNumber.ToString() + ":" + // File number //Item[0] + "\t" + // TypeFlag ( Directory: 0, file: 1 ) //Item[1] + "\t" + // Absolute file path Item[2] + "\t" + // Relative file path Item[3].ToString() + "\t" + // File size Item[4].ToString() + "\t" + // File attribute Item[5].ToString() + "\t" + // Last write date Item[6].ToString() + "\t" + // Last write time Item[7].ToString() + "\t" + // Creation date Item[8].ToString()); // Creation time if (Convert.ToInt32(Item[0]) == 1) { // files only // Files list for encryption _FileList.Add(Item[1].ToString()); // Absolute file path // Total file size _TotalFileSize += Convert.ToInt64(Item[3]); } else { // Directory _FileList.Add(Item[1].ToString()); // Absolute file path } FileNumber++; } // end foreach (ArrayList Item in GetFilesList(ParentPath, FilePath)); } } // end foreach (string FilePath in FilePaths); //---------------------------------------------------------------------- // Check the disk space //---------------------------------------------------------------------- string RootDriveLetter = Path.GetPathRoot(OutFilePath).Substring(0, 1); if (RootDriveLetter == "\\") { // Network } else { DriveInfo drive = new DriveInfo(RootDriveLetter); DriveType driveType = drive.DriveType; switch (driveType) { case DriveType.CDRom: case DriveType.NoRootDirectory: case DriveType.Unknown: break; case DriveType.Fixed: // Local Drive case DriveType.Network: // Mapped Drive case DriveType.Ram: // Ram Drive case DriveType.Removable: // Usually a USB Drive // The drive is not available, or not enough free space. if (drive.IsReady == false || drive.AvailableFreeSpace < _TotalFileSize) { e.Result = NO_DISK_SPACE; // not available free space return(Tuple.Create(false, NO_DISK_SPACE)); } break; } } //---------------------------------------------------------------------- // Create header data string[] FileInfoText = (string[])FileInfoList.ToArray(typeof(string)); // Shift-JIS ( Japanese ) byteArray = Encoding.GetEncoding(932).GetBytes(string.Join("\n", FileInfoText)); ms.Write(byteArray, 0, byteArray.Length); Console.WriteLine(FileInfoText); // UTF-8 byteArray = Encoding.UTF8.GetBytes("\n" + string.Join("\n", FileInfoText).Replace("Fn_", "U_")); ms.Write(byteArray, 0, byteArray.Length); Console.WriteLine(FileInfoText); #if (DEBUG) //Output text file of header contents for debug. Int64 NowPosition = ms.Position; ms.Position = 0; //Save to Desktop folder. string DesktopPath = System.Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); string HeaderTextFilePath = Path.Combine(DesktopPath, "encrypt_header.txt"); FileStream fsDebug = new FileStream(HeaderTextFilePath, FileMode.Create, FileAccess.Write); ms.WriteTo(fsDebug); fsDebug.Close(); ms.Position = NowPosition; #endif // The Header of MemoryStream is encrypted using (Rijndael aes = new RijndaelManaged()) { aes.BlockSize = 256; // BlockSize = 16bytes aes.KeySize = 256; // KeySize = 16bytes aes.Mode = CipherMode.CBC; // CBC mode //aes.Padding = PaddingMode.Zeros; // Padding mode is "None". // Password if (PasswordBinary != null) { // Binary bufferPassword = PasswordBinary; } else { // Text bufferPassword = Encoding.UTF8.GetBytes(Password); //byte[] bufferPassword = Encoding.GetEncoding(932).GetBytes(Password); // Shift-JIS } // Password is 256 bit, so truncated up to 32 bytes or fill up the data size. // パスワードは256 bitなので、32バイトまで切り詰めるか、あるいはそのサイズまで埋める処理 for (int i = 0; i < bufferKey.Length; i++) { if (i < bufferPassword.Length) { // Cut down to 32 bytes characters. bufferKey[i] = bufferPassword[i]; } else { bufferKey[i] = 0; // Zero filled } } aes.Key = bufferKey; // Initilization Vector aes.GenerateIV(); outfs.Write(aes.IV, 0, 32); ms.Position = 0; //Encryption interface. ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV); using (CryptoStream cse = new CryptoStream(outfs, encryptor, CryptoStreamMode.Write)) { //---------------------------------------------------------------------- // ヘッダーの暗号化 //---------------------------------------------------------------------- int len = 0; _AtcHeaderSize = 0; // exclude IV of header buffer = new byte[BUFFER_SIZE]; while ((len = ms.Read(buffer, 0, BUFFER_SIZE)) > 0) { cse.Write(buffer, 0, len); _AtcHeaderSize += len; } } } // end using (Rijndael aes = new RijndaelManaged()); } // end using (MemoryStream ms = new MemoryStream()); } // end using (FileStream outfs = new FileStream(OutFilePath, FileMode.Create, FileAccess.Write)); //---------------------------------------------------------------------- // 本体データの暗号化 //---------------------------------------------------------------------- using (FileStream outfs = new FileStream(OutFilePath, FileMode.OpenOrCreate, FileAccess.Write)) { byteArray = new byte[4]; // Back to current positon of 'encrypted file size' if (_fExecutable == true) { outfs.Seek(ExeOutFileSize + 28, SeekOrigin.Begin); // self executable file } else { outfs.Seek(28, SeekOrigin.Begin); } byteArray = BitConverter.GetBytes(_AtcHeaderSize); outfs.Write(byteArray, 0, 4); // Out file stream postion move to end outfs.Seek(0, SeekOrigin.End); // The Header of MemoryStream is encrypted using (Rijndael aes = new RijndaelManaged()) { aes.BlockSize = 256; // BlockSize = 16bytes aes.KeySize = 256; // KeySize = 16bytes aes.Mode = CipherMode.CBC; // CBC mode //aes.Padding = PaddingMode.PKCS7; // Padding mode is "PKCS7". // Password is 256 bit, so truncated up to 32 bytes or fill up the data size. for (int i = 0; i < bufferKey.Length; i++) { if (i < bufferPassword.Length) { //Cut down to 32bytes characters. bufferKey[i] = bufferPassword[i]; } else { bufferKey[i] = 0; } } aes.Key = bufferKey; // Initilization Vector byte[] iv = new byte[32]; RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); rng.GetNonZeroBytes(iv); aes.IV = iv; outfs.Write(iv, 0, 32); // Encryption interface. ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV); using (CryptoStream cse = new CryptoStream(outfs, encryptor, CryptoStreamMode.Write)) { // zlib 2bytes header cse.WriteByte(0x78); // cse.WriteByte(0x01); //No Compression/low cse.WriteByte(0x9C); //Default Compression //cse.WriteByte(0xDA); //Best Compression Ionic.Zlib.CompressionLevel flv = Ionic.Zlib.CompressionLevel.Default; switch (AppSettings.Instance.CompressRate) { case 0: flv = Ionic.Zlib.CompressionLevel.Level0; break; case 1: flv = Ionic.Zlib.CompressionLevel.Level1; break; case 2: flv = Ionic.Zlib.CompressionLevel.Level2; break; case 3: flv = Ionic.Zlib.CompressionLevel.Level3; break; case 4: flv = Ionic.Zlib.CompressionLevel.Level4; break; case 5: flv = Ionic.Zlib.CompressionLevel.Level5; break; case 6: flv = Ionic.Zlib.CompressionLevel.Level6; break; case 7: flv = Ionic.Zlib.CompressionLevel.Level7; break; case 8: flv = Ionic.Zlib.CompressionLevel.Level8; break; case 9: flv = Ionic.Zlib.CompressionLevel.Level9; break; } using (Ionic.Zlib.DeflateStream ds = new Ionic.Zlib.DeflateStream(cse, Ionic.Zlib.CompressionMode.Compress, flv)) { int len = 0; foreach (string path in _FileList) { // Only file is encrypted if (File.Exists(path) == true) { buffer = new byte[BUFFER_SIZE]; using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read)) { len = 0; while ((len = fs.Read(buffer, 0, BUFFER_SIZE)) > 0) { ds.Write(buffer, 0, len); _TotalSize += len; string MessageText = ""; if (_TotalNumberOfFiles > 1) { MessageText = path + " ( " + _NumberOfFiles.ToString() + " files/ " + _TotalNumberOfFiles.ToString() + " folders )"; } else { MessageText = path; } MessageList = new ArrayList(); MessageList.Add(DECRYPTING); MessageList.Add(MessageText); float percent = ((float)_TotalSize / _TotalFileSize); worker.ReportProgress((int)(percent * 10000), MessageList); if (worker.CancellationPending == true) { e.Cancel = true; return(Tuple.Create(false, USER_CANCELED)); } } } } // end if (File.Exists(path) == true); } // end foreach (string path in _FileList); /* * Random r = new Random(); * byteArray = new byte[BUFFER_SIZE]; * r.NextBytes(byteArray); * ds.Write(buffer, 0, BUFFER_SIZE); */ } // end using ( Ionic.Zlib.DeflateStream ds); } // end using (CryptoStream cse); } // end using (Rijndael aes = new RijndaelManaged()); } // end using (FileStream outfs = new FileStream(OutFilePath, FileMode.Create, FileAccess.Write)); // Self-executable file if (fExecutable == true) { using (FileStream outfs = new FileStream(OutFilePath, FileMode.Open, FileAccess.Write)) { Int64 DataSize = outfs.Seek(0, SeekOrigin.End); DataSize = DataSize - _StartPos; byteArray = BitConverter.GetBytes(DataSize); outfs.Write(byteArray, 0, sizeof(Int64)); } } // Set the timestamp of encryption file to original files or directories if (_fKeepTimeStamp == true) { DateTime dtCreate = File.GetCreationTime((string)AppSettings.Instance.FileList[0]); DateTime dtUpdate = File.GetLastWriteTime((string)AppSettings.Instance.FileList[0]); DateTime dtAccess = File.GetLastAccessTime((string)AppSettings.Instance.FileList[0]); File.SetCreationTime(OutFilePath, dtCreate); File.SetLastWriteTime(OutFilePath, dtUpdate); File.SetLastAccessTime(OutFilePath, dtAccess); } //Encryption succeed. e.Result = ENCRYPT_SUCCEEDED; return(Tuple.Create(true, ENCRYPT_SUCCEEDED)); } // encrypt();
/// <summary> /// Create a ParallelDeflateOutputStream using the specified /// CompressionLevel and CompressionStrategy, and specifying whether to /// leave the captive stream open when the ParallelDeflateOutputStream is /// closed. /// </summary> /// <remarks> /// See the <see cref="ParallelDeflateOutputStream(System.IO.Stream)"/> /// constructor for example code. /// </remarks> /// <param name="stream">The stream to which compressed data will be written.</param> /// <param name="level">A tuning knob to trade speed for effectiveness.</param> /// <param name="strategy"> /// By tweaking this parameter, you may be able to optimize the compression for /// data with particular characteristics. /// </param> /// <param name="leaveOpen"> /// true if the application would like the stream to remain open after inflation/deflation. /// </param> public ParallelDeflateOutputStream(System.IO.Stream stream, CompressionLevel level, CompressionStrategy strategy, bool leaveOpen) { TraceOutput(TraceBits.Lifecycle | TraceBits.Session, "-------------------------------------------------------"); TraceOutput(TraceBits.Lifecycle | TraceBits.Session, "Create {0:X8}", this.GetHashCode()); _outStream = stream; _compressLevel= level; Strategy = strategy; _leaveOpen = leaveOpen; this.MaxBufferPairs = 16; // default }
/// <summary> /// Multiple files or directories is encrypted by AES (exactly Rijndael) to use password string. /// 複数のファイル、またはディレクトリをAES(正確にはRijndael)を使って指定のパスワードで暗号化する /// </summary> /// <param name="FilePath">File path or directory path is encrypted</param> /// <param name="OutFilePath">Output encryption file name</param> /// <param name="Password">Encription password string</param> /// <returns>Encryption success(true) or failed(false)</returns> public Tuple <bool, int> Encrypt( object sender, DoWorkEventArgs e, string[] FilePaths, string OutFilePath, string Password, byte[] PasswordBinary, string NewArchiveName) { _AtcFilePath = OutFilePath; BackgroundWorker worker = sender as BackgroundWorker; // The timestamp of original file DateTime dtCreate = File.GetCreationTime(FilePaths[0]); DateTime dtUpdate = File.GetLastWriteTime(FilePaths[0]); DateTime dtAccess = File.GetLastAccessTime(FilePaths[0]); // Create Header data. ArrayList MessageList = new ArrayList(); MessageList.Add(READY_FOR_ENCRYPT); MessageList.Add(Path.GetFileName(OutFilePath)); worker.ReportProgress(0, MessageList); _FileList = new List <string>(); byte[] byteArray = null; // Salt Rfc2898DeriveBytes deriveBytes; if (PasswordBinary == null) { // String Password deriveBytes = new Rfc2898DeriveBytes(Password, 8, 1000); } else { // Binary Password byte[] random_salt = new byte[8]; RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); rng.GetBytes(random_salt); deriveBytes = new Rfc2898DeriveBytes(PasswordBinary, random_salt, 1000); } byte[] salt = deriveBytes.Salt; byte[] key = deriveBytes.GetBytes(32); byte[] iv = deriveBytes.GetBytes(32); using (FileStream outfs = new FileStream(OutFilePath, FileMode.Create, FileAccess.Write)) { // 自己実行形式ファイル(Self-executable file) if (_fExecutable == true) { ExeOutFileSize = rawData.Length; outfs.Write(rawData, 0, (int)ExeOutFileSize); } _StartPos = outfs.Seek(0, SeekOrigin.End); // Application version Version ver = ApplicationInfo.Version; short vernum = Int16.Parse(ver.ToString().Replace(".", "")); byteArray = BitConverter.GetBytes(vernum); outfs.Write(byteArray, 0, 2); // Input password limit byteArray = BitConverter.GetBytes(_MissTypeLimits); outfs.Write(byteArray, 0, 1); // Exceed the password input limit, destroy the file? byteArray = BitConverter.GetBytes(fBrocken); outfs.Write(byteArray, 0, 1); // Token that this is the AttacheCase file byteArray = Encoding.ASCII.GetBytes(STRING_TOKEN_NORMAL); outfs.Write(byteArray, 0, 16); // File sub version byteArray = BitConverter.GetBytes(DATA_FILE_VERSION); outfs.Write(byteArray, 0, 4); // The size of encrypted Atc header size ( reserved ) byteArray = BitConverter.GetBytes((int)0); outfs.Write(byteArray, 0, 4); // Salt outfs.Write(salt, 0, 8); // Cipher text header. using (MemoryStream ms = new MemoryStream()) { byteArray = Encoding.ASCII.GetBytes(AtC_ENCRYPTED_TOKEN + "\n"); ms.Write(byteArray, 0, byteArray.Length); int FileNumber = 0; string ParentPath; ArrayList FileInfoList = new ArrayList(); //---------------------------------------------------------------------- // Put together files in one ( Save as the name ). // 複数ファイルを一つにまとめる(ファイルに名前をつけて保存) if (NewArchiveName != "") { // Now time DateTime dtNow = new DateTime(); FileInfoList.Add("0:" + // File number NewArchiveName + "\\\t" + // File name "0" + "\t" + // File size "16" + "\t" + // File attribute dtNow.Date.Subtract(new DateTime(1, 1, 1)).TotalDays + "\t" + // Last write date dtNow.TimeOfDay.TotalSeconds + "\t" + // Last write time dtNow.Date.Subtract(new DateTime(1, 1, 1)).TotalDays + "\t" + // Creation date dtNow.TimeOfDay.TotalSeconds); // Creation time FileNumber++; } //---------------------------------------------------------------------- // When encrypt multiple files // 複数のファイルを暗号化する場合 foreach (string FilePath in FilePaths) { ParentPath = Path.GetDirectoryName(FilePath); if (ParentPath.EndsWith("\\") == false) // In case of 'C:\\' root direcroy. { ParentPath = ParentPath + "\\"; } if ((worker.CancellationPending == true)) { e.Cancel = true; return(Tuple.Create(false, USER_CANCELED)); } //---------------------------------------------------------------------- // 暗号化リストを生成(ファイル) // Create file to encrypt list ( File ) //---------------------------------------------------------------------- if (File.Exists(FilePath) == true) { ArrayList Item = GetFileInfo(ParentPath, FilePath); FileInfoList.Add(FileNumber.ToString() + ":" + // File number //Item[0] + "\t" + // TypeFlag ( Directory: 0, file: 1 ) //Item[1] + "\t" + // Absolute file path Item[2] + "\t" + // Relative file path Item[3].ToString() + "\t" + // File size Item[4].ToString() + "\t" + // File attribute Item[5].ToString() + "\t" + // Last write date Item[6].ToString() + "\t" + // Last write time Item[7].ToString() + "\t" + // Creation date Item[8].ToString() + "\t" + // Creation time Item[9].ToString()); // SHA-256 Hash string // files only if (Convert.ToInt32(Item[0]) == 1) { // Files list for encryption _FileList.Add(Item[1].ToString()); // Absolute file path // Total file size _TotalFileSize += Convert.ToInt64(Item[3]); } FileNumber++; } //---------------------------------------------------------------------- // 暗号化リストを生成(ディレクトリ) // Create file to encrypt list ( Directory ) //---------------------------------------------------------------------- else { // Directory _FileList.Add(FilePath); // Absolute file path foreach (ArrayList Item in GetFileList(ParentPath, FilePath)) { if ((worker.CancellationPending == true)) { e.Cancel = true; return(Tuple.Create(false, USER_CANCELED)); } if (NewArchiveName != "") { Item[2] = NewArchiveName + "\\" + Item[2]; } if ((int)Item[0] == 0) { // Directory FileInfoList.Add(FileNumber.ToString() + ":" + // File number Item[2] + "\t" + // Relative file path Item[3].ToString() + "\t" + // File size Item[4].ToString() + "\t" + // File attribute Item[5].ToString() + "\t" + // Last write date Item[6].ToString() + "\t" + // Last write time Item[7].ToString() + "\t" + // Creation date Item[8].ToString()); // Creation time } else { // File FileInfoList.Add(FileNumber.ToString() + ":" + // File number Item[2] + "\t" + // Relative file path Item[3].ToString() + "\t" + // File size Item[4].ToString() + "\t" + // File attribute Item[5].ToString() + "\t" + // Last write date Item[6].ToString() + "\t" + // Last write time Item[7].ToString() + "\t" + // Creation date Item[8].ToString() + "\t" + // Creation time Item[9].ToString()); // SHA-256 hash } if (Convert.ToInt32(Item[0]) == 1) { // files only // Files list for encryption _FileList.Add(Item[1].ToString()); // Absolute file path // Total file size _TotalFileSize += Convert.ToInt64(Item[3]); } else { // Directory _FileList.Add(Item[1].ToString()); // Absolute file path } FileNumber++; } // end foreach (ArrayList Item in GetFilesList(ParentPath, FilePath)); } // if (File.Exists(FilePath) == true); } // end foreach (string FilePath in FilePaths); //---------------------------------------------------------------------- // Check the disk space //---------------------------------------------------------------------- string RootDriveLetter = Path.GetPathRoot(OutFilePath).Substring(0, 1); if (RootDriveLetter == "\\") { // Network } else { DriveInfo drive = new DriveInfo(RootDriveLetter); DriveType driveType = drive.DriveType; switch (driveType) { case DriveType.CDRom: case DriveType.NoRootDirectory: case DriveType.Unknown: break; case DriveType.Fixed: // Local Drive case DriveType.Network: // Mapped Drive case DriveType.Ram: // Ram Drive case DriveType.Removable: // Usually a USB Drive // The drive is not available, or not enough free space. if (drive.IsReady == false || drive.AvailableFreeSpace < _TotalFileSize) { e.Result = NO_DISK_SPACE; // not available free space return(Tuple.Create(false, NO_DISK_SPACE)); } break; } } //---------------------------------------------------------------------- // Create header data string[] FileInfoText = (string[])FileInfoList.ToArray(typeof(string)); byteArray = Encoding.UTF8.GetBytes(string.Join("\n", FileInfoText)); ms.Write(byteArray, 0, byteArray.Length); #if (DEBUG) //Output text file of header contents for debug. Int64 NowPosition = ms.Position; ms.Position = 0; //Save to Desktop folder. string AppDirPath = Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath); string HeaderTextFilePath = Path.Combine(AppDirPath, "encrypt_header.txt"); using (FileStream fsDebug = new FileStream(HeaderTextFilePath, FileMode.Create, FileAccess.Write)) { ms.WriteTo(fsDebug); ms.Position = NowPosition; } #endif // The Header of MemoryStream is encrypted using (Rijndael aes = new RijndaelManaged()) { aes.BlockSize = 256; // BlockSize = 16bytes aes.KeySize = 256; // KeySize = 16bytes aes.Mode = CipherMode.CBC; // CBC mode //aes.Padding = PaddingMode.Zeros; // Padding mode is "None". aes.Key = key; aes.IV = iv; ms.Position = 0; //Encryption interface. ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV); using (CryptoStream cse = new CryptoStream(outfs, encryptor, CryptoStreamMode.Write)) { //---------------------------------------------------------------------- // ヘッダーの暗号化 //---------------------------------------------------------------------- int len = 0; _AtcHeaderSize = 0; // exclude IV of header buffer = new byte[BUFFER_SIZE]; while ((len = ms.Read(buffer, 0, BUFFER_SIZE)) > 0) { cse.Write(buffer, 0, len); _AtcHeaderSize += len; } } } // end using (Rijndael aes = new RijndaelManaged()); } // end using (MemoryStream ms = new MemoryStream()); } // end using (FileStream outfs = new FileStream(OutFilePath, FileMode.Create, FileAccess.Write)); //---------------------------------------------------------------------- // 本体データの暗号化 //---------------------------------------------------------------------- using (FileStream outfs = new FileStream(OutFilePath, FileMode.OpenOrCreate, FileAccess.Write)) { try { byteArray = new byte[4]; // Back to current positon of 'encrypted file size' if (_fExecutable == true) { outfs.Seek(ExeOutFileSize + 24, SeekOrigin.Begin); // self executable file } else { outfs.Seek(24, SeekOrigin.Begin); } byteArray = BitConverter.GetBytes(_AtcHeaderSize); outfs.Write(byteArray, 0, 4); // Out file stream postion move to end outfs.Seek(0, SeekOrigin.End); // The Header of MemoryStream is encrypted using (Rijndael aes = new RijndaelManaged()) { aes.BlockSize = 256; // BlockSize = 16bytes aes.KeySize = 256; // KeySize = 16bytes aes.Mode = CipherMode.CBC; // CBC mode aes.Padding = PaddingMode.Zeros; // Padding mode aes.Key = key; aes.IV = iv; // Encryption interface. ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV); using (CryptoStream cse = new CryptoStream(outfs, encryptor, CryptoStreamMode.Write)) { Ionic.Zlib.CompressionLevel flv = Ionic.Zlib.CompressionLevel.Default; switch (AppSettings.Instance.CompressRate) { case 0: flv = Ionic.Zlib.CompressionLevel.Level0; break; case 1: flv = Ionic.Zlib.CompressionLevel.Level1; break; case 2: flv = Ionic.Zlib.CompressionLevel.Level2; break; case 3: flv = Ionic.Zlib.CompressionLevel.Level3; break; case 4: flv = Ionic.Zlib.CompressionLevel.Level4; break; case 5: flv = Ionic.Zlib.CompressionLevel.Level5; break; case 6: flv = Ionic.Zlib.CompressionLevel.Level6; break; case 7: flv = Ionic.Zlib.CompressionLevel.Level7; break; case 8: flv = Ionic.Zlib.CompressionLevel.Level8; break; case 9: flv = Ionic.Zlib.CompressionLevel.Level9; break; } using (Ionic.Zlib.DeflateStream ds = new Ionic.Zlib.DeflateStream(cse, Ionic.Zlib.CompressionMode.Compress, flv)) { int len = 0; foreach (string path in _FileList) { // Only file is encrypted if (File.Exists(path) == true) { try { buffer = new byte[BUFFER_SIZE]; using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) { len = 0; while ((len = fs.Read(buffer, 0, BUFFER_SIZE)) > 0) { ds.Write(buffer, 0, len); _TotalSize += len; string MessageText = ""; if (_TotalNumberOfFiles > 1) { MessageText = path + " ( " + _NumberOfFiles.ToString() + " / " + _TotalNumberOfFiles.ToString() + " files )"; } else { MessageText = path; } float percent = ((float)_TotalSize / _TotalFileSize); MessageList = new ArrayList(); MessageList.Add(ENCRYPTING); MessageList.Add(MessageText); worker.ReportProgress((int)(percent * 10000), MessageList); if (worker.CancellationPending == true) { fs.Dispose(); e.Cancel = true; return(Tuple.Create(false, USER_CANCELED)); } } } } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message.ToString()); e.Result = ERROR_UNEXPECTED; return(Tuple.Create(false, ERROR_UNEXPECTED)); } } // end if (File.Exists(path) == true); } // end foreach (string path in _FileList); /* * for (int i = 0; i < 10; i++) * { * Random r = new Random(); * byteArray = new byte[BUFFER_SIZE]; * r.NextBytes(byteArray); * cse.Write(buffer, 0, BUFFER_SIZE); * } */ } // end using ( Ionic.Zlib.DeflateStream ds); } // end using (CryptoStream cse); } // end using (Rijndael aes = new RijndaelManaged()); } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message.ToString()); e.Result = ERROR_UNEXPECTED; return(Tuple.Create(false, ERROR_UNEXPECTED)); } } // end using (FileStream outfs = new FileStream(OutFilePath, FileMode.Create, FileAccess.Write)); // Set the timestamp of encryption file to original files or directories if (_fKeepTimeStamp == true) { File.SetCreationTime(OutFilePath, dtCreate); File.SetLastWriteTime(OutFilePath, dtUpdate); File.SetLastAccessTime(OutFilePath, dtAccess); } else { dtUpdate = DateTime.Now; File.SetLastWriteTime(OutFilePath, dtUpdate); } //Encryption succeed. e.Result = ENCRYPT_SUCCEEDED; return(Tuple.Create(true, ENCRYPT_SUCCEEDED)); } // encrypt();
public void AddFilesAndDeleteFromDisk([NotNull] IEnumerable <FileInfo> files, string zipArchiveName, Ionic.Zlib.CompressionLevel level) { var fileInfos = files as FileInfo[] ?? files.ToArray(); if (fileInfos.Any()) { var filePerDates = fileInfos.OrderBy(x => x.LastWriteTimeUtc).ToList(); var d = new Dictionary <string, FileInfo>(); foreach (var filePerDate in filePerDates) { d.Add(filePerDate.Name, filePerDate); } AddEntries(d, zipArchiveName, level); } }
public void AddEntryToZip(FileInfo f, [NotNull] string entryName, string zipArchiveName, Ionic.Zlib.CompressionLevel level) { var d = new Dictionary <string, FileInfo>() { { entryName, f } }; AddEntries(d, zipArchiveName, level); }
public void AddEntries(Dictionary <string, FileInfo> files, string zipArchiveName, Ionic.Zlib.CompressionLevel level) { try { List <string> entryAdded = new List <string>(); List <string> entryDeleted = new List <string>(); if (files.Count > 0) { lock (_zipLock) { var filesToDelete = new List <string>(); // using (var izip = new Ionic.Zip.ZipFile(zipArchiveName)) { izip.CompressionLevel = level; foreach (var keyValuePair in files) { try { if (keyValuePair.Value.Exists) { ZipEntry e = izip.AddFile(keyValuePair.Value.FullName); e.FileName = keyValuePair.Key; entryAdded.Add(e.FileName); filesToDelete.Add(keyValuePair.Value.FullName); } } catch { // } } izip.Save(); } foreach (var fileToDelete in filesToDelete) { try { System.IO.File.Delete(fileToDelete); entryDeleted.Add(fileToDelete); } catch { } } FileInfo ziFileInfo = new FileInfo(zipArchiveName); OnLogRotated(new ZipRotationPerformedEventArgs(zipArchiveName, entryAdded, entryDeleted, ziFileInfo.Length)); } } } catch /*(Exception exception)*/ { // } }
public bool Encrypt( object sender, DoWorkEventArgs e, string[] FilePaths, string OutFilePath, string Password, byte[] PasswordBinary, string NewArchiveName) { #if (DEBUG) Logger lg = new Logger(); lg.Info("-----------------------------------"); lg.Info(OutFilePath); lg.Info("Encryotion satrt."); lg.StopWatchStart(); #endif _AtcFilePath = OutFilePath; BackgroundWorker worker = sender as BackgroundWorker; // The timestamp of original file DateTime dtCreate = File.GetCreationTime(FilePaths[0]); DateTime dtUpdate = File.GetLastWriteTime(FilePaths[0]); DateTime dtAccess = File.GetLastAccessTime(FilePaths[0]); // Create Header data. ArrayList MessageList = new ArrayList { READY_FOR_ENCRYPT, Path.GetFileName(_AtcFilePath) }; worker.ReportProgress(0, MessageList); // Stopwatch for measuring time and adjusting the progress bar display Stopwatch swEncrypt = new Stopwatch(); Stopwatch swProgress = new Stopwatch(); swEncrypt.Start(); swProgress.Start(); float percent = 0; _FileList = new List <string>(); byte[] byteArray = null; // Salt Rfc2898DeriveBytes deriveBytes; if (PasswordBinary == null) { // String Password deriveBytes = new Rfc2898DeriveBytes(Password, 8, 1000); } else { // Binary Password byte[] random_salt = new byte[8]; RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); rng.GetBytes(random_salt); deriveBytes = new Rfc2898DeriveBytes(PasswordBinary, random_salt, 1000); } byte[] salt = deriveBytes.Salt; byte[] key = deriveBytes.GetBytes(32); byte[] iv = deriveBytes.GetBytes(32); try { using (FileStream outfs = new FileStream(_AtcFilePath, FileMode.Create, FileAccess.Write)) { // 自己実行形式ファイル(Self-executable file) if (_fExecutable == true) { // Read from ExeOut3.cs ExeOutFileSize = rawData.Length; outfs.Write(rawData, 0, (int)ExeOutFileSize); } _StartPos = outfs.Seek(0, SeekOrigin.End); // Application version Version ver = ApplicationInfo.Version; short vernum = Int16.Parse(ver.ToString().Replace(".", "")); byteArray = BitConverter.GetBytes(vernum); outfs.Write(byteArray, 0, 2); // Input password limit byteArray = BitConverter.GetBytes(_MissTypeLimits); outfs.Write(byteArray, 0, 1); // Exceed the password input limit, destroy the file? byteArray = BitConverter.GetBytes(fBrocken); outfs.Write(byteArray, 0, 1); // Token that this is the AttacheCase file byteArray = Encoding.ASCII.GetBytes(STRING_TOKEN_NORMAL); outfs.Write(byteArray, 0, 16); // File sub version byteArray = BitConverter.GetBytes(DATA_FILE_VERSION); outfs.Write(byteArray, 0, 4); // The size of encrypted Atc header size ( reserved ) byteArray = BitConverter.GetBytes((int)0); outfs.Write(byteArray, 0, 4); // Salt outfs.Write(salt, 0, 8); // Cipher text header. using (MemoryStream ms = new MemoryStream()) { byteArray = Encoding.ASCII.GetBytes(AtC_ENCRYPTED_TOKEN + "\n"); ms.Write(byteArray, 0, byteArray.Length); int FileNumber = 0; string ParentPath; ArrayList FileInfoList = new ArrayList(); //---------------------------------------------------------------------- // Put together files in one ( Save as the name ). // 複数ファイルを一つにまとめる(ファイルに名前をつけて保存) if (NewArchiveName != "") { NewArchiveName = NewArchiveName + "\\"; // Now time DateTime dtNow = new DateTime(); FileInfoList.Add("0:" + // File number NewArchiveName + "\t" + // File name "0" + "\t" + // File size "16" + "\t" + // File attribute dtNow.Date.Subtract(new DateTime(1, 1, 1)).TotalDays + "\t" + // Last write date dtNow.TimeOfDay.TotalSeconds + "\t" + // Last write time dtNow.Date.Subtract(new DateTime(1, 1, 1)).TotalDays + "\t" + // Creation date dtNow.TimeOfDay.TotalSeconds + "\t" + // Creation time "" + "\t" + // ver.3.2.3.0 ~ DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss") + "\t" + DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss")); FileNumber++; } //---------------------------------------------------------------------- // When encrypt multiple files // 複数のファイルを暗号化する場合 foreach (string FilePath in FilePaths) { ParentPath = Path.GetDirectoryName(FilePath); if (ParentPath.EndsWith("\\") == false) // In case of 'C:\\' root direcroy. { ParentPath = ParentPath + "\\"; } if ((worker.CancellationPending == true)) { e.Cancel = true; return(false); } //---------------------------------------------------------------------- // 暗号化リストを生成(ファイル) // Create file to encrypt list ( File ) //---------------------------------------------------------------------- if (File.Exists(FilePath) == true) { ArrayList Item = GetFileInfo(ParentPath, FilePath); FileInfoList.Add(FileNumber.ToString() + ":" + // File number //Item[0] + "\t" + // TypeFlag ( Directory: 0, file: 1 ) //Item[1] + "\t" + // Absolute file path NewArchiveName + Item[2] + "\t" + // Relative file path Item[3].ToString() + "\t" + // File size Item[4].ToString() + "\t" + // File attribute Item[5].ToString() + "\t" + // Last write date Item[6].ToString() + "\t" + // Last write time Item[7].ToString() + "\t" + // Creation date Item[8].ToString() + "\t" + // Creation time Item[9].ToString() + "\t" + // SHA-256 Hash string // ver.3.2.3.0 ~ Item[10].ToString() + "\t" + // Last write date time(UTC) Item[11].ToString()); // Creation date time(UTC) // files only if (Convert.ToInt32(Item[0]) == 1) { // Files list for encryption _FileList.Add(Item[1].ToString()); // Absolute file path // Total file size _TotalFileSize += Convert.ToInt64(Item[3]); } FileNumber++; } //---------------------------------------------------------------------- // 暗号化リストを生成(ディレクトリ) // Create file to encrypt list ( Directory ) //---------------------------------------------------------------------- else { // Directory _FileList.Add(FilePath); // Absolute file path foreach (ArrayList Item in GetFileList(ParentPath, FilePath)) { if ((worker.CancellationPending == true)) { e.Cancel = true; return(false); } if (NewArchiveName != "") { Item[2] = NewArchiveName + "\\" + Item[2]; } if ((int)Item[0] == 0) { // Directory FileInfoList.Add(FileNumber.ToString() + ":" + // File number NewArchiveName + Item[2] + "\t" + // Relative file path Item[3].ToString() + "\t" + // File size Item[4].ToString() + "\t" + // File attribute Item[5].ToString() + "\t" + // Last write date Item[6].ToString() + "\t" + // Last write time Item[7].ToString() + "\t" + // Creation date Item[8].ToString() + "\t" + // Creation time "" + "\t" + // ver.3.2.3.0 ~ Item[10].ToString() + "\t" + // Last write date time(UTC) Item[11].ToString()); // Creation date date time(UTC) } else { // File FileInfoList.Add(FileNumber.ToString() + ":" + // File number NewArchiveName + Item[2] + "\t" + // Relative file path Item[3].ToString() + "\t" + // File size Item[4].ToString() + "\t" + // File attribute Item[5].ToString() + "\t" + // Last write date Item[6].ToString() + "\t" + // Last write time Item[7].ToString() + "\t" + // Creation date Item[8].ToString() + "\t" + // Creation time Item[9].ToString() + "\t" + // SHA-256 hash // ver.3.2.3.0 ~ Item[10].ToString() + "\t" + // Last write date time(UTC) Item[11].ToString()); // Creation date date time(UTC) } if (Convert.ToInt32(Item[0]) == 1) { // files only // Files list for encryption _FileList.Add(Item[1].ToString()); // Absolute file path // Total file size _TotalFileSize += Convert.ToInt64(Item[3]); } else { // Directory _FileList.Add(Item[1].ToString()); // Absolute file path } FileNumber++; } // end foreach (ArrayList Item in GetFilesList(ParentPath, FilePath)); } // if (File.Exists(FilePath) == true); } // end foreach (string FilePath in FilePaths); //---------------------------------------------------------------------- // Check the disk space //---------------------------------------------------------------------- string RootDriveLetter = Path.GetPathRoot(_AtcFilePath).Substring(0, 1); if (RootDriveLetter == "\\") { // Network } else { DriveInfo drive = new DriveInfo(RootDriveLetter); DriveType driveType = drive.DriveType; switch (driveType) { case DriveType.CDRom: case DriveType.NoRootDirectory: case DriveType.Unknown: break; case DriveType.Fixed: // Local Drive case DriveType.Network: // Mapped Drive case DriveType.Ram: // Ram Drive case DriveType.Removable: // Usually a USB Drive // The drive is not available, or not enough free space. if (drive.IsReady == false || drive.AvailableFreeSpace < _TotalFileSize) { // not available free space _ReturnCode = NO_DISK_SPACE; _DriveName = drive.ToString(); //_TotalFileSize = _TotalFileSize; _AvailableFreeSpace = drive.AvailableFreeSpace; return(false); } break; } } //---------------------------------------------------------------------- // Create header data string[] FileInfoText = (string[])FileInfoList.ToArray(typeof(string)); #if (DEBUG) string DesktopPath = System.Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); string FileListTextPath = Path.Combine(DesktopPath, "_header_text.txt"); var FileListText = String.Join("\n", FileInfoText); System.IO.File.WriteAllText(FileListTextPath, FileListText, System.Text.Encoding.UTF8); #endif byteArray = Encoding.UTF8.GetBytes(string.Join("\n", FileInfoText)); ms.Write(byteArray, 0, byteArray.Length); // The Header of MemoryStream is encrypted using (Rijndael aes = new RijndaelManaged()) { aes.BlockSize = 256; // BlockSize = 16bytes aes.KeySize = 256; // KeySize = 16bytes aes.Mode = CipherMode.CBC; // CBC mode //aes.Padding = PaddingMode.Zeros; // Padding mode is "None". aes.Key = key; aes.IV = iv; ms.Position = 0; //Encryption interface. ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV); using (CryptoStream cse = new CryptoStream(outfs, encryptor, CryptoStreamMode.Write)) { //---------------------------------------------------------------------- // ヘッダーの暗号化 //---------------------------------------------------------------------- int len = 0; _AtcHeaderSize = 0; // exclude IV of header buffer = new byte[BUFFER_SIZE]; while ((len = ms.Read(buffer, 0, BUFFER_SIZE)) > 0) { cse.Write(buffer, 0, len); _AtcHeaderSize += len; } } } // end using (Rijndael aes = new RijndaelManaged()); } // end using (MemoryStream ms = new MemoryStream()); } // end using (FileStream outfs = new FileStream(_AtcFilePath, FileMode.Create, FileAccess.Write)); //---------------------------------------------------------------------- // 本体データの暗号化 //---------------------------------------------------------------------- using (FileStream outfs = new FileStream(_AtcFilePath, FileMode.OpenOrCreate, FileAccess.Write)) { byteArray = new byte[4]; // Back to current positon of 'encrypted file size' if (_fExecutable == true) { outfs.Seek(ExeOutFileSize + 24, SeekOrigin.Begin); // self executable file } else { outfs.Seek(24, SeekOrigin.Begin); } byteArray = BitConverter.GetBytes(_AtcHeaderSize); outfs.Write(byteArray, 0, 4); // Out file stream postion move to end outfs.Seek(0, SeekOrigin.End); // The Header of MemoryStream is encrypted using (Rijndael aes = new RijndaelManaged()) { aes.BlockSize = 256; // BlockSize = 16bytes aes.KeySize = 256; // KeySize = 16bytes aes.Mode = CipherMode.CBC; // CBC mode aes.Padding = PaddingMode.Zeros; // Padding mode aes.Key = key; aes.IV = iv; // Encryption interface. ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV); using (CryptoStream cse = new CryptoStream(outfs, encryptor, CryptoStreamMode.Write)) { Ionic.Zlib.CompressionLevel flv = Ionic.Zlib.CompressionLevel.Default; switch (AppSettings.Instance.CompressRate) { case 0: flv = Ionic.Zlib.CompressionLevel.Level0; break; case 1: flv = Ionic.Zlib.CompressionLevel.Level1; break; case 2: flv = Ionic.Zlib.CompressionLevel.Level2; break; case 3: flv = Ionic.Zlib.CompressionLevel.Level3; break; case 4: flv = Ionic.Zlib.CompressionLevel.Level4; break; case 5: flv = Ionic.Zlib.CompressionLevel.Level5; break; case 6: flv = Ionic.Zlib.CompressionLevel.Level6; break; case 7: flv = Ionic.Zlib.CompressionLevel.Level7; break; case 8: flv = Ionic.Zlib.CompressionLevel.Level8; break; case 9: flv = Ionic.Zlib.CompressionLevel.Level9; break; } using (Ionic.Zlib.DeflateStream ds = new Ionic.Zlib.DeflateStream(cse, Ionic.Zlib.CompressionMode.Compress, flv)) { int len = 0; foreach (string path in _FileList) { // Only file is encrypted if (File.Exists(path) == true) { buffer = new byte[BUFFER_SIZE]; using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) { len = 0; while ((len = fs.Read(buffer, 0, BUFFER_SIZE)) > 0) { ds.Write(buffer, 0, len); _TotalSize += len; string MessageText = ""; if (_TotalNumberOfFiles > 1) { MessageText = path + " ( " + _NumberOfFiles.ToString() + " / " + _TotalNumberOfFiles.ToString() + " files )"; } else { MessageText = path; } MessageList = new ArrayList(); MessageList.Add(ENCRYPTING); MessageList.Add(MessageText); // プログレスバーの更新間隔を100msに調整 if (swProgress.ElapsedMilliseconds > 100) { percent = ((float)_TotalSize / _TotalFileSize); worker.ReportProgress((int)(percent * 10000), MessageList); swProgress.Restart(); } if (worker.CancellationPending == true) { fs.Dispose(); e.Cancel = true; return(false); } } } } // end if (File.Exists(path) == true); } // end foreach (string path in _FileList); /* * for (int i = 0; i < 10; i++) * { * Random r = new Random(); * byteArray = new byte[BUFFER_SIZE]; * r.NextBytes(byteArray); * cse.Write(buffer, 0, BUFFER_SIZE); * } */ } // end using ( Ionic.Zlib.DeflateStream ds); } // end using (CryptoStream cse); } // end using (Rijndael aes = new RijndaelManaged()); } // end using (FileStream outfs = new FileStream(_AtcFilePath, FileMode.Create, FileAccess.Write)); // Set the timestamp of encryption file to original files or directories if (_fKeepTimeStamp == true) { File.SetCreationTime(_AtcFilePath, dtCreate); File.SetLastWriteTime(_AtcFilePath, dtUpdate); File.SetLastAccessTime(_AtcFilePath, dtAccess); } else { dtUpdate = DateTime.Now; File.SetLastWriteTime(_AtcFilePath, dtUpdate); } //Encryption succeed. _ReturnCode = ENCRYPT_SUCCEEDED; return(true); } catch (UnauthorizedAccessException) { //オペレーティング システムが I/O エラーまたは特定の種類のセキュリティエラーのためにアクセスを拒否する場合、スローされる例外 //The exception that is thrown when the operating system denies access //because of an I/O error or a specific type of security error. _ReturnCode = OS_DENIES_ACCESS; _ErrorFilePath = _AtcFilePath; return(false); } catch (DirectoryNotFoundException ex) { //ファイルまたはディレクトリの一部が見つからない場合にスローされる例外 //The exception that is thrown when part of a file or directory cannot be found _ReturnCode = DIRECTORY_NOT_FOUND; _ErrorMessage = ex.Message; return(false); } catch (DriveNotFoundException ex) { //使用できないドライブまたは共有にアクセスしようとするとスローされる例外 //The exception that is thrown when trying to access a drive or share that is not available _ReturnCode = DRIVE_NOT_FOUND; _ErrorMessage = ex.Message; return(false); } catch (FileLoadException ex) { //マネージド アセンブリが見つかったが、読み込むことができない場合にスローされる例外 //The exception that is thrown when a managed assembly is found but cannot be loaded _ReturnCode = FILE_NOT_LOADED; _ErrorFilePath = ex.FileName; return(false); } catch (FileNotFoundException ex) { //ディスク上に存在しないファイルにアクセスしようとして失敗したときにスローされる例外 //The exception that is thrown when an attempt to access a file that does not exist on disk fails _ReturnCode = FILE_NOT_FOUND; _ErrorFilePath = ex.FileName; return(false); } catch (PathTooLongException) { //パス名または完全修飾ファイル名がシステム定義の最大長を超えている場合にスローされる例外 //The exception that is thrown when a path or fully qualified file name is longer than the system-defined maximum length _ReturnCode = PATH_TOO_LONG; return(false); } catch (IOException ex) { //I/Oエラーが発生したときにスローされる例外。現在の例外を説明するメッセージを取得します。 //The exception that is thrown when an I/O error occurs. Gets a message that describes the current exception. _ReturnCode = IO_EXCEPTION; _ErrorMessage = ex.Message; return(false); } catch (Exception ex) { _ReturnCode = ERROR_UNEXPECTED; _ErrorMessage = ex.Message; return(false); } finally { #if (DEBUG) lg.StopWatchStop(); lg.Info("encryption finished!"); #endif swEncrypt.Stop(); swProgress.Stop(); // 計測時間 TimeSpan ts = swEncrypt.Elapsed; _EncryptionTimeString = Convert.ToString(ts.Hours) + "h" + Convert.ToString(ts.Minutes) + "m" + Convert.ToString(ts.Seconds) + "s" + Convert.ToString(ts.Milliseconds) + "ms"; } } // encrypt();
public static void AddToZip(BackgroundWorker worker, string zipfile, string FileToAdd, string AsFilename = "", bool showProgress = true, Ionic.Zlib.CompressionLevel complevel = Ionic.Zlib.CompressionLevel.Default) { if (!File.Exists(zipfile)) { throw new FileNotFoundException("Zipfile " + zipfile + " does not exist"); } bool exists = ExistsInZip(zipfile, AsFilename == "" ? FileToAdd : AsFilename); using (ZipFile zip = new ZipFile(zipfile)) { Utility.SetZipTempFolder(zip); zip.CompressionLevel = complevel; if (exists) { zip.RemoveEntry(AsFilename == "" ? FileToAdd : AsFilename); } ZipEntry ze = zip.AddFile(FileToAdd, ""); if (!string.IsNullOrEmpty(AsFilename)) { ze.FileName = AsFilename; } if (showProgress) { zip.SaveProgress += (o, e) => { if (e.EventType == ZipProgressEventType.Saving_EntryBytesRead && e.CurrentEntry.FileName == (AsFilename == "" ? FileToAdd : AsFilename)) { worker.ReportProgress((int)((float)e.BytesTransferred / e.TotalBytesToTransfer * 100)); } } } ; zip.Save(); } } }
public static string[] CreateDotNetZipArchive(Tuple <string, string, string[]>[] files, string path, int?maxSegmentSizeBytes = null, Ionic.Zlib.CompressionLevel compressionLevel = Ionic.Zlib.CompressionLevel.BestCompression) { using (var zip = new Ionic.Zip.ZipFile { CompressionLevel = compressionLevel }) { var entities = files.SelectMany(x => x.Item3.Select(y => new { path = y, directoryPathInArchive = string.IsNullOrWhiteSpace(x.Item1) || !y.StartsWith(x.Item1, StringComparison.OrdinalIgnoreCase) ? x.Item2 ?? "" : Path.Combine(x.Item2 ?? "", Path.GetDirectoryName(y.Substring(x.Item1.Length).TrimStart('\\'))) })).ToArray(); foreach (var entity in entities) { zip.AddFile(entity.path, entity.directoryPathInArchive); } if (maxSegmentSizeBytes.HasValue) { zip.MaxOutputSegmentSize = maxSegmentSizeBytes.Value; } zip.Save(path); return(Enumerable.Range(0, maxSegmentSizeBytes.HasValue ? zip.NumberOfSegmentsForMostRecentSave : 1) .Select(x => x == 0 ? path : Path.Combine(Path.GetDirectoryName(path), Path.GetFileNameWithoutExtension(path) + ".z" + (x < 10 ? "0" : "") + x)).ToArray()); } }
protected IonicCompression(CompressionOptions options) : base(options) { CompressionLevel = MapCompressionLevel(Options.CompressionLevel); }
public static byte[] EncryptData(ref byte[] data, byte[] salt, RijndaelManaged aes, Ionic.Zlib.CompressionLevel level) { using (ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV)) using (MemoryStream outms = new MemoryStream()) using (CryptoStream cse = new CryptoStream(outms, encryptor, CryptoStreamMode.Write)) { // Write salt and IV data. outms.Write(salt, 0, salt.Length); outms.Write(aes.IV, 0, aes.IV.Length); using (DeflateStream ds = new DeflateStream(cse, CompressionMode.Compress, false)) //using (Ionic.Zlib.DeflateStream ds = new Ionic.Zlib.DeflateStream(cse, Ionic.Zlib.CompressionMode.Compress, level)) { ds.Write(data, 0, data.Length); } return(outms.ToArray()); } }
public static bool ZipPack(string[] pFiles, string pDestinationFileName, string pPassword, EncryptionAlgorithm pEncryptionAlgorithm, CompressionMethod pCompressionMethod, Ionic.Zlib.CompressionLevel pCompressionLevel) { bool debug = false; bool result = false; try { using (ZipFile zip = new ZipFile()) { //Set zip properties except compression ones: Must be here if (pPassword != string.Empty) { zip.Password = pPassword; zip.Encryption = pEncryptionAlgorithm; } //Add Files for (int i = 0; i < pFiles.Length; i++) { if (File.Exists(pFiles[i])) { if (debug) { _log.Debug(string.Format("Add File:[{0}] to Zip:[{1}]", pFiles[i], pDestinationFileName)); } zip.AddFile(pFiles[i], System.IO.Path.GetDirectoryName(pFiles[i])); } else { if (debug) { _log.Debug(string.Format("Error Adding File:[{0}] to Zip:[{1}]. Cant Find the File", pFiles[i], pDestinationFileName)); } } } //Set compression just before Save() zip.CompressionMethod = pCompressionMethod; zip.CompressionLevel = pCompressionLevel; zip.Save(pDestinationFileName); result = true; } } catch (Exception ex) { _log.Error(ex.Message, ex); result = false; } return(result); }