How can I get content of an exe file and convert it into Base64 encoding ?
Edit
I use D2010 and I want to know how is it possible exactly ?
open an exe file
convert its content into base64
In Delphi 2009/2010/XE there is unit EncdDecd.pas (Soap.EncdDecd.pas for Delphi XE2) containing the functions EncodeBase64 and DecodeBase64. You can load the exe file into a memorystream and then call EncodeBase64.
function EncodeFile(const FileName: string): AnsiString;
var
stream: TMemoryStream;
begin
stream := TMemoryStream.Create;
try
stream.LoadFromFile(Filename);
result := EncodeBase64(stream.Memory, stream.Size);
finally
stream.Free;
end;
end;
In ancient Delphi versions, you can use synapse (link here)
Just put synacode.pas in your uses e call EncodeBase64/EncodeBase64.
Cheers
As also mentioned in the comments, since Delphi XE8 you can use the System.NetEncoding.TNetEncoding.Base64 class property.
It also returns a string instead of an AnsiString:
function TryEncodeFile(const AFileName: string; out ABase64string: string): Boolean;
var
MemStream: TMemoryStream;
begin
MemStream := TMemoryStream.Create;
try
MemStream.LoadFromFile(AFileName);
ABase64string :=
TNetEncoding.Base64.EncodeBytesToString(MemStream.Memory, MemStream.Size);
Result := True;
finally
MemStream.Free;
end;
end;
Related
I've searched many forums and blogs before posting the question.
I've found samples in python and VB which are using ZLib.
but I can't get it to work in Delphi.
I have the stream from a pdf that is encoded with FlateDecode.
Here is the stream saved as a simple file named "compressed_stream.pdf" (in fact it's not pdf - it's only the stream, but I just left the .pdf file extension)
https://files.fm/u/epka2hxz
Here is my code:
Execution goes to System.Zlib.ZDecompressStream(streamIn, streamOut); and just sleeps... no errors, no crashes, nothing - just sleeps until I break the execution.
Any idea?
var
fs: TFileStream;
streamIn, streamOut: TMemoryStream;
begin
fs := TFileStream.Create(sDocumentFolder + 'compressed_stream.pdf', fmOpenRead);
streamIn := TMemoryStream.Create();
streamOut := TMemoryStream.Create();
streamIn.CopyFrom(fs, 0);
streamIn.Position := 0;
System.Zlib.ZDecompressStream(streamIn, streamOut);
end;
Thanks to Dima I quickly found a sample for TZDecomoressionStream:
https://forum.lazarus.freepascal.org/index.php?topic=33009.0
function ZDecompressString(aText: string): string;
var
strInput,
strOutput: TStringStream;
Unzipper: TZDecompressionStream;
begin
Result:= '';
strInput:= TStringStream.Create(aText);
strOutput:= TStringStream.Create;
try
Unzipper:= TZDecompressionStream.Create(strInput);
try
strOutput.CopyFrom(Unzipper, Unzipper.Size);
finally
Unzipper.Free;
end;
Result:= strOutput.DataString;
finally
strInput.Free;
strOutput.Free;
end;
end;
okay, so I (VERY) recently started playing with lazaruz/free pascal, and I'm a little stuck with reading files with TMemoryStream and it's streaming kin.
I'm trying to write a simple base64 encoder, that can encode strings of text, or files (like images and WAVs) to then be used in html and javascript.
The following code compiles great but I get EReadError Illegal stream image when trying to load a file. I'll include the working string only procedure for reference:
procedure TForm1.TextStringChange(Sender: TObject);
begin
Memo1.Lines.Text := EncodeStringBase64(TextString.Text);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
Memo1.Lines.Text := '';
Form1.BorderIcons := [biSystemMenu,biMinimize];
end;
procedure TForm1.BitBtn1Click(Sender: TObject);
begin
if OpenDialog1.Execute then
begin
filename := OpenDialog1.Filename;
stream := TMemoryStream.Create;
try
StrStream := TStringStream.Create(s);
try
stream.LoadFromFile(filename);
stream.Seek(0, soFromBeginning);
ObjectBinaryToText(stream, StrStream);
StrStream.Seek(0, soFromBeginning);
Memo1.Lines.Text := EncodeStringBase64(StrStream.DataString);
finally
StrStream.Free;
end;
finally
stream.Free;
end;
end;
end;
Can anyone help me out?
You get the "illegal stream image" exception because the file you're loading probably isn't a binary DFM file. That's what ObjectBinaryToText is meant to process. It's not for arbitrary data. So get rid of that command.
You can skip the TMemoryStream, too. TStringStream already has a LoadFromFile method, so you can call it directly instead of involving another buffer.
StrStream.LoadFromFile(filename);
But a string isn't really the right data structure to store your file in prior to base64-encoding it. The input to base64 encoding is binary data; the output is text. Using a text data structure as an intermediate format means you may introduce errors into your data because of difficulties in encoding certain data as valid characters. The right interface for your encoding function is this:
function Base64Encode(Data: TStream): string;
You don't need to load the entire file into memory prior to encoding it. Just open the file with a TFileStream and pass it to your encoding function. Read a few bytes from it at a time with the stream's Read method, encode them as base64, and append them to the result string. (If you find that you need them, you can use an intermediate TStringBuilder for collecting the result, and you can add different buffering around the file reads. Don't worry about those right away, though; get your program working correctly first.)
Use it something like this:
procedure TForm1.BitBtn1Click(Sender: TObject);
var
filename: string;
stream: TStream;
begin
if OpenDialog1.Execute then begin
filename := OpenDialog1.Filename;
stream := TFileStream.Create(filename, fmOpenRead);
try
Memo1.Lines.Text := Base64Encode(stream);
finally
stream.Free;
end;
end;
end;
I never heard before about ObjectBinaryToText(), but looks like funky one. Also, what is EncodeStringBase64() function?
At first place, you shouldn't convert binary stream to text to encode it, instead you should directly B64 encode binary data. B64 algorithm is intended to work on array of bytes.
Since Delphi 6, there is EncdDecd.pas unit, which implements B64 encoding methods. I'm not sure if Lazarus/FPC have this, but if they do, your code to B64 encode file should look like this (add EncdDecd to uses list):
procedure TForm1.Button1Click(Sender: TObject);
var
instream : TFileStream;
outstream: TStringStream;
begin
if OpenDialog1.Execute then
begin
instream := TFileStream.Create(OpenDialog1.FileName, fmOpenRead or fmShareDenyNone);
try
outstream := TStringStream.Create;
try
EncodeStream(instream, outstream);
Memo1.Lines.Text := outstream.DataString;
finally
outstream.Free;
end;
finally
instream.Free;
end;
end;
end;
I am downloading an EXE file from internet using Indy (idHTTP), and I can use memorystream or filestream to save it to disk, but I really do not know if there is any difference between them (maybe in the result structure of the file?). I could't find yet an answer for this.
Where, here are 2 simple functions to simulate what I am doing:
Function DownloadMS(FUrl, Dest: String): Boolean;
var
Http: TIdHTTP;
Strm: TMemoryStream;
Begin
Result := False;
Http := TIdHTTP.Create;
Strm := TMemoryStream.Create;
With Http, Strm Do
Try
Try
Get(FUrl, Strm);
If (Size > 0) Then
Begin
Position := 0;
SaveToFile(Dest);
Result := True;
end;
Except
end;
Finally
Strm.Free;
Http.Free;
end;
end;
Function DownloadFS(FUrl, Dest: String): Boolean;
var
Http: TIdHTTP;
Strm: TFileStream;
Begin
Result := False;
Http := TIdHTTP.Create;
Strm := TFileStream.Create(Dest, fmCreate);
With Http, Strm Do
Try
Try
Get(FUrl, Strm);
Result := (Size > 0);
Except
end;
Finally
Strm.Free;
Http.Free;
end;
end;
What you experts think about using one or other type (memorystream or filestream)? Is there any difference in the structure of the EXE file when using one or other type? What type is recommended?
Thank you! Have a nice weekend!
There is no difference between TMemoryStream or TFileStream from the stream point of view.
They are both streams and hold a stream of bytes and are both derived from TStream.
You can implement your function generalized like this
function DownloadToStream( const AUrl : String; ADest : TStream ): Boolean;
var
LHttp: TIdHTTP;
begin
LHttp := TIdHTTP.Create;
try
LHttp.Get( AUrl, ADest );
Result := ADest.Size > 0;
finally
LHttp.Free;
end;
end;
and call it with a TFileStream
var
LStream : TStream;
begin
LStream := TFileStream.Create( 'MyFile.exe', fmCreate );
if DownloadToStream( '', LStream ) then
...
end;
or TMemoryStream or whatever stream instance you like
In many cases there will be no point in putting an intermediate memory stream in between the download and the file. All that will do is consume memory because you have to put the entire file in memory before you can put it to disk. Using a file stream directly avoids that issue.
The main situation where the file stream option has problems is if you want to be sure that you've downloaded the entire file successfully before saving to disk. For example, if you are overwriting a previous version of a file, you may want to download it, check a hash signature, and only then overwrite the original file. In that scenario you need to put the file to some temporary location before over-writing. You could use a memory stream, or you could use a file stream using a temporary file name.
Is there a way to get the RTF data from a richedit without using savetostream as in
strStream := TStringStream.Create('') ;
try
RichEdit.Lines.SaveToStream(strStream);
Text := strStream.DataString;
strStream.CleanupInstance;
finally
strStream.Free
Tim the only way to get the RTF data from an RichEdit control is using a Stream because the windows message (EM_STREAMOUT) wich retrieve the RTF Data require a EditStreamCallback structure, this is the way used by windows to transfer rtf data into or out of a richedit control.
So you can use your own sample code, or implement the call to the windows message EM_STREAMOUT.
function RichTextToStr(red : TRichEdit) : string;
var ss : TStringStream;
begin
ss := TStringStream.Create('');
try
red.Lines.SaveToStream(ss);
Result := ss.DataString;
finally
ss.Free;
end;
end;
procedure CopyRTF(redFrom,redTo : TRichEdit);
var s : TMemoryStream;
begin
s := TMemoryStream.Create;
try
redFrom.Lines.SaveToStream(s);
s.Position := 0;
redTo.Lines.LoadFromStream(s);
finally
s.Free;
end;
end;
I can attest deviation from the pattern results in frustration....
In this question is mentioned the wcrypt2.
What I need is simply calculate the MD5 of a file. It would be perfect if I could calculate it without having to save it because it is a downloaded file in stream format.
I would like to have the most straightforward way to do that.
Thanks!
Here is a working code for Indy 10:
function MD5File(const FileName: string): string;
var
IdMD5: TIdHashMessageDigest5;
FS: TFileStream;
begin
IdMD5 := TIdHashMessageDigest5.Create;
FS := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
try
Result := IdMD5.HashStreamAsHex(FS)
finally
FS.Free;
IdMD5.Free;
end;
end;
Regards,
OscaR1
Based on #dummzeuch answere I wrote this function:
function getMD5checksum(s: TStream): string;
var
md5: TIdHashMessageDigest5;
hash : T4x4LongWordRecord;
begin
md5 := TIdHashMessageDigest5.Create;
s.Seek(0,0);
hash := md5.HashValue(s);
result := IntToHex(Integer(hash[0]), 4) +
IntToHex(Integer(hash[1]), 4) +
IntToHex(Integer(hash[2]), 4) +
IntToHex(Integer(hash[3]), 4);
end;
Indy comes with functions for calculating several hashes, MD5 is one of them. Indy is included in all versions of Delphi since at least Delphi 2006 and available as a free download for older versions.
What about:
function GetFileMD5(const Stream: TStream): String; overload;
var MD5: TIdHashMessageDigest5;
begin
MD5 := TIdHashMessageDigest5.Create;
try
Result := MD5.HashStreamAsHex(Stream);
finally
MD5.Free;
end;
end;
function GetFileMD5(const Filename: String): String; overload;
var FileStream: TFileStream;
begin
FileStream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
try
Result := GetFileMD5(FileStream);
finally
FileStream.Free;
end;
end;
As you mentioned, the post you linked to talks about wcrypt2, which is a library of cryptographic routines, including MD5. The post you linked to also seems to indicate that it is available for Delphi 7 since the asker includes output labeled "Delphi 7." You have tagged this question delphi7, so I assume that's the version you're using, too. So what's stopping you from using wcrypt2?
The question links to a copy of wcrypt2.pas, and the copyright dates in that file appear to indicate that the unit was available by the time Delphi 7 was released. Check your installation; you might already have it. If not, then the unit also says that it was obtained via Project Jedi, so you could try looking there for the unit as well.
The answers to your referenced question include example Delphi code and the names of units that come with Delphi for doing MD5. They come with Delphi 2009, so you should check whether they're also available for your version.
Take a look at this implementation of MD5SUM in Delphi. It requires a string for input, but I imagine you can easily make it work with a stream.
MessageDigest_5 would work for this as well.
I use the following function in Delphi 7 with Indy 10.1.5
uses IdHashMessageDigest, idHash, Classes;
...
function cc_MD5File(const p_fileName : string) : string;
//returns MD5 has for a file
var
v_idmd5 : TIdHashMessageDigest5;
v_fs : TFileStream;
v_hash : T4x4LongWordRecord;
begin
v_idmd5 := TIdHashMessageDigest5.Create;
v_fs := TFileStream.Create(p_fileName, fmOpenRead OR fmShareDenyWrite) ;
try
v_hash := v_idmd5.HashValue(v_fs);
result := v_idmd5.AsHex(v_hash);
finally
v_fs.Free;
v_idmd5.Free;
end;
end;
If you use Overbyte http://www.overbyte.eu/frame_index.html just add unit and call function FileMD5 with name of file
uses OverbyteIcsMd5;
....
function GetMd5File:String;
begin
Result := FileMD5(FileName);
end;