function TEncodedStream.Write(const Buffer; Count: Longint): Longint; var pBuf, pEnc: PChar; I, EncVal: Integer; begin // allocate memory for the encoded buffer GetMem (pEnc, Count); try // use the buffer as an array of characters pBuf := PChar (@Buffer); // for every character of the buffer for I := 0 to Count - 1 do begin // encode the value and store it EncVal := ( Ord (pBuf[I]) + Ord(Key) ) mod 256; pEnc [I] := Chr (EncVal); end; // write the encoded buffer to the file Result := inheritedWrite (pEnc^, Count); finally FreeMem (pEnc, Count); end; end;
function TEncodedStream.Read(var Buffer; Count: Longint): Longint; var pBuf, pEnc: PChar; I, CountRead, EncVal: Integer; begin // allocate memory for the encoded buffer GetMem (pEnc, Count); try // read the encoded buffer from the file CountRead := inheritedRead (pEnc^, Count); // use the output buffer as a string pBuf := PChar (@Buffer); // for every character actually read for I := 0 to CountRead - 1 do begin // decode the value and store it EncVal := ( Ord (pEnc[I]) - Ord(Key) ) mod 256; pBuf [I] := Chr (EncVal); end; finally FreeMem (pEnc, Count); end; // return the number of characters read Result := CountRead; end;
procedure TFormEncode.BtnSaveEncodedClick(Sender: TObject); var EncStr: TEncodedStream; begin if SaveDialog1.Execute then begin EncStr := TEncodedStream.Create( SaveDialog1.Filename, fmCreate); try Memo1.Lines.SaveToStream (EncStr); finally EncStr.Free; end; end; end;
procedure TFormEncode.BtnLoadEncodedClick(Sender: TObject); var EncStr: TEncodedStream; begin if OpenDialog1.Execute then begin EncStr := TEncodedStream.Create( OpenDialog1.FileName, fmOpenRead); try Memo2.Lines.LoadFromStream (EncStr); finally EncStr.Free; end; end; end;
procedure TFormEncode.BtnLoadPlainClick(Sender: TObject); begin if OpenDialog1.Execute then Memo1.Lines.LoadFromFile ( OpenDialog1.FileName); end;