Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Need for swapping int64 bytes to conform DES #1

Open
nickaein opened this issue Jan 23, 2017 · 0 comments
Open

Need for swapping int64 bytes to conform DES #1

nickaein opened this issue Jan 23, 2017 · 0 comments

Comments

@nickaein
Copy link

nickaein commented Jan 23, 2017

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);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant