blob: 58bb8542e04159adbf870572e2940312bc54b288 [file] [log] [blame]
Viet-Trung Luu96b05c12016-01-11 11:26:36 -08001#include <stdint.h>
2#include <stdlib.h>
3#include <unistd.h>
4
5struct expanded_key {
George Kulakowski17e3b042016-02-18 15:59:50 -08006 uint32_t l[16], r[16];
Viet-Trung Luu96b05c12016-01-11 11:26:36 -08007};
8
George Kulakowski17e3b042016-02-18 15:59:50 -08009void __des_setkey(const unsigned char* key, struct expanded_key* ekey);
10void __do_des(uint32_t l_in,
11 uint32_t r_in,
12 uint32_t* l_out,
13 uint32_t* r_out,
14 uint32_t count,
15 uint32_t saltbits,
16 const struct expanded_key* ekey);
Viet-Trung Luu96b05c12016-01-11 11:26:36 -080017
18static struct expanded_key __encrypt_key;
19
George Kulakowski17e3b042016-02-18 15:59:50 -080020void setkey(const char* key) {
21 unsigned char bkey[8];
22 int i, j;
Viet-Trung Luu96b05c12016-01-11 11:26:36 -080023
George Kulakowski17e3b042016-02-18 15:59:50 -080024 for (i = 0; i < 8; i++) {
25 bkey[i] = 0;
26 for (j = 7; j >= 0; j--, key++)
27 bkey[i] |= (uint32_t)(*key & 1) << j;
28 }
Viet-Trung Luu96b05c12016-01-11 11:26:36 -080029
George Kulakowski17e3b042016-02-18 15:59:50 -080030 __des_setkey(bkey, &__encrypt_key);
Viet-Trung Luu96b05c12016-01-11 11:26:36 -080031}
32
George Kulakowski17e3b042016-02-18 15:59:50 -080033void encrypt(char* block, int edflag) {
34 struct expanded_key decrypt_key, *key;
35 uint32_t b[2];
36 int i, j;
37 char* p;
Viet-Trung Luu96b05c12016-01-11 11:26:36 -080038
George Kulakowski17e3b042016-02-18 15:59:50 -080039 p = block;
40 for (i = 0; i < 2; i++) {
41 b[i] = 0;
42 for (j = 31; j >= 0; j--, p++)
43 b[i] |= (uint32_t)(*p & 1) << j;
44 }
Viet-Trung Luu96b05c12016-01-11 11:26:36 -080045
George Kulakowski17e3b042016-02-18 15:59:50 -080046 key = &__encrypt_key;
47 if (edflag) {
48 key = &decrypt_key;
49 for (i = 0; i < 16; i++) {
50 decrypt_key.l[i] = __encrypt_key.l[15 - i];
51 decrypt_key.r[i] = __encrypt_key.r[15 - i];
52 }
53 }
Viet-Trung Luu96b05c12016-01-11 11:26:36 -080054
George Kulakowski17e3b042016-02-18 15:59:50 -080055 __do_des(b[0], b[1], b, b + 1, 1, 0, key);
Viet-Trung Luu96b05c12016-01-11 11:26:36 -080056
George Kulakowski17e3b042016-02-18 15:59:50 -080057 p = block;
58 for (i = 0; i < 2; i++)
59 for (j = 31; j >= 0; j--)
60 *p++ = b[i] >> j & 1;
Viet-Trung Luu96b05c12016-01-11 11:26:36 -080061}