Delphi implements encryption and decryption files

xiaoxiao2021-03-06  22

File encryption compression with Delphi

Date: January 27, 2005

Author: e Meng Yuan (wnhoo) Mail: wnhoo@163.com dream love romantic e Overview: In this document, encryption of data about individual files, data compression, to achieve self-extracting. Similarly, it is also possible to implement compression of multiple files or folders, as long as it is slightly modified. Keywords: encryption compression, Zlib, stream, resource file quotation: In daily, we must use Winzip, WinRAR's famous compression software, is that we need to encounter data encryption and data compression in our development software! In this paper, we will explore this technical problem. At the same time, thank you for the skills. When I face the problem, it is a skill that you have worked hard, always let me suddenly, the problem is solved. This article mainly uses the data encryption compression of Delph's powerful stream processing, and is used in actual software program development, writing my personal experience and development experience. 1. System Function 1), data compression uses two streams provided by Delphi (TcompressionStream and TDecompressionStream) to complete data compression and decompression. 2) Data encryption compression, through the application of "stream" in Delphi, the data is applied, mainly using the two derived class TFileStream, TMEMORYSTREAM of TSTREAM; in which data compression part uses 1) implementation method 3), double-click compressed file Auto-associative decompression by changing the implementation of the registry and the association of the program file, mainly using Tregistry; and, the API function ShchangeNotify is rendered immediately. 4), can generate self-extracting file self-extracting file implementation data compression 1) automatic decompression of data encryption compression 2); and, through the use of the use of the use of the resource file to implement the merge of the executable self-demired file and the data file, to complete the data Self-decompression implementation. 2, system implementation 2.1, working principle 2.2, key technologies "(1) ZLIB1) This event occurs during the process. Format: Procedure OnProgress (Sender: TObject); dynamic; 2), a compression type TCompressionStream: In addition to inheriting the OnProgress properties of the base class, the added attribute: CompressionRate, which is defined as follows: Property CompressionRate: Single read GetCompressionRate; by This property can be compressed.

Its important ways are defined as follows: Constructor TcompressionStream.create (COMPRESSILVEL: TCompressionLevel; DEST: TSTREAM); where: TcompressionLevel (Compression Type), which defines the following: 1), Clnone: No data compression; 2 ), CLFASTEST: Fast compression, sacrificial compression efficiency; 3), CLDEFAULT: normal compression; 4), CLMAX: Maximize compression, sacrificial speed; DEST: Destination flow, used to store compressed data. Function TcompressionStream.write (CONST BUFFER): Longint; where: buffer: Data that needs to be compressed; Count: The number of bytes of data required; the function returns the number of bytes written to write. Note: The data of the compressed class TcompressionStream can only be written. If you try to read data from it, an "error" exception will occur. The data that needs to be compressed is compressed in the process of writing, and is compressed during the write process and saves the onprocess event in the internal memory stream provided by the constructor. 3), decompression class TDECompressionStream: Contrary to compressed class TcompressionStream, it is only readable, if you try to write data to it, a "error" exception will occur. Its important methods are defined as follows: Constructor Create (Source: TSTREAM); where: source is a stream that holds compressed data; Function Read (VAR Buffer; Count: longint): longint; data read function, buffer : Deposit data buffer; count: The size of the buffer; the function returns the number of bytes read. Data is decompressed and triggered an onprocess event during the read. (2) Flow in Delphi, the base class of all current objects is a TSTREAM class, which defines the common attributes and methods of all streams. The properties defined in the TSTream class are as follows: 1), Size: This property is in the data size in bytes. 2) Position: This property controls the location of the pointer in the stream. The virtual method defined in TSTream has four: 1), read: This method implements the data from the stream, the return value is the number of bytes actually read, which can be less than or equal to the specified value. 2), WRITE: This method implements the data write stream, the return value is the number of bytes in the actual write stream. 3), seek: This method implements the movement of the pointer in the stream, and the return value is the position of the moving pointer.

The function is: function seek (offset: longint; origint: word): line; virtual; abstract; parameter OFFSET is the number of offset bytes, the parameter origint points out the actual meaning of the OFFSET, which may be as follows: SOFROMBEGINNING: OFFSET is The pointer starts position. At this time, the OFFSET must be greater than or equal to zero. SOFROMCURRENT: OFFSET is the relative position of the movement pointer and the current pointer. SofroMend: OFFSET is the position of the end of the pointer distance data. At this time, OFFSET must be less than or equal to zero. 4), setsize: This method implements the size of the data. In addition, several static methods are also defined in the TSTream class: 1), readbuffer: This method is to read data from the current location in the stream, which is the same as the above. Note: An EREADERROR exception is generated when the number of data bytes read is different from the number of bytes you need to read. 2), WriteBuffer: The role of this method is to write data to the stream in the current position, which is the same as the WRITE above. Note: EWRITEERROR exception will be generated when the number of data bytes written is different from the number of bytes that needs to be written. 3), CopyFrom: This method is to copy data flow from other streams. The function is: function CopyFrom (Source: TSTREAM; Count: longint): longint; parameter source is the number of data bytes that provide data. When Count is greater than 0, CopyFrom is copied from the current location of the Source parameter. When count is equal to 0, the position property of the Source parameter is 0, then copy all the data of the Source; TSTREAM FAQ: TFileStream (Access to Filing) TStringStream (String Type Data in Memory) TMEMORYSTREAM (for work-proof memory area data processing) TBLOBSTREAM (Data Processing of the BLOB Type Field) TwinsocketStream (Socket Read / write processing) TOLESTREAM (COM interface Data Processing) TRESOURCESTREAM (resource file flow) is the most commonly used TFileStream class. Use the TFileStream class to access files, first create an instance. The declaration is as follows: constructor create (const filename: string; modename) The file name (including the path) Mode is open file, which includes the file's open mode and sharing mode, which may take the value and significance as follows: Open mode: fmcreate: Create a file with the specified file name, if the file already exists, open it. FmopenRead: Open the specified file in a read-only mode: Open the specified file with only Write mode: Open the specified file sharing mode with a write mode: FMShareCompat: Share mode is compatible with FMShareExClusive: Do not allow other programs to open this file in any way FMSharednywrite: Do not allow other programs to open this file fmsharednyreread: Do not allow other programs to open this file in reading, FMSharednynnenone: other programs can open this file in any way (3) Resource file 1), create a resource file first Create a .rc plain text file.

Format: Resource Identifier Keyword Resource File Name Resource Identifier: Special Number When Calling Resources Calls; Keywords: Identify Resource File Types; Wave: Resource Files are sound files; RCData: JPEG files; avi: avi animation; icon : Icon file; Bitmap: Bitmap: Bitmap file; Cursor: Cursor file; EXEFILE: EXE file resource file name: File of resource files stored on disk full name, for example: Myzjy Exefile Zjy.exe2, compile resource file installation in Delphi installation Under the catalog / bin, use the brcc32.exe to compile the resource file .rc. Of course, the BRCC32 can be copied separately to the program document directory. For example: brcc32 wnhoo_reg.rc3), resource file reference ... importation {$ r * .dfm} {$ r wnhoo_reg.res} ... 4), call resource files (1) Access to bitmaps in the resource file. Picture.bitmap.handle: = loadingBitmap (Hinstance, 'resource identifier'); Note: If the bitmap is not loaded, the program is still executed, but the image will no longer display the picture. You can determine whether the load is successful according to the return value of the loadbitmap function. If the load success return value is non-0, if the load failed return value is 0. Another method of accessing display bitmaps is as follows IMAGE.PICTURE.BITMAP.LOADFROMROMROMRESOURE.BITMAP.LOADFROMROMROMRESOURCENAME (Hinstance, 'Resource Identifier'); (2) Acquisition of Cursor Screen.cursors [] is a cursor array, using cursor files We can add custom cursors to this property. Because the default cursor is 0 in array, the index value is 0, so it is best to set the custom cursor index to 1 unless you want to replace the default cursor. Screen.cursors [1]: = loadCursor (Hinstance, 'Resource Identifier'); Image.cursor: = 1; (3) Access the icon in the resource file to put the icon in the resource file, you can realize the dynamic change application icon. Application.icon.Handle: = LoadCon (Hinstance, 'Resource Identifier'); (4) Access Avianimate.ResName: = 'myavi' in the resource file; // Resource Identifier symbol Animate.Active: = true; (5 The JPEG in the access resource file adds the JPEG unit into the USES unit.

varFjpg: TJpegImage; FStream: TResourceStream; beginFjpg: = TJpegImage.Create; // TresourceStream use FStream: = TResourceStream.Create (Hinstance, 'resource identifier', resource type); FJpg.LoadFromStream (FStream); Image.Picture.Bitmap .Ssign (fjpg); (6) Accessing WAVE in the resource file Add MMSystem to the USES unit Plays (Pchar ('MyWav'), Hinstance, SND_ASYNC or SND_MEMORY OR SND_RESOURCE); (4) INI file operation (1) ini The structure of the file:; This is the note section of the INI file [Node] Keyword = value ... INI file Allows multiple nodes, each node is allowed to have multiple keywords, "=" is the keyword The value (type has three: string, integer value, and Boolean value. The string is stored in the INI file without quotation marks, Boolean real value is indicated by 1, and the Boolean value is represented by 0). Note Taking a semicolon ";" starting. (2) Operation of INI file 1. Inifiles; 2, add a line in the VAR variable definition section: InIfile: Tinifile; then, you can create, open, read, read, write, etc. . 3, open the INI file: INIFILE: = Tinifile.create ('tmp.ini'); 4, read the value of the keyword: A: = INIFILE.ReadString ('Node', 'Keyword', default); // string type B: = INIFILE.Readinteger ('Node', 'Keyword', default); // Integer type C: = INIFILE.ReadBool ('Node', 'Keyword', default); // boolean type where [Default] is the default value returned when the INI file does not exist. 5, write INI file: inIfile.writestring ('Node', 'Keyword', variable or string value); Inifile.WriteInteger ('Node', 'Keyword', variable or integer value); inIfile.writeBool ('Node', 'Keyword', Variable or True or False); The above statement will automatically create the INI file when the node of this INI file does not exist. 6, delete keyword: INIFILE.DELETEKEY ('Node', 'Keyword'); // Keyword Delete InIfile.ReseSection ('Node'); // Node Delete 7, Node Operation: InIfile.Readsection ('Node' , Tstrings variables); // can read all keyword names in the specified section to a string list variable; inIfile.Readsections (TSTRINGS variable); // can read all the subnads in the INI file to a character The string list variable. InIfile.ReadsectionValues ​​('Node', TStrings Variable); // You can read all rows (including keywords, =, values) in the INI file to a string list variable.

8, the release: inifile.distory; or inifile.free; (v) the associated file usesregistry, shlobj; // achieve association registration procedure Tmyzip.regzzz; varreg: TRegistry; begin reg: = TRegistry.Create; reg.RootKey: = HKEY_CLASSES_ROOT Reg.openkey ('. Zzz', true); reg.writestring ('', 'myzip'); reg.closekey; reg.openkey ('myzip / shell / open / command', true); // Open the .zzz file's executable reg.writeString ('', '"" "% 1"); reg.closekey; reg.openkey (' myzip / defaulticon ', true); / / Take the icon of the current executable program as a .zzz file icon reg.writestring ('', '' application.exename ', 0'); reg.free; // Immediately refresh ShchanGenotify (shcne_assocchanged, shcnf_idlist, nil, nil ); END; 2.3, encrypting compression implementation 1, generating INI temporary encryption files for encrypted INI temporary file format: [file1] // node, use file1 in software to implement multi-file encryption filename = compression File Name Password = Decompression Password FileSize = File size FileDate = Create Date IsJM = Decompression If you need a password If you are a multi-file, folder information storage, you can have a total node. This article is only encrypted with a single file, so as long as the above format is. 2, the data file with the INI file used for encryption, this can be implemented in the form of file streams. After encryption, file structure. Figure: Figure (1) Figure (2) The above two forms can be employed according to actual use. This paper uses the structure of Figure (1). 3. For encrypted data, the ZLIB technology implements compression storage, generating files in new compressed forms. 2.4, implementation of file association See 2.2 (5) 2.5, self-extracting implementation 1. Establish a executable file 2 that is specifically used from decompression. Generate the file established in 1 to generate a resource file 3. Place the resource file into the program of this compression tool in this article. 4. Generate self-extracting files by mergen with the resource file with the compressed file. Self-decompressed file structure diagram: 5. Self-decompression implementation: By decomposing the encryption compressed data in its own file, the real data file is decompressed again and decompressed again. 2.6 System Program Design This is the core part of this software implementation, which tells all technical details of this software in detail.

// wnhoo_zzz.pasunit wnhoo_zzz; interfaceuses Windows, Forms, SysUtils, Classes, zlib, Registry, INIFILES, Dialogs, shlobj; type pass = string [20]; type Tmyzip = classprivate {private declarations here} protected {protected declarations here} public procedure regzzz; procedure ys_file (infileName, outfileName: string; password: pass; isjm: boolean; ysbz: integer); function jy_file (infileName: string; password: pass = ''): boolean; procedure zjywj (var filename: string) ; constructor Create; destructor Destroy; override; {public declarations here} published {published declarations here} end; implementationconstructor Tmyzip.Create; begininherited Create; initialization inherited portion end //; // ######### ######################################################################################### JM_FILE (Vfile: string; var target: tmemorystream; password: pass; isjm: boolean); {vfile: encrypted file Target: After encryption output target stream "" "password: password isjm: Whether encryption -------- -------------------------------------------------- --- Encrypted file size = original file Size [INI encrypted compressed information file] SIZE storage [INI encryption compressed information file] size data type size -------------------------------------------------- ------------- ----------------------------------} VARTMPSTREAM, INISTREAM: TFILESTREAM; FileSize: Integer; Inifile: TiniFile; FileName : string; begin // Open Require [Encrypted Compressed File] TmpStream: = TFileStream.create (VFile, FmopenRead or FMShareExClusive); TRY // Write [Original Flow] Target.Seek to [Provisional Encryption Compressed Flow] 0, SOFROMEND; TARGET.COPYFROM (TmpStream, 0); // Get the file path, generate [INI encryption compressed information file] filename: = extractfilepath (paramstr (0)) 'tmp.in _'; inIfile: = tinifile. Create (filename); inifile.WriteString ( 'file1', 'filename', ExtractFileName (vFile)); inifile.WriteString ( 'file1', 'password', password); inifile.WriteInteger ( 'file1', 'filesize', Target.size); InIfile.WriteDateTime ('file1', 'filedate', now ());

INIFILE.WRITEBOOL ('file1', 'isjm', isjm); inIfile.free; // Read [INI encryption compression information file flow] Inistream: = tfilestream.create (filename, fmopenread or fmsharexclusive); try // Continue [Temporary encryption compression file flow] Tissue [INI encryption compression information file] Inistream.position: = 0; target.seek (0, SofroMend); target.copyfrom (inStream, 0); // Calculate current [INI encryption compression information File] FileSize: = INISTREAM.SIZE; // Continue to join the [INI encryption compressed information file] to add [INI encryption compressed information file] TARGET.WRITEOF (FileSize); Finally Inistream.free; deletefile (Filename); end; finallytmpstream.free; end; end; // *************************************************************** **************************** / / stream compression Procedure Ys_Stream (Instream, Outstream: TSTREAM; YSBZ: Integer); {Instream: Stay Compressed encrypted file flow OUTSTREAM compressed output file stream YSBZ: Compression Standard} VAR YS: TcompressionStream; Begin // Flow pointer pointing head instream.position: = 0; // Compressed standard Case YSBZ of 1: ys: ys:: = TCompressionStream.Create (clFastest, OutStream); // rapid compression 3:; = TCompressionStream.Create (clnone, OutStream) // 2 without compressing ys: = TCompressionStream.Create (cldefault, OutStream); // standard compression 4: ys: = TcompressionStream.create (CLMAX, Outstream); // Maximum compression else ys: = tcompressionStream.create (CLFASTEST, OUTSTREAM); END; TRY / / Compressed Dream Ys.copyFrom (Instream, 0); Finally Ys.Free; end; end; // ****** *********************************************************** ********* // streaming procedure jy_stream (instream, outstream: tstract; {instream: raw shrink file outstream: unzipped backflow file} var jyl: tdecompressionStream; buf: array [1..512 ] Of byte; sjread: integer; begin instream.position: = 0; jyl: = tdecompressionStream.create (instream); try repeat // Reads actual size sjread: = jyl.read (buf, sizeof (buf)); if Sjread> 0 Then OutStream.write (buf, sjread); Until (sjread = 0); finally jyl.free; end; end;

// ******************************************************** ************* // Realize the association registration Procedure TMYZIP.REGZZZ; varreg: Tregistry; recomb: = tregistry.create; reg.rootkey: = hkey_classes_rootkey; reg.openkey ('. Zzz ', True);', ',' myzip '); reg.closekey; reg.openkey (' myzip / shell / open / command ', TRUE); // Used to open the .zzz file executable Reg.writeString (',' "' application.exename '" "% 1"); reg.closekey; reg.openkey ('myzip / default ", true); // Take the current executable icon The icon of the .zzz file reg.writeString ('', ' application.exename ', 0 '); reg.free; // Immediately refresh ShchanGenotify (shcne_assocchanged, shcnf_idlist, nil, nil); end; // Compressed file Procedure TMYZIP.YS_FILE (InfileName, Outfilename: String; Password: pass; isjm: boolean; ysbz: integer; {infilename: // Need to compress encrypted file OutfileName: // Compressed file password: // Decompressive password YSBZ: // Compression Standard} VarinStream: TMEMoryStream; // File Encryption Temporary Flow Outstream: TFileStream; // Compressed Output Files Begin // Create [File Encrypted Temfering] Instream: = TmemoryStream.create; // Document encryption JM_File (InfileName, Instream, Password, ISJM); // Create a compressed output file outstream: = TFileStream.create (OUTF Ilename, fmcreate; TRY / / [Temporary flow after file encryption] Compressed ys_stream (Instream, outstream, ysbz); Finally Outstream.free; instream.free; end; end; // Unzip file function TMYZIP.JY_FILE (InfileName: string; password: pass = ''): boolean; var inStream, inistream, filestream_ok: TFileStream; {instream: // unzip the file name inistream: // INI temporary file stream filestream_ok: // OK decompressed file} outStream: tmemorystream; // temporary memory flow inifile: TINIFILE; // temporary INI file FileSize: integer; SIZE resultvalue // password file: boolean; // return value begintry inStream: = TFileStream.create (inFIleName, fmOpenRead); try outStream: = tmemorystream .create;

Try jy_stream (instream, outstream); // Generate temporary INI file inistream: = tfilestream.create (extractFilePath) 'tmp.in_', fmcreate; try // point to the INTEGER type variable position of the storage decoding information Outstream.seek; // Read variable information Outstream.readbuffer (filesis, sizeof (filesize)); // Point to decoding information Outstream.seek (- (FileSize Sizeof (FileSize)) , SOFROMEND; // read the decoded information into the INISTREAM.COPYFROM (OutStream, FileSize); // Release INI file infinistream.free; // Read Ini file information inIfile: = tinifile.create (ExtractFilePath (Paramstr (0)) 'tmp.in_'); ResultValue: = INIFILE.ReadBool ('file1', 'isjm', false); if ResultValue the beginning, ketstring ('file1', 'password', '') = Trim (Password) Then ResultValue: = true else resultValue: = false; end else resultvalue: = true; if Resultvalue the beg in filestream_ok: = TFileStream.create (ExtractFilePath (paramstr (1)) inifile.ReadString ( 'file1', 'filename', 'wnhoo.zzz'), fmCreate); try OutStream.Position: = 0; filestream_ok.CopyFrom ( OutStream, inifile.ReadInteger ( 'file1', 'filesize', 0)); finally filestream_ok.Free; end; end; inifile.Free; finally // delete temporary INI files deletefile (ExtractFilePath (paramstr (0)) 'tmp .in_ '); end; // finally outstream.free; end; finally instream.free; end;

转载请注明原文地址:https://www.9cbs.com/read-39716.html

New Post(0)