Xor-el / CryptoLib4Pascal

Crypto for Modern Object Pascal
MIT License
211 stars 65 forks source link

Sample for simple AES encryptions #15

Closed ertankucukoglu closed 4 years ago

ertankucukoglu commented 4 years ago

Hello,

I am already using your libraries and thank you for making them available. I had no problem until today. Today, I had the need to encrypt a file using AES/CBC/PKCS7PADDING 256bits.

My existing code is something like below. However, that only encrypts data from TBytes

uses
  System.NetEncoding,
  ClpIBufferedCipher,
  ClpCipherUtilities,
  ClpIParametersWithIV,
  ClpParametersWithIV,
  ClpParameterUtilities,
  ClpEncoders;

//------------------------------------------------------------------------------
function EncryptAESCBC256WithKeyIV(const Key, IV: TBytes; const PlainText: string; out CryptBase64Text: string): Boolean;
var
  Cipher: IBufferedCipher;
  KeyParametersWithIV: IParametersWithIV;
  KeyBytes: TBytes;
  IVBytes: TBytes;
  Buf: TBytes;
  CryptBytes: TBytes;
begin
  try
    SetLength(KeyBytes, Length(Key)); // SizeOf() in Delphi behaves strange. Length() is much more stable even for arrays
    Move(Key[0], Pointer(KeyBytes)^, Length(Key));

    SetLength(IVBytes, Length(IV));
    Move(IV[0], Pointer(IVBytes)^, Length(IV));

    Cipher := TCipherUtilities.GetCipher('AES/CBC/PKCS7PADDING');
    KeyParametersWithIV := TParametersWithIV.Create(TParameterUtilities.CreateKeyParameter('AES', KeyBytes), IVBytes);
    Cipher.Init(True, KeyParametersWithIV); // init encryption cipher

    Buf := TEncoding.UTF8.GetBytes(PlainText);
    CryptBytes := Cipher.DoFinal(Buf);

    CryptBase64Text := TNetEncoding.Base64.EncodeBytesToString(CryptBytes);
  except
    on E: Exception do
    begin
      ALog.LogError('EncryptAESCBC256WithKeyIV(): ' + E.Message);
      Exit(False);
    end;
  end;
  Result := True;
end;

I believe, it will be helpful to have simple example(s) (nothing like elliptic curves, etc) for people like me who have very simple and basic needs as to encryption and willing to use your libraries.

I also appreciate if you can provide a simple way of encrypting a file. Possibly using one TFileStream class for input and one for output as parameter.

Just a side note, above code is from Delphi, I am trying to solve a problem on Linux (ARM platform) with file encryption, now. So, I will be using Lazarus for that matter.

Thanks & Regards, Ertan

Xor-el commented 4 years ago

Hi, this line has what you need (encrypting chunks of bytes), https://github.com/Xor-el/CryptoLib4Pascal/blob/master/CryptoLib.Tests/src/Crypto/AESTests.pas#L106-#L115

For other examples, please check the unit tests or usageexamples.pas file.