1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| #include <stdio.h>
#define KEYLEN 4 #define PLEN 2 #define DELTA 0x9e3779b9 #define LUN 32
void Encrypt(unsigned int * v, unsigned int * k); void Decrypt(unsigned int * v, unsigned int * k);
int main(void) { unsigned int v[PLEN] = { 0x20210000, 0x1205 }, k[KEYLEN] = { 1, 2, 3, 4 }; printf("Encrypt:"); Encrypt(v, k); printf("0x%x, 0x%x", v[0], v[1]); puts("\n"); printf("Decrypt:"); Decrypt(v, k); printf("0x%x, 0x%x", v[0], v[1]); return 0; }
void Encrypt(unsigned int * v, unsigned int * k) { unsigned int k0 = k[0], k1 = k[1], k2 = k[2], k3 = k[3]; unsigned int v0 = v[0], v1 = v[1]; unsigned int sum = 0 * DELTA; int i; for ( i = 0; i < LUN; i++ ) { sum += DELTA; v0 += ((v1 << 4) + k0) ^ (v1 + sum) ^ ((v1 >> 5) + k1); v1 += ((v0 << 4) + k2) ^ (v0 + sum) ^ ((v0 >> 5) + k3); } v[0] = v0; v[1] = v1; }
void Decrypt(unsigned int * v, unsigned int * k) { unsigned int k0 = k[0], k1 = k[1], k2 = k[2], k3 = k[3]; unsigned int v0 = v[0], v1 = v[1]; unsigned int sum = LUN * DELTA; int i; for ( i = 0; i < LUN; i++ ) { v1 -= ((v0 << 4) + k2) ^ (v0 + sum) ^ ((v0 >> 5) + k3); v0 -= ((v1 << 4) + k0) ^ (v1 + sum) ^ ((v1 >> 5) + k1); sum -= DELTA; } v[0] = v0; v[1] = v1; }
|