Перейти к содержанию
Fire Monkey от А до Я
  • 0

Есть ли в FireMonkey какие-либо процедуры шифрования текста?


antarey

Вопрос

Подскажите, есть ли в обезьяне стандартные компоненты/процедуры для шифрования/дешифрации текста, применимо для вин/андроид платформ?

Если да - пример не помешал бы.

Спасибо

Ссылка на комментарий

Рекомендуемые сообщения

  • 0

XOR и NOT еще никто не отменял  :)

function StrEncrypt( s: string ): string;
var
  i: Integer;
  b: TBytes;
begin
   b := BytesOf( s );
   for i := 0 to Length( b )-1 do
      b[i] := not( b[i] xor 25 );
   Result := StringOf( b );
end;

function StrDecrypt( s: string ): string;
var
  i: Integer;
  b: TBytes;
begin
   b := BytesOf( s );
   for i := 0 to Length( b )-1 do
      b[i] := not( b[i] ) xor 25;
   Result := StringOf( b );
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  s: string;
begin
   s := 'crypt my';
   ShowMessage( s );
   s := StrEncrypt( s );
   ShowMessage( s );
   s := StrDecrypt( s );
   ShowMessage( s );
end;
Ссылка на комментарий
  • 0

Спасибо конечно, но вот как раз XOR и NOT использовать и не хочется - для начала довольно часто в зашифрованные символы попадают управляющие последовательности и при хранении пароля в инишке возникают проблемы с чтением, да и в плане роз шифровки ето самый неустойчивый алгоритм

Ссылка на комментарий
  • 0

Относительно управляющих символов - после шифрования обработай строку Base64. Относительно неустойчивости - ты прав, но FM тебе тут вряд ли поможет, изобретай свой велосипед или позаимствуй чужой.

Ссылка на комментарий
  • 0
  1. Видел когда то в Инди компонент для (де)шифрования текста. Сейчас не могу назвать какой именно.
  2. И вот еще посмотри:  https://code.google.com/p/delphidec/
Ссылка на комментарий
  • 0

Оставлю тут инфу, чтобы не забыть. Понадобилось тоже шифровать текст, сделал себе простенький юнит на основе https://github.com/MHumm/DelphiEncryptionCompendium

 

unit Encrypt_unit;

interface

uses DECCipherBase, DECFormatBase, DECCipherModes, System.SysUtils,
  System.TypInfo, Generics.Collections,
  DECBaseClass, DECFormat,
  DECCipherFormats, DECCiphers, DECUtil, DECCipherInterface, FMX.Dialogs;

const
  FILLER_TEXT = '01';
  INIT_VECTOR_TEXT = '127E22';
  KEY_TEXT = '123456ADE';
  CIPHER_FUNCTION = 'TCipher_1DES';
  CIPHER_MODE = 'cmCTSx';
  AuthenticationBitLength = 128;
  EditAuthenticatedData = '';
  EditExpectedAuthenthicationResult = '';
  EditCalculatedAuthenticationValue = '';
  FORMAT_TEXT = 'TFormat_Copy';

var
  EditFiller: string;
  EditInitVector: string;
  EditKey: string;

function EncryptText(EditPlainText: string): string;
function DecryptText(EditCipherText: string): string;

implementation

function GetSelectedCipherMode: TCipherMode;
var
  ModeStr: string;
begin
  ModeStr := CIPHER_MODE;
  if ModeStr.Contains('(') then
    ModeStr := ModeStr.Remove(ModeStr.IndexOf('(') - 1);
  result := TCipherMode(System.TypInfo.GetEnumValue(TypeInfo(TCipherMode), ModeStr));
end;

function GetCipherInstance: TDECCipherModes;
begin
  result := TDECCipher.ClassByName(CIPHER_FUNCTION).Create as TDECCipherModes;
  result.Mode := GetSelectedCipherMode;
end;

{function IsAuthenticatedCipher: Boolean;
var
  Cipher: TDECCipherModes;
begin
  Cipher := GetCipherInstance;
  try
    result := Cipher.IsAuthenticated;
  finally
    Cipher.Free;
  end;
end;

procedure UpdateAuthenticationStatus;
begin
  IsAuthenticatedCipher;
end;

procedure InitCipherAlgorithm;
var
  Context: TCipherContext;
begin
  Context := TDECCipher.ClassByName(CIPHER_FUNCTION).Context;
  UpdateAuthenticationStatus;
end;}

function GetInitializedCipherInstance: TDECCipherModes;
var
  FillerByte: UInt8;

begin
  EditFiller := FILLER_TEXT;
  EditInitVector := INIT_VECTOR_TEXT;
  EditKey := KEY_TEXT;
  if not EditFiller.IsEmpty then
  begin
    while length(EditFiller) < 2 do
      EditFiller := '0' + EditFiller;

    FillerByte := StrToInt('0x' + EditFiller)
  end
  else

    FillerByte := 0;

  if TFormat_HEXL.IsValid(RawByteString(EditInitVector.ToLower)) and TFormat_HEXL.IsValid(RawByteString(EditKey.ToLower)) then
  begin
    result := GetCipherInstance;
    result.Init(BytesOf(TFormat_HEXL.Decode(RawByteString(EditKey.ToLower))), BytesOf(TFormat_HEXL.Decode(RawByteString(EditInitVector.ToLower))), FillerByte);
  end
  else
    raise Exception.Create('No valid encryption key or init vector given!');
end;

procedure SetAuthenticationParams(Cipher: TDECCipherModes);
begin
  Assert(Assigned(Cipher));

  if Cipher.IsAuthenticated then
  begin
    Cipher.AuthenticationResultBitLength := AuthenticationBitLength;
    Cipher.DataToAuthenticate := TFormat_HEXL.Decode(BytesOf(RawByteString(EditAuthenticatedData)));
    Cipher.ExpectedAuthenticationResult := TFormat_HEXL.Decode(BytesOf(RawByteString(EditExpectedAuthenthicationResult)));
  end;
end;

function GetFormatSettings(var PlainTextFormatting, CipherTextFormatting: TDECFormatClass): Boolean;
begin
  PlainTextFormatting := TDECFormat.ClassByName(FORMAT_TEXT);
  CipherTextFormatting := TDECFormat.ClassByName(FORMAT_TEXT);
  result := true;
end;

function EncryptText(EditPlainText: string): string;
var
  Cipher: TDECCipherModes;
  InputFormatting: TDECFormatClass;
  OutputFormatting: TDECFormatClass;
  InputBuffer: TBytes;
  OutputBuffer: TBytes;
begin
  result := '';

  if not GetFormatSettings(InputFormatting, OutputFormatting) then
    exit;

  try
    Cipher := GetInitializedCipherInstance;

    try
      InputBuffer := System.SysUtils.BytesOf(EditPlainText);

      if InputFormatting.IsValid(InputBuffer) then
      begin
        // Set all authentication related properties
        SetAuthenticationParams(Cipher);

        try
          OutputBuffer := (Cipher as TDECFormattedCipher).EncodeBytes(InputFormatting.Decode(InputBuffer));
          (Cipher as TDECFormattedCipher).Done;
        except
          On e: Exception do
            ShowMessage('Encryption failure:' + sLineBreak + e.Message);
        end;

        result := string(DECUtil.BytesToRawString(OutputFormatting.Encode(OutputBuffer)));

      end
      else
        ShowMessage('Input has wrong format');
    finally
      Cipher.Free;
    end;
  except
    On e: Exception do
      ShowMessage('Encryption init failure: ' + e.Message);
  end;
end;

function DecryptText(EditCipherText: string): string;
var
  Cipher: TDECCipherModes;
  CipherTextFormatting: TDECFormatClass;
  PlainTextFormatting: TDECFormatClass;
  CipherTextBuffer: TBytes;
  PlainTextBuffer: TBytes;
  AuthenticationOK: Boolean;
begin
  result := '';
  if not GetFormatSettings(PlainTextFormatting, CipherTextFormatting) then
    exit;

  try
    Cipher := GetInitializedCipherInstance;

    try
      CipherTextBuffer := System.SysUtils.BytesOf(EditCipherText);

      if CipherTextFormatting.IsValid(CipherTextBuffer) then
      begin
        // Set all authentication related properties
        SetAuthenticationParams(Cipher);
        AuthenticationOK := false;

        try
          PlainTextBuffer := (Cipher as TDECFormattedCipher).DecodeBytes(CipherTextFormatting.Decode(CipherTextBuffer));
          // in case of an authenticated cipher mode like cmGCM the Done method
          // will raise an exceptino when the calculated authentication value does
          // not match the given expected one
          (Cipher as TDECFormattedCipher).Done;
          // If we managed to get to here, the calculated authentication value is
          // ok if we're in an authenticated mode and have entered an expected value.
          if (length(EditExpectedAuthenthicationResult) > 0) and (length(EditExpectedAuthenthicationResult) = length(EditCalculatedAuthenticationValue)) then
            AuthenticationOK := true;
        except
          On e: Exception do
            ShowMessage('Decryption failure:' + sLineBreak + e.Message);
        end;

        result := string(DECUtil.BytesToRawString(PlainTextFormatting.Encode(PlainTextBuffer)));
      end
      else
        ShowMessage('Input has wrong format');
    finally
      Cipher.Free;
    end;
  except
    On e: Exception do
      ShowMessage('Decryption init failure: ' + e.Message);
  end;
end;

end.

 

 

 

Изменено пользователем gonzales
Ссылка на комментарий
  • 0

Используйте LockBox.
Мне кажется в ней Вы найдете все, что Вам нужно.

Раньше использовал, в том числе при использовании FMX и под Android.

Изменено пользователем Semitako Oy
Ссылка на комментарий

Присоединяйтесь к обсуждению

Вы можете написать сейчас и зарегистрироваться позже. Если у вас есть аккаунт, авторизуйтесь, чтобы опубликовать от имени своего аккаунта.

Гость
Ответить на вопрос...

×   Вставлено с форматированием.   Вставить как обычный текст

  Разрешено использовать не более 75 эмодзи.

×   Ваша ссылка была автоматически встроена.   Отображать как обычную ссылку

×   Ваш предыдущий контент был восстановлен.   Очистить редактор

×   Вы не можете вставлять изображения напрямую. Загружайте или вставляйте изображения по ссылке.

  • Последние посетители   0 пользователей онлайн

    • Ни одного зарегистрированного пользователя не просматривает данную страницу
×
×
  • Создать...