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