Encrypting and Decrypting strings in Delphi.

By: Kendall Sullivan

Abstract: Code sample demonstrates a basic Encryption/Decryption algorithm for strings.

QUESTION:

How can I encrypt and decrypt string values?

ANSWER:

There are a number of ways to do this, below is a code sample that demonstrates one of the ways. Start with a form, and drop three Edit components, and two buttons. Add the EnDeCrypt function to the TForm1 class declaration in the type portion of the Unit. Omitting the TForm. section of the declaration. Then add the function in the implementation section of the Unit as shown below. Now double click each of the buttons and add the code as shown below. Run the project, in the Edit1 text area type in a word and click Button1. Now click Button2, you should see your word encrypted in Edit2 text and decrypted in Edit3 text. This should give you a basic idea on how Encryption works.

type
  TForm1 = class(TForm)
    Button1: TButton;
    Edit1: TEdit;
    Edit2: TEdit;
    Button2: TButton;
    Edit3: TEdit;
    procedure Button1Click(Sender: TObject);
    function EnDeCrypt(const Value : String) : String;
    procedure Button2Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

function TForm1.EnDeCrypt(const Value : String) : String;
var
  CharIndex : integer;
begin
  Result := Value;
  for CharIndex := 1 to Length(Value) do
    Result[CharIndex] := chr(not(ord(Value[CharIndex])));
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  Edit2.Text := EnDeCrypt(Edit1.Text);
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  Edit3.Text := EnDeCrypt(Edit2.Text);
end;

Server Response from: ETNASC02