1 #include <stdint.h>
2 #include <stdlib.h>
3 #include <unistd.h>
4
5 struct expanded_key {
6 uint32_t l[16], r[16];
7 };
8
9 void __des_setkey(const unsigned char* key, struct expanded_key* ekey);
10 void __do_des(uint32_t l_in, uint32_t r_in, uint32_t* l_out, uint32_t* r_out, uint32_t count,
11 uint32_t saltbits, const struct expanded_key* ekey);
12
13 static struct expanded_key __encrypt_key;
14
setkey(const char * key)15 void setkey(const char* key) {
16 unsigned char bkey[8];
17 int i, j;
18
19 for (i = 0; i < 8; i++) {
20 bkey[i] = 0;
21 for (j = 7; j >= 0; j--, key++)
22 bkey[i] |= (uint32_t)(*key & 1) << j;
23 }
24
25 __des_setkey(bkey, &__encrypt_key);
26 }
27
encrypt(char * block,int edflag)28 void encrypt(char* block, int edflag) {
29 struct expanded_key decrypt_key, *key;
30 uint32_t b[2];
31 int i, j;
32 char* p;
33
34 p = block;
35 for (i = 0; i < 2; i++) {
36 b[i] = 0;
37 for (j = 31; j >= 0; j--, p++)
38 b[i] |= (uint32_t)(*p & 1) << j;
39 }
40
41 key = &__encrypt_key;
42 if (edflag) {
43 key = &decrypt_key;
44 for (i = 0; i < 16; i++) {
45 decrypt_key.l[i] = __encrypt_key.l[15 - i];
46 decrypt_key.r[i] = __encrypt_key.r[15 - i];
47 }
48 }
49
50 __do_des(b[0], b[1], b, b + 1, 1, 0, key);
51
52 p = block;
53 for (i = 0; i < 2; i++)
54 for (j = 31; j >= 0; j--)
55 *p++ = b[i] >> j & 1;
56 }
57