我想用 AES 加密 TidBytes

I want to encrypt TidBytes with AES

我正在使用 Tforge 和 Delphi,我正在尝试使用 AES

加密 TidBytes
var Key,MyBytearray: ByteArray;
MyTidBytes:TidBytes;

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

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

此代码在 ByteArray 上运行良好,但我想将它与 idBytes 一起使用,这可能吗?

如何将 ByteArray 转换为 TidBytes

这完全取决于 ByteArrayTidBytes 的声明方式。


如果它们都是 Byte 的动态数组,您可以使用 typecast.

TidBytesByteArray:

MyByteArray := ByteArray(MyTidBytes);

ByteArrayTidBytes:

MyTidBytes := TidBytes(MyBytearray);

如果 ByteArray 的定义类似于 this 并且 TidBytesByte 的动态数组,请尝试以下操作:

MyByteArray.Insert(0, TBytes(MyTidBytes));

ByteArray 被声明为一个 record 内部持有一个 IBytes 接口对象包装字节数据。 TIdBytes 被声明为一个简单的动态数组。因此,您不能 直接 在它们之间进行类型转换。您必须来回复制 原始字节。

您可以手动执行此操作,例如:

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 ...

或者,ByteArray 具有 TBytesImplicit 转换运算符,并且 TIdBytesTBytes 类型转换兼容,因为它们都是动态的数组,例如:

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

...

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