and_cesbo icon

triple_des_set_key

and_cesbo | PRO | 04/10/24 09:06:41 AM UTC (Edited) | 0 ⭐ | 14692 👁️ | Never ⏰ | []
C |

2.52 KB

|

Cybersecurity

|

0 👍

/

0 👎

#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <openssl/des.h>
 
// Build: gcc $(pkg-config --libs --cflags libcrypto) -o x x.c
 
static void triple_des_set_key(const uint8_t *des_key, const uint8_t *key, size_t key_size) {
    uint8_t tmp_key[14];
    memcpy(tmp_key, des_key, sizeof(tmp_key));
 
    // set key
    for(size_t i = 0; i < key_size; ++i)
        tmp_key[i % sizeof(tmp_key)] ^= key[i];
 
    uint8_t triple_des_key[16];
    DES_key_schedule ks1;
    DES_key_schedule ks2;
 
    triple_des_key[0] = tmp_key[0] & 0xfe;
    triple_des_key[1] = ((tmp_key[0] << 7) | (tmp_key[1] >> 1)) & 0xfe;
    triple_des_key[2] = ((tmp_key[1] << 6) | (tmp_key[2] >> 2)) & 0xfe;
    triple_des_key[3] = ((tmp_key[2] << 5) | (tmp_key[3] >> 3)) & 0xfe;
    triple_des_key[4] = ((tmp_key[3] << 4) | (tmp_key[4] >> 4)) & 0xfe;
    triple_des_key[5] = ((tmp_key[4] << 3) | (tmp_key[5] >> 5)) & 0xfe;
    triple_des_key[6] = ((tmp_key[5] << 2) | (tmp_key[6] >> 6)) & 0xfe;
    triple_des_key[7] = tmp_key[6] << 1;
    triple_des_key[8] = tmp_key[7] & 0xfe;
    triple_des_key[9] = ((tmp_key[7] << 7) | (tmp_key[8] >> 1)) & 0xfe;
    triple_des_key[10] = ((tmp_key[8] << 6) | (tmp_key[9] >> 2)) & 0xfe;
    triple_des_key[11] = ((tmp_key[9] << 5) | (tmp_key[10] >> 3)) & 0xfe;
    triple_des_key[12] = ((tmp_key[10] << 4) | (tmp_key[11] >> 4)) & 0xfe;
    triple_des_key[13] = ((tmp_key[11] << 3) | (tmp_key[12] >> 5)) & 0xfe;
    triple_des_key[14] = ((tmp_key[12] << 2) | (tmp_key[13] >> 6)) & 0xfe;
    triple_des_key[15] = tmp_key[13] << 1;
 
    DES_set_odd_parity((DES_cblock *)&triple_des_key[0]);
    DES_set_odd_parity((DES_cblock *)&triple_des_key[8]);
 
    DES_key_sched((DES_cblock *)&triple_des_key[0], &ks1);
    DES_key_sched((DES_cblock *)&triple_des_key[8], &ks2);
 
    const uint8_t *ks1_ptr = (const uint8_t *)&ks1;
    printf("ks1: 0x");
    for(int i = 0; i < sizeof(ks1); i++)
        printf("%02x", ks1_ptr[i]);
    printf("\n");
 
    const uint8_t *ks2_ptr = (const uint8_t *)&ks2;
    printf("ks2: 0x");
    for(int i = 0; i < sizeof(ks2); i++)
        printf("%02x", ks2_ptr[i]);
    printf("\n");
} /* triple_des_set_key */
 
int main() {
    const uint8_t des_key[] = {
        0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
        0x09, 0x10, 0x11, 0x12, 0x13, 0x14
    };
 
    const uint8_t key[] = {
        0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,
        0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x5D,
    };
 
    triple_des_set_key(des_key, key, sizeof(key));
 
    return 0;
}
 

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎

    
        
  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎