StrAES.pas 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. unit StrAES;
  2. interface
  3. uses
  4. Windows,SysUtils,Classes,ElAES,math;
  5. function AESDecyptStr(strIn,AESKey: string): string;
  6. function AESEncryptStr(strIn,AESKey: string): string;
  7. implementation
  8. function AESDecyptStr(strIn,AESKey: string): string;
  9. function HexToString(S: string): string;
  10. var
  11. i: integer;
  12. begin
  13. Result := '';
  14. // Go throught every single hexadecimal characters, and convert
  15. // them to ASCII characters...
  16. for i := 1 to Length( S ) do
  17. begin
  18. // Only process chunk of 2 digit Hexadecimal...
  19. if ((i mod 2) = 1) then
  20. Result := Result + Chr( StrToInt( '0x' + Copy( S, i, 2 )));
  21. end;
  22. end;
  23. var
  24. Source: TStringStream;
  25. Dest: TStringStream;
  26. Start, Stop: cardinal;
  27. Size: integer;
  28. Key: TAESKey128;
  29. EncryptedText: TStrings;
  30. S: string;
  31. begin
  32. // Convert hexadecimal to a strings before decrypting...
  33. Source := TStringStream.Create( HexToString( strIn ));
  34. Dest := TStringStream.Create( '' );
  35. try
  36. // Start decryption...
  37. Size := Source.Size;
  38. Source.ReadBuffer(Size, SizeOf(Size));
  39. // Prepare key...
  40. FillChar(Key, SizeOf(Key), 0);
  41. Move(PChar(AESKey)^, Key, Min(SizeOf(Key), Length(AESKey)));
  42. // Decrypt now...
  43. DecryptAESStreamECB(Source, Source.Size - Source.Position, Key, Dest);
  44. // Display unencrypted text...
  45. Result := Dest.DataString;
  46. finally
  47. Source.Free;
  48. Dest.Free;
  49. end;
  50. end;
  51. function AESEncryptStr(strIn,AESKey: string): string;
  52. function StringToHex(S: string): string;
  53. var
  54. i: integer;
  55. begin
  56. Result := '';
  57. // Go throught every single characters, and convert them
  58. // to hexadecimal...
  59. for i := 1 to Length( S ) do
  60. Result := Result + IntToHex( Ord( S[i] ), 2 );
  61. end;
  62. var
  63. Source: TStringStream;
  64. Dest: TStringStream;
  65. Size: integer;
  66. Key: TAESKey128;
  67. begin
  68. // Encryption
  69. Source := TStringStream.Create(strIn );
  70. Dest := TStringStream.Create( '' );
  71. try
  72. // Save data to memory stream...
  73. Size := Source.Size;
  74. Dest.WriteBuffer( Size, SizeOf(Size) );
  75. // Prepare key...
  76. FillChar( Key, SizeOf(Key), 0 );
  77. Move( PChar(AESKey)^, Key, Min( SizeOf( Key ), Length( AESKey)));
  78. // Start encryption...
  79. EncryptAESStreamECB( Source, 0, Key, Dest );
  80. // Display encrypted text using hexadecimals...
  81. Result := StringToHex( Dest.DataString );
  82. finally
  83. Source.Free;
  84. Dest.Free;
  85. end;
  86. end;
  87. end.