Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > IT форум > Помощь студентам
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 20.05.2014, 13:05   #1
Killan
Новичок
Джуниор
 
Регистрация: 20.05.2014
Сообщений: 2
По умолчанию Работа с модулями в Дельфи

Здравствуйте!
Подскажите пожалуйста, как вынести в отдельный модуль алгоритм шифрования и подключить его к программе. Я думаю, что надо вынести procedure AesInit и function AesGetCryptoByte, но реализация у меня не получилась
Код:
unit MainUnit;
interface
uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Buttons, shellapi;
type
  TForm1 = class(TForm)
    Edit1: TEdit;
    Label1: TLabel;
    Label2: TLabel;
    Memo1: TMemo;
    OD: TOpenDialog;
    Button1: TButton;
    odkey: TOpenDialog;
    Button2: TButton;
    Button3: TButton;
    Button4: TButton;
    Button5: TButton;
    sdkey: TSaveDialog;
    sd: TSaveDialog;
    SpeedButton1: TSpeedButton;
    Button6: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);
    procedure Button4Click(Sender: TObject);
    procedure Button5Click(Sender: TObject);
    procedure Button6Click(Sender: TObject);
    procedure SpeedButton1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;
var
  Form1: TForm1;
  aes:array[0..255] of byte;
  aesi, aesj: byte;
implementation
{$R *.dfm}
function gep:string;
var s:string;
begin
s:=ExtractFilePath(paramstr(0));
if s[length(s)]<>'\' then s:=s+'\';
Result:=s;
end;
function RandomKey(PWLen: integer): string;
const StrTable: string =
  '!#$%&/()=?@<>|{[]}\*~+#;:.-_' +
    'ABCDEFGHIJKLMabcdefghijklm' +
    '0123456789' +
    'ДЦЬдцьЯ' +
    'NOPQRSTUVWXYZnopqrstuvwxyz';
var
  N, K, X, Y: integer;
begin
  if (PWlen > Length(StrTable)) then
    K := Length(StrTable)-1
  else
    K := PWLen;
  SetLength(result, K);
  Y := Length(StrTable);
  N := 0;
  while N < K do
  begin
    X := Random(Y) + 1;
    if (pos(StrTable[X], result) = 0) then
    begin
      inc(N);
      Result[N] := StrTable[X];
    end;
  end;
end;
procedure AesInit(key:shortstring);
var
  k: array[0..255] of byte;
  i, j, t : byte;
begin
aesi:=0;
aesj:=0;
for i:=0 to 255 do aes[i]:=i;
j:=0;
t:=length(key);
 for i:=0 to 255 do begin
  inc(j);
  k[i]:=Byte(key[j]);
  if j=t then j:=0;
 end;
j:=0;
 for i:=0 to 255 do begin
  j:=(j+k[i]+aes[i]) mod 256;
  t:=aes[i];
  aes[i]:=aes[j];
  aes[j]:=t;
 end;
end;
function AesGetCryptoByte(ch:byte):byte;
var t:byte;
begin
aesi:=(aesi+1) mod 256;
aesj:=(aesj+aes[aesi]) mod 256;
t:=aes[aesi];
aes[aesi]:=aes[aesj];
aes[aesj]:=t;
t:=(aes[aesi]+aes[aesj]) mod 256;
AesGetCryptoByte:=aes[t] xor ch;
end;
procedure TForm1.Button1Click(Sender: TObject);
var sl:TstringList;
 s:string;
begin
randomize;
edit1.Text:=randomkey(random(15)+5);
sl:=TStringList.Create;
sl.Text:=edit1.Text;
if sdkey.Execute then
 sl.SaveToFile(sdkey.FileName+'.aes') else begin
  s:=gep+'MyKey.aes';
  sl.SaveToFile(s);
  messagedlg('Файл сохранен в '+s,mtinformation,[mbok],0);
 end;
sl.Free;
end;
procedure TForm1.Button2Click(Sender: TObject);
var sl:TStringList;
begin
if not odkey.Execute then exit;
sl:=TStringList.Create;
sl.LoadFromFile(odkey.FileName);
edit1.Text:=sl.Strings[0];
sl.Free;
end;
procedure TForm1.Button3Click(Sender: TObject);
begin
od.Title:='Открыть';
if not od.Execute  then  exit;
memo1.Lines.LoadFromFile(od.FileName);
end;
procedure TForm1.Button4Click(Sender: TObject);
var InFile, OutFile :file of byte;
    t:byte;
    s, outfn:string;
begin
if (memo1.Text='')or(edit1.Text='') then  begin
 messagedlg('Отсутствует текст или ключ для шифрования.',mterror,[mbok],0);
 exit;
end else begin
   if not sd.Execute  then exit;
   if sd.FilterIndex=1 then outfn:=sd.FileName+'.txt' else outfn:=sd.FileName;
  // showmessage(inttostr(sd.FilterIndex));
   s:=gep+'temp.sss';
   memo1.Lines.SaveToFile(s);
   AssignFile(InFile, s);
   Reset(InFile);
   AssignFile(OutFile, outfn);
   Rewrite(OutFile);
   AesInit(Edit1.Text+'1');
   while not eof(InFile) do begin
    read(InFile, t); //читаем байт
    t:=AesGetCryptoByte(t);
    write(OutFile, t);
   end;
   CloseFile(InFile);
   CloseFile(OutFile);
   DeleteFile(s);
   messagedlg('Файл зашифрован!',mtinformation,[mbok],0);
end;
end;
Killan вне форума Ответить с цитированием
Старый 20.05.2014, 13:07   #2
Killan
Новичок
Джуниор
 
Регистрация: 20.05.2014
Сообщений: 2
По умолчанию

Код:
procedure TForm1.Button5Click(Sender: TObject);
var InFile, OutFile :file of byte;
    t:byte;
    s:string;
begin
 if edit1.Text='' then  begin
 messagedlg('Упс :( Отсутствует ключ для расшифровки.',mterror,[mbok],0);
 exit;
end else begin
   od.Title:='Выберите файл для расшифровки';
   if not od.Execute  then exit;
  // showmessage(inttostr(sd.FilterIndex));
   s:=gep+'temp.sss';
   AssignFile(InFile, od.FileName);
   Reset(InFile);
   AssignFile(OutFile, s);
   Rewrite(OutFile);
   AesInit(Edit1.Text+'1');
   while not eof(InFile) do begin
    read(InFile, t);
    t:=AesGetCryptoByte(t);
    write(OutFile, t);
   end;
   CloseFile(InFile);
   CloseFile(OutFile);
   DeleteFile(Od.FileName);
   Rename(OutFile, Od.FileName);
   messagedlg('Файл расшифрован!',mtinformation,[mbok],0);
end;
end;
procedure TForm1.Button6Click(Sender: TObject);
begin
shellexecute(0,0,pchar(gep+'help.html'),0,0,sw_show);
end;
procedure TForm1.SpeedButton1Click(Sender: TObject);
var sl:TstringList;
 s:string;
begin
if edit1.Text='' then  exit;
sl:=TStringList.Create;
sl.Text:=edit1.Text;
if sdkey.Execute then
 sl.SaveToFile(sdkey.FileName+'.aes') else begin
  s:=gep+'MyKey.aes';
  sl.SaveToFile(s);
  messagedlg('Файл сохранен в '+s,mtinformation,[mbok],0);
 end;
sl.Free;
end;
end.
Killan вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц

Опции темы Поиск в этой теме
Поиск в этой теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Проблема с модулями с модулями DesignIntf и DesignEditors. Где найти их dcu? DrAndriy Общие вопросы Delphi 13 22.12.2017 20:55
Работа с записями и модулями (pascal) L@ris@ Помощь студентам 0 23.05.2012 18:19
работа с модулями(паскаль) прошу ответить jamkca Помощь студентам 9 14.05.2012 10:58
Работа в Дельфи!!! L0102591 Помощь студентам 2 11.06.2010 04:34
работа с модулями denis_stell Паскаль, Turbo Pascal, PascalABC.NET 0 17.05.2010 18:57