Android Question Problem with AES and Delphi

sinner181

Member
Hi everybody,
I'm newbie user for B4A, I'm trying to develop application for android after many years of Windows applications, I think that B4A is the best compromise from DELPHI language.

I'm trying to connect my application from a delphi server with AES encryption, Here the code:

I'm using for test, a fake string
B4X:
  AESKey: TAESKey256 = ($67, $67, $67, $67, $67, $67, $67, $67, $67, $67, $67, $67, $67, $67, $67, $67, $67, $67, $67, $67, $67, $67, $67, $67, $67, $67, $67, $67, $67, $67, $67, $67);
  AESIV: TAESBuffer = ($68, $68, $68, $68, $68, $68, $68, $68, $68, $68, $68, $68, $68, $68, $68, $68);
(AESKey = 32 x "g" and AESIV = 16 x "h")

function Encrypt(data : string) : String;
var
  S : String;
begin
   S := IntToHex(Length(Data), 16);
   Result := AESEncryptString(S + Data, AESKey, AESIV);
end;

function AESEncryptString(Data : AnsiString; Key : TAESKey256; IV : TAESBuffer) : AnsiString;
var
  Cipher: TDCP_rijndael;
  I: Integer;
begin
  Cipher := TDCP_rijndael.Create(nil);
  Cipher.Init(Key[0], 256, @IV[0]);

  if (Length(Data) mod 16 > 0) then   //this fix is less than 16
    for I := 1 to (16 - (Length(Data) mod 16)) do
      Data := Data + AnsiChar(0);

  SetLength(Result, Length(Data));
  Cipher.EncryptCBC(Data[1], Result[1], Length(Data));
  Cipher.Burn;
  Cipher.Free;
end;


In B4A I've tryed a lot of classes without result, for example

B4X:
Public Sub AES_Encrypt(DataToEncrypt As String) As String
    Dim poKG As KeyGenerator
    Dim poCy As Cipher
    Dim poBC As ByteConverter
    Dim poData() As Byte
    Dim USER_IV16 As String
    Dim USER_KEY As String
    USER_IV16 = "hhhhhhhhhhhhhhhh"
    USER_KEY = "gggggggggggggggggggggggggggggggg"

    ' doing AES
    poCy.Initialize("AES")
    ' set InitializationVector value
    poCy.InitialisationVector = poBC.StringToBytes(USER_IV16, "ASCII")
    ' Generate a key
    poKG.Initialize("AES")
    poKG.KeyFromBytes(poBC.StringToBytes(USER_KEY, "ASCII"))
    ' encrypt the string into a byte array
    poData = poCy.Encrypt(poBC.StringToBytes(DataToEncrypt, "ASCII"), poKG.Key, True)
    ' convert the byte array to a HEX string and return it
    'Return poBC.HexFromBytes(poData)
    Return BytesToString(poData,0,poData.Length,"ASCII")
End Sub

Ths string arrive to my server and is totally different, unreadable. (in ASCII and UTF8 is the same result)
-------------------------------------------------------

B4XEncryption I think is unusable because IV is random....or wrong? :/

Someone can help me please, sorry if there are rubbish but this is my 3th days here =)
Thank you
 
Last edited:

Erel

B4X founder
Staff member
Licensed User
Longtime User
Upvote 0
Top