Annotation of OpenXM/src/ox_ntl/crypt/blowfish/blowfish.c, Revision 1.2
1.2 ! iwane 1: /* $OpenXM: OpenXM/src/ox_ntl/crypt/blowfish/blowfish.c,v 1.1 2004/07/22 12:12:05 iwane Exp $ */
1.1 iwane 2:
3: /*
4: * BLOWFISH: Bruce Schneier
5: * http://www.schneier.com/blowfish.html
6: */
7:
8: #include "blowfish.h"
9: #include "bf_tbl.h"
10:
11: #if HAVE_CONFIG_H
12: #include "config.h"
13: #endif
14:
1.2 ! iwane 15: #include <unistd.h>
1.1 iwane 16:
17:
18: static uint32_t
19: f(const blowfish_key *key, uint32_t x)
20: {
21: #define S(i) key->s[256 * i + a[i]]
22: uint8_t a[4];
23: int i;
24:
25: for (i = 0; i < 4; i++) {
26: a[i] = (x >> ((3 - i) * 8)) & 0xff;
27: }
28:
29: return (((S(0) + S(1)) ^ S(2)) + S(3));
30: #undef S
31: }
32:
33:
34: void
35: blowfish_enc_i(const blowfish_key *key,
36: uint32_t ml, uint32_t mr,
37: uint32_t *el, uint32_t *er)
38: {
39: int i;
40: uint32_t tmp;
41:
42: for (i = 0; i < 16; i++) {
43: ml = ml ^ key->p[i];
44: tmp = f(key, ml) ^ mr;
45:
46: mr = ml;
47: ml = tmp;
48: }
49:
50: *er = ml ^ key->p[i++];
51: *el = mr ^ key->p[i++];
52: }
53:
54: void
55: blowfish_dec_i(const blowfish_key *key,
56: uint32_t ml, uint32_t mr,
57: uint32_t *el, uint32_t *er)
58: {
59: int i;
60: uint32_t tmp;
61:
62: for (i = 17; i >= 2; i--) {
63: ml = ml ^ key->p[i];
64: tmp = f(key, ml) ^ mr;
65:
66: mr = ml;
67: ml = tmp;
68: }
69:
70: *er = ml ^ key->p[i--];
71: *el = mr ^ key->p[i--];
72: }
73:
74:
75: #define BLOWFISH_MAXKEYLEN 448
76:
77: void
78: blowfish_setkey(const unsigned char *str, int len, blowfish_key *key)
79: {
80: int i, j, k;
81: uint32_t t;
82: uint32_t ml, mr;
83:
84: if (len > BLOWFISH_MAXKEYLEN )
85: len = BLOWFISH_MAXKEYLEN;
86:
87: memcpy(key->p, __blowfish_tbl_p, sizeof(uint32_t) * 18);
88: memcpy(key->s, __blowfish_tbl_s, sizeof(uint32_t) * 256 * 4);
89:
90: j = 0;
91: for (i = 0; i < 18; i++) {
92: t = 0;
93: for (k = 0; k < 4; k++)
94: t |= str[j++ % len] << (8 * (3 - k));
95:
96: key->p[i] ^= t;
97: }
98:
99: ml = mr = 0;
100: for (i = 0; i < 18; i += 2) {
101: blowfish_enc_i(key, ml, mr, &ml, &mr);
102:
103: key->p[i] = ml;
104: key->p[i + 1] = mr;
105: }
106: for (i = 0; i < 4 * 256; i += 2) {
107: blowfish_enc_i(key, ml, mr, &ml, &mr);
108:
109: key->s[i] = ml;
110: key->s[i + 1] = mr;
111: }
112: }
113:
114:
115:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>