The Road to Delphi

Delphi – Free Pascal – Oxygene

Using Rijndael Algorithm in Delphi 2007. Net

Leave a comment

The next code shows a sample of how use the Rijndael Algorithm in Delphi 2007. Net

uses
   System.Security.Cryptography, 
   System.Text;

type
  TDynamicArrayOfByte = array of Byte;

function Encrypt(StrtoEncrypt, PK: string): TDynamicArrayOfByte; // pk, must be of a string of 32 characters
var
   miRijndael:  Rijndael;
   encrypted:   TDynamicArrayOfByte;
   toEncrypt:   TDynamicArrayOfByte;
   bytPK:       TDynamicArrayOfByte;
   i: integer;
begin
   Result     := nil;
   miRijndael := System.Security.Cryptography.RijndaelManaged.Create;
   try
    toEncrypt :=  System.Text.Encoding.UTF8.GetBytes(StrtoEncrypt);
    bytPK     :=  System.Text.Encoding.UTF8.GetBytes(PK);    
    miRijndael.Key := bytPK;
    miRijndael.GenerateIV;
    encrypted := (miRijndael.CreateEncryptor()).TransformFinalBlock(toEncrypt, 0, Length(toEncrypt));
    setlength(result, Length(miRijndael.IV) + Length(encrypted));

      for i:=0 to Length(miRijndael.IV)-1 do
         result[i] := miRijndael.IV[i];

      for i:=0 to Length(encrypted)-1 do
         result[i + Length(miRijndael.IV)] := encrypted[i];

   finally
      miRijndael.Clear();
   end;
end;

function DesEncrypt(BufferEncrypted: TDynamicArrayOfByte; PK: string): string; //   pk, must be of a string of 32 characters
var
   miRijndael:  Rijndael;
   encrypted:   TDynamicArrayOfByte;
   tempArray:   TDynamicArrayOfByte;
   bytPK:       TDynamicArrayOfByte;
   i : integer;
begin
   Result     := '';
   miRijndael := System.Security.Cryptography.RijndaelManaged.Create;
   setlength(tempArray, Length(miRijndael.IV));
   setlength(encrypted, Length(BufferEncrypted) - Length(miRijndael.IV));
   try
    bytPK     :=  System.Text.Encoding.UTF8.GetBytes(PK);
    miRijndael.Key :=  bytPK;

      for i:=0 to Length(tempArray)-1 do
         tempArray[i] := BufferEncrypted[i];

      for i:=0 to Length(encrypted)-1 do
         encrypted[i] := BufferEncrypted[i + Length(tempArray)];

    miRijndael.IV := tempArray;
    Result :=  System.Text.Encoding.UTF8.GetString((miRijndael.CreateDecryptor()).TransformFinalBlock(encrypted, 0, Length(encrypted)));
   finally
     miRijndael.Clear();
   end;
end;

Author: Rodrigo

Just another Delphi guy.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s