2

I am using Tforge and Delphi and I am trying to encrypt TidBytes with AES

var Key,MyBytearray: ByteArray;
MyTidBytes:TidBytes;

Key:= ByteArray.FromText('1234567890123456');

EncryptedText:= TCipher.AES.ExpandKey(Key, CTR_ENCRYPT or PADDING_NONE).EncryptByteArray(MyBytearray);

This code works fine with ByteArray but I want to use it with idBytes is this possible?

How I will convert ByteArray to TidBytes?

Fabrizio
  • 7,603
  • 6
  • 44
  • 104
icinema gr
  • 310
  • 3
  • 14
  • TIdBytes is part of Indy networking library that ships with Delphi. Now since Indy library also offers some of its own encryption capabilites maybe you could use that instead of TCipher. Othervise based on [this](https://stackoverflow.com/a/18854367/3636228) SO answer it might be possible to typecast TIdBytes array as TBytes array since both are dynamic arrays. – SilverWarior Aug 07 '19 at 11:23

2 Answers2

2

ByteArray is declared as a record that internally holds an IBytes interfaced object wrapping the byte data. TIdBytes is declared as a simple dynamic array instead. As such, you can't directly typecast between them. You must copy the raw bytes back and forth.

You can do that manually, eg:

MyBytearray := ...;
MyTidBytes := RawToBytes(MyBytearray.Raw^, MyBytearray.Len);
// RawToBytes() is an Indy function in the IdGlobal unit...

...

MyTidBytes := ...;
MyBytearray := ByteArray.FromBytes(MyTidBytes);
// FromBytes() accepts any type of raw byte array as input, including dynamic arrays ...

Or, alternatively, ByteArray has Implicit conversion operators for TBytes, and TIdBytes is typecast-compatible with TBytes as they are both dynamic arrays, eg:

MyBytearray := ...;
TBytes(MyTidBytes) := MyBytearray;

...

MyTidBytes := ...;
MyBytearray := TBytes(MyTidBytes);
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
1

It all depends on how ByteArray and TidBytes are declared.


If they are both dynamic arrays of Byte, you could use a typecast.

From TidBytes to ByteArray:

MyByteArray := ByteArray(MyTidBytes);

From ByteArray to TidBytes:

MyTidBytes := TidBytes(MyBytearray);

If ByteArray is defined like this and TidBytes is a dynamic array of Byte, try the following:

MyByteArray.Insert(0, TBytes(MyTidBytes));
Fabrizio
  • 7,603
  • 6
  • 44
  • 104
  • but i want to connvert Tidbytes to Bytearray and not the other way – icinema gr Aug 07 '19 at 11:12
  • 1
    @icinemagr If the cast works in one direction, surely it will work in the other direction? – David Heffernan Aug 07 '19 at 11:35
  • No it doesnt work i try it bytearray is declared in Tfarrays.pas here https://bitbucket.org/sergworks/tforge/src/default/Source/User/tfArrays.pas And is not working. what i am trying to do is to send the Encrypted ByteArray Thru indy UDP client. and decrypt it on IndyUDPserver but i cannot – icinema gr Aug 07 '19 at 11:44
  • i checked as correct because you are the only one answer me.But it Doesnt work i get exception error – icinema gr Aug 07 '19 at 12:16