#include #include "XTEA.h" void XTEA::setKey(void* key) { memcpy(_key, key, 16); } void XTEA::setIV(void* iv) { memcpy(_vector, iv, 8); } void XTEA::setIV(uint32_t ivh = 0, uint32_t ivl = 0) { memcpy(_vector, &ivh, 4); memcpy(_vector+4, &ivl, 4); } void XTEA::cbc_encrypt(void *dest, const void *plain, uint16_t nr_blocks) { for (uint32_t i = 0; i < nr_blocks; i++) { // XOR the current vector with the block before encrypting for (auto j = 0; j < 8; j++) { ((uint8_t*)plain)[i*8 + j] ^= _vector[j]; } // Encrypt the block encrypt_block((uint8_t*)dest + i*8, (uint8_t*)plain + i*8); // Copy the cipher output to the current vector memcpy(_vector, (uint8_t*)dest + i*8, 8); } } void XTEA::cbc_decrypt(void *dest, const void *cipher, uint16_t nr_blocks) { for (uint32_t i = 0; i < nr_blocks; i++) { // Decrypt the block decrypt_block((uint8_t*)dest + i*8, (uint8_t*)cipher + i*8); // XOR the output with the current vector to fully decrypt for (auto j = 0; j < 8; j++) { ((uint8_t*)dest)[i*8 + j] ^= _vector[j]; } // Copy the cipher text to the current vector memcpy(_vector, (uint8_t*)cipher + i*8, 8); } } void XTEA::encrypt_block(void *dest, const void *block) { uint8_t i; uint32_t v0=((uint32_t*)block)[0], v1=((uint32_t*)block)[1]; uint32_t sum=0, delta=0x9E3779B9; for(i=0; i> 5) + v1) ^ (sum + ((uint32_t*)_key)[sum & 3]); sum += delta; v1 += ((v0 << 4 ^ v0 >> 5) + v0) ^ (sum + ((uint32_t*)_key)[sum>>11 & 3]); } ((uint32_t*)dest)[0]=v0; ((uint32_t*)dest)[1]=v1; } void XTEA::decrypt_block(void *dest, const void *block) { uint8_t i; uint32_t v0=((uint32_t*)block)[0], v1=((uint32_t*)block)[1]; uint32_t delta=0x9E3779B9, sum=delta*XTEA_CYCLES; for(i=0; i> 5) + v0) ^ (sum + ((uint32_t*)_key)[sum>>11 & 3]); sum -= delta; v0 -= ((v1 << 4 ^ v1 >> 5) + v1) ^ (sum + ((uint32_t*)_key)[sum & 3]); } ((uint32_t*)dest)[0]=v0; ((uint32_t*)dest)[1]=v1; }