Skip to content

Instantly share code, notes, and snippets.

@sfan5 sfan5/xteapipe.c
Last active Dec 19, 2015

Embed
What would you like to do?
De/Encrypts from stdin to stdout using XTEA in OFB mode
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
void xtea_encrypt(unsigned int num_rounds, uint32_t v[2], uint32_t const key[4]) {
unsigned int i;
uint32_t v0=v[0], v1=v[1], sum=0, delta=0x9E3779B9;
for (i=0; i < num_rounds; i++) {
v0 += (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum + key[sum & 3]);
sum += delta;
v1 += (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum + key[(sum>>11) & 3]);
}
v[0]=v0; v[1]=v1;
}
int main(int argc, char *argv[])
{
if(argc <= 2) { printf("Usage: %s <iv> <key>\n", argv[0]); return 1; }
if(strlen(argv[1]) != 16) { fprintf(stderr, "IV must be 16 characters\n"); return 1; }
if(strlen(argv[2]) != 32) { fprintf(stderr, "Key must be 32 characters\n"); return 1; }
char *temp = malloc(3);
temp[2] = 0;
unsigned char i;
uint8_t* iv = (uint8_t*) malloc(8);
for(i = 0; i < 8; i++)
{
strncpy(temp, (char*) argv[1]+i*2, 2);
sscanf(temp, "%02x", (unsigned int*) &iv[i]);
}
uint8_t* key = (uint8_t*) malloc(16);
for(i = 0; i < 16; i++)
{
strncpy(temp, (char*) argv[2]+i*2, 2);
sscanf(temp, "%02x", (unsigned int*) &key[i]);
}
short pos = 9;
uint8_t* current = (uint8_t*) malloc(8);
memcpy(current, iv, 8);
while(1)
{
if(pos == 9)
{
xtea_encrypt(32, (uint32_t*) current, (uint32_t*) key);
pos = 0;
}
char c = getc(stdin);
if(feof(stdin)) break;
putchar(c ^ current[pos]);
//fflush(stdout);
pos++;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.