3 * a implementation of the PRESENT block-cipher
5 * email: daniel.otte@rub.de
14 static uint8_t sbox(uint8_t b){
15 uint8_t sb[]={0xC, 0x5, 0x6, 0xB,
19 return (((sb[b>>4])<<4)|(sb[b&0xf]));
22 static uint8_t sbox_inv(uint8_t b){
23 uint8_t sb[]={0x5, 0xE, 0xF, 0x8,
27 return (((sb[b>>4])<<4)|(sb[b&0xf]));
30 #define SHR_O(a) c=(a)&1; (a)>>=1;
31 #define SHR_I(a) (a)=(c?0x8000:0x0000) | ((a)>>1);
33 static void p(uint16_t* o, uint8_t* i){
50 static void p_inv(uint8_t* o, uint8_t* i){
56 void present_init(const uint8_t* key, uint8_t keysize_b, present_ctx_t* ctx){
57 uint8_t buffer[10], tmp[2];
59 memcpy(buffer, key, 10);
60 memcpy(&(ctx->k[0]), buffer+2, 8);
62 /* rotate buffer 19 right */
63 memcpy(tmp, buffer, 2);
64 memmove(buffer, buffer+2, 8);
65 memcpy(buffer+8, tmp, 2);
66 /* three shifts to do*/
68 *((uint64_t*)buffer)>>=3;
69 *((uint16_t*)(buffer+8))>>=3;
70 buffer[9] |= tmp[1]<<5;
71 buffer[7] |= tmp[0]<<5;
72 /* rotating done now substitution */
73 buffer[9] = (sbox(buffer[9])&0xF0) | ((buffer[9])&0x0F);
74 /* xor with round counter */
75 *((uint16_t*)(buffer+1)) ^= (uint16_t)i<<7;
76 memcpy(&(ctx->k[i]), buffer+2, 8);
80 void present_enc(void* buffer, present_ctx_t* ctx){
83 *((uint64_t*)buffer) ^= ctx->k[i];
85 tmp[j] = sbox(((uint8_t*)buffer)[j]);
87 p((uint16_t*)buffer, tmp);
89 *((uint64_t*)buffer) ^= ctx->k[31];
93 void present_dec(void* buffer, present_ctx_t* ctx){
96 *((uint64_t*)buffer) ^= ctx->k[31];
99 p_inv(tmp, (uint8_t*)buffer);
101 ((uint8_t*)buffer)[j] = sbox_inv(tmp[j]);
103 *((uint64_t*)buffer) ^= ctx->k[i];