Сообщение от
Sokolik
procedure TForm1.ReadParams;
Var IniFile: TIniFile;
begin
IniFile:=TIniFile.Create('abc.ini');
xppanel1.Caption:=IniFile.ReadString('FORM1','Pane l',xppanel1.Caption);
IniFile.Free;
end;
procedure TForm1.WriteParams;
Var IniFile: TIniFile;
begin
IniFile:=TIniFile.Create('abc.ini');
IniFile.WriteString('FORM1','Panel',xppanel1.Capti on);
IniFile.Free;
end;
Как сделать, чтобы в abc.ini текст хранился в шифрованном, а не в открытом виде? Метод шифрования можно самый простой. Желательно показать примерчик. Заранее спасибо всем кто ответит.
Вам изначально необходимо выбрать способ шифрования. В общем случае чтение и запись будут реализованы так:
Код:
procedure TForm1.WriteParams;
Var
IniFile: TIniFile;
OpenText, CloseText: string;
begin
... выполнение неободимых действий
// в OpenText хранится текст для записи
// Encrypt - функция шифрования, которой передаются следующие параметры: текст и ключ для шифрования
CloseText := EnCrypt(OpenText, Key);
IniFile:=TIniFile.Create('abc.ini');
IniFile.WriteString('Section','PName', CloseText);
IniFile.Free;
end;
procedure TForm1.ReadParams;
Var
IniFile: TIniFile;
OpenText, CloseText: string;
begin
// Decrypt - функция расшифрования, которой передаются следующие параметры: текст и ключ для шифрования
IniFile:=TIniFile.Create('abc.ini');
CloseText := IniFile.ReadString('Section','PName', '');
IniFile.Free;
OpenText := Decrypt(CloseText, key);
end;
Если нужен простейший пример шифрования, то вот класс описывающий шифрование Виженера:
Код:
unit VigenereCrypt;
interface
uses Classes;
type
TVigenereCrypt = class
Alphabet: string; // алфавит
Mask: TStrings; // маска шифрования
TabulaRecta: TStrings;
constructor Create;
procedure CreateMask;
procedure Encrypt;
procedure Decrypt;
end;
implementation
constructor TVigenereCrypt.Create;
var
i, j: byte;
tmp: string;
tmpint: byte;
begin
Alphabet := 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя0123456789$!.,?;*(){}+=:/[]@\^"';
// создадим строковые списки
InputText := TStringList.Create;
OutputText := TStringList.Create;
Mask := TStringList.Create;
TabulaRecta := TStringList.Create;
for i := 0 to 63 do
begin
tmp := Alphabet;
for j := 1 to 64 do
begin
tmpint := (j+i) mod 64;
if (tmpint = 0) then
tmp[j] := Alphabet[64]
else
tmp[j] := Alphabet[tmpint];
end;
TabulaRecta.Append(tmp);
end;
end;
procedure TVigenereCrypt.CreateMask;
var
// длина ключа и текущий индекс символа в ключе
KeyLength: integer;
index: integer;
// счетчики циклов
i, j: integer;
// временные переменные
tmp: string;
begin
KeyLength := Length(key);
index := 1;
for i := 0 to InputText.Count -1 do
begin
SetLength(tmp, length(InputText[i]));
for j := 1 to length(InputText[i]) do
begin
tmp[j] := key[index];
inc(index);
if (index = KeyLength +1) then
index := 1;
end;
Mask.Append(tmp);
end;
end;
procedure TVigenereCrypt.Encrypt;
var
i,j : integer;
tmp : string;
index, tmpint: integer;
begin
for i := 0 to InputText.Count - 1 do
begin
// установим длину временной строки
SetLength(tmp,Length(InputText[i]));
// посимвольно обрабатываем строку
for j := 1 to Length(InputText[i]) do
begin
tmpint := POS(InputText[i][j], Alphabet);
// если символ не из алфавита, то пропустим его
if (tmpint = 0) then
tmp[j] := InputText[i][j]
// иначе обрабатываем
else
begin
index := POS(Mask[i][j], Alphabet)-1;
tmp[j] := TabulaRecta[index][tmpint];
end; // else
end; // for j
// добавим строку к обработанному тексту
OutputText.Append(tmp);
end; // for i
end;
procedure TVigenereCrypt.Decrypt;
var
i,j : integer;
tmp : string;
index, tmpint: integer;
begin
for i := 0 to InputText.Count - 1 do
begin
// установим длину временной строки
SetLength(tmp,Length(InputText[i]));
// посимвольно обрабатываем строку
for j := 1 to Length(InputText[i]) do
begin
index := POS(Mask[i][j], Alphabet)-1;
// если символ не из алфавита, то пропустим его
if (POS(InputText[i][j], Alphabet) = 0)
then tmp[j] := InputText[i][j]
// иначе обрабатываем его
else
begin
tmpint := POS(InputText[i][j], TabulaRecta[index]);
tmp[j] := Alphabet[tmpint];
end; // else
end; // for j
// добавим строку к обработанному тексту
OutputText.Append(tmp);
end; // for i
end;
end.
При использовании процедуры Encrypt этого класса будут зашифрованы все строчные символы кирилицы, цифры и некоторые символы. Всегда можешь изменить алфавит и немного доработать класс.
Использовать тогда шифрование нужно так:
Код:
procedure TForm1.WriteParams;
Var
IniFile: TIniFile;
CloseText: string;
Crypt: TVigenereCrypt;
begin
Crypt:= TVigenereCrypt.Create;
Crypt.key := 'ялюблюантичат';
Crypt.InputText.Clear;
Crypt.InputText.Append(xppanel1.Caption);
Crypt.CreateMask;
Crypt.Encrypt;
CloseText := Crypt.OutputText[0];
IniFile:=TIniFile.Create('abc.ini');
IniFile.WriteString('FORM1','Panel', CloseText);
IniFile.Free;
end;
procedure TForm1.ReadParams;
Var
IniFile: TIniFile;
tmpstr: string;
Crypt: TVigenereCrypt;
begin
Crypt:= TVigenereCrypt.Create;
Crypt.key := 'ялюблюантичат';
IniFile:=TIniFile.Create('abc.ini');
tmpstr:= IniFile.ReadString('FORM1','Panel', 'lalala');
IniFile.Free;
Crept.InputText.clear;
Crypt.InputText.Append(tmpstr);
Crypt.CreateMask;
Crypt.Decrypt;
xppanel1.Caption:= Crypt.OutputText[0];
end;
P.S. все кроме класса писал прямо здесь, мог где то ошибиться.