Skip to content

Need for swapping int64 bytes to conform DESΒ #1

@nickaein

Description

@nickaein

When using encrypting/decrypting a byte array, one has to always swap bytes in int64 to get the conforming result with DES standard.

For instance, consider this DES encryption case
input data: 0011223344556677
key: 0123456789ABCDEF
output: CADB6782EE2B4823
(can be verified by http://www.emvlab.org/descalc)

The following code can calculates this output only by performing a swap on the data bytes. Note that all of the _byteswap_uint64 (or __builtin_bswap64 for gcc) are required. Removing any of them (especially the first two one) leads to incorrect results.

One workaround could be overloading encrypt and decrypt functions to accept byte arrays and swap the bytes internally. However this can impact the performance.
It would be nice if the internal calculations can be fixed in a way to avoid the need for the swapping the input array bytes.

void test_des()
{
	// Prepare the key
	uint8_t key[8] = { 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF };

	uint64_t key_int = *(uint64_t*)key;

	key_int = _byteswap_uint64(key_int);

	// Generate DES instance
	DES des(key_int);

	// Prepare the input data
	uint8_t data[8] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77 };

	uint64_t data_int = *(uint64_t*)data;

	data_int = _byteswap_uint64(data_int);

	// Encrypt
	data_int = des.encrypt(data_int);

	// Write the result in byte array
	uint8_t cipher[8];
	data_int = _byteswap_uint64(data_int);
	memcpy(cipher, &data_int, 8);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions