Search code examples
delphidelphi-7delphi-2010

convert char to char such as encryption


How to make a simple encryption decryption?
2 pieces of make edit box and a button in the project, then I write something in editbox1 and then press button1 in editbox2 generate some keys in such settings ..

a: = 1; b: = 2; c: = 3; d: = 4; e: = 5; f: = 6; g: = 7; h: = 8; i: = 9; j: = 0; k: = #; l: = $; m: =%; n: = ~; o: = *;

and then with the symbol say
a: = 1; it means: a is 1 if at editbox2

letters (A) be the number 1 subparagraph (B) be the number 2 subparagraph (C) be the number 3 simple conversion .. so make a simple substitution cipher and decryption


Solution

  • Here is a simple substitution cipher

    const
      CPlain = 'abcdefghijklmno';
      CCrypt = '1234567890#$%~*';
    
    function Transcode( const AStr, ALookupA, ALookupB : string ): string;
    var
      LIdx, LCharIdx : integer;
    begin
      // the result has the same length as the input string
      SetLength( Result, Length( AStr ) );
      // walk through the whole string
      for LIdx := 1 to Length( AStr ) do
      begin
        // find position of char in LookupA
        LCharIdx := Pos( AStr[LIdx], ALookupA );
        // use the char from LookupB at the previous position
        Result[LIdx] := ALookupB[LCharIdx];
      end;
    end;
    
    function Encrypt( const AStr : string ) : string;
    begin
      // from plain text to crypt text
      Result := Transcode( AStr, CPlain, CCrypt );
    end;
    
    function Decrypt( const AStr : string ) : string;
    begin
      // from crypt text to plain text
      Result := Transcode( AStr, CCrypt, CPlain );
    end;