Search code examples
delphidelphi-7

Encryption of a password


i've managed to do a simple encryption of a password entered using the following code which then displays the encrypted password in a labels caption,

procedure TfrmLogin.edtAddPasswordClick(Sender: TObject);
var
  NormalPassword, EncryptedPassword: string;
  PasswordChar: Char;
  EncryptedCharValue: string;
  CharPtr: Integer;
  Ptr, n: Integer;
begin
  NormalPassword := Edit1.text;
  EncryptedPassword := '';
  for CharPtr := 1 to Length(NormalPassword) do
  begin
    PasswordChar := NormalPassword[CharPtr];
    EncryptedCharValue := IntToStr (Ord(PasswordChar) * 5 + 14);
    EncryptedPassword := EncryptedPassword + EncryptedCharValue;
    Label1.Caption := EncryptedPassword;
  end;
end;

The problem is that i would like to convert the encrypted password displayed in label1.caption back into its original form on the click of another button and i can't work out how this could be done. any suggestions?


Solution

  • Instead of create your own algorithm to hash( or encrypt) a password, try using a well tested and reliable algorithm like SHA1, MD5, and so on.

    Back to your question to convert the encrypted value to the original, all you must do is reverse your algorithm , try this sample.

    var
      NormalPassword, EncryptedPassword: String;
      PasswordChar : char;
      EncryptedCharValue : String;
      CharPtr : Integer;
    begin
      NormalPassword    :='';
      EncryptedPassword := Label1.Caption; //here is stored the encrypted password
      CharPtr := 1;
      while CharPtr< length(EncryptedPassword) do
        Begin
          EncryptedCharValue:=Copy(EncryptedPassword, CharPtr, 3);
          Inc(CharPtr, 3);
          PasswordChar     := Chr((StrToint(EncryptedCharValue)-14) div 5);
          NormalPassword  :=NormalPassword+ PasswordChar;
        end;
        Label2.Caption := NormalPassword; 
    end;