1 // SPDX-License-Identifier: GPL-2.0-or-later
5 * Blowfish Cipher Algorithm, by Bruce Schneier.
6 * http://www.counterpane.com/blowfish.html
8 * Adapted from Kerneli implementation.
10 * Copyright (c) Herbert Valerio Riedel <hvr@hvrlab.org>
11 * Copyright (c) Kyle McMartin <kyle@debian.org>
12 * Copyright (c) 2002 James Morris <jmorris@intercode.com.au>
14 #include <linux/init.h>
15 #include <linux/module.h>
17 #include <asm/byteorder.h>
18 #include <linux/crypto.h>
19 #include <linux/types.h>
20 #include <crypto/blowfish.h>
23 * Round loop unrolling macros, S is a pointer to a S-Box array
24 * organized in 4 unsigned longs at a row.
26 #define GET32_3(x) (((x) & 0xff))
27 #define GET32_2(x) (((x) >> (8)) & (0xff))
28 #define GET32_1(x) (((x) >> (16)) & (0xff))
29 #define GET32_0(x) (((x) >> (24)) & (0xff))
31 #define bf_F(x) (((S[GET32_0(x)] + S[256 + GET32_1(x)]) ^ \
32 S[512 + GET32_2(x)]) + S[768 + GET32_3(x)])
34 #define ROUND(a, b, n) ({ b ^= P[n]; a ^= bf_F(b); })
36 static void bf_encrypt(struct crypto_tfm
*tfm
, u8
*dst
, const u8
*src
)
38 struct bf_ctx
*ctx
= crypto_tfm_ctx(tfm
);
39 const __be32
*in_blk
= (const __be32
*)src
;
40 __be32
*const out_blk
= (__be32
*)dst
;
41 const u32
*P
= ctx
->p
;
42 const u32
*S
= ctx
->s
;
43 u32 yl
= be32_to_cpu(in_blk
[0]);
44 u32 yr
= be32_to_cpu(in_blk
[1]);
66 out_blk
[0] = cpu_to_be32(yr
);
67 out_blk
[1] = cpu_to_be32(yl
);
70 static void bf_decrypt(struct crypto_tfm
*tfm
, u8
*dst
, const u8
*src
)
72 struct bf_ctx
*ctx
= crypto_tfm_ctx(tfm
);
73 const __be32
*in_blk
= (const __be32
*)src
;
74 __be32
*const out_blk
= (__be32
*)dst
;
75 const u32
*P
= ctx
->p
;
76 const u32
*S
= ctx
->s
;
77 u32 yl
= be32_to_cpu(in_blk
[0]);
78 u32 yr
= be32_to_cpu(in_blk
[1]);
100 out_blk
[0] = cpu_to_be32(yr
);
101 out_blk
[1] = cpu_to_be32(yl
);
104 static struct crypto_alg alg
= {
105 .cra_name
= "blowfish",
106 .cra_driver_name
= "blowfish-generic",
108 .cra_flags
= CRYPTO_ALG_TYPE_CIPHER
,
109 .cra_blocksize
= BF_BLOCK_SIZE
,
110 .cra_ctxsize
= sizeof(struct bf_ctx
),
112 .cra_module
= THIS_MODULE
,
113 .cra_u
= { .cipher
= {
114 .cia_min_keysize
= BF_MIN_KEY_SIZE
,
115 .cia_max_keysize
= BF_MAX_KEY_SIZE
,
116 .cia_setkey
= blowfish_setkey
,
117 .cia_encrypt
= bf_encrypt
,
118 .cia_decrypt
= bf_decrypt
} }
121 static int __init
blowfish_mod_init(void)
123 return crypto_register_alg(&alg
);
126 static void __exit
blowfish_mod_fini(void)
128 crypto_unregister_alg(&alg
);
131 subsys_initcall(blowfish_mod_init
);
132 module_exit(blowfish_mod_fini
);
134 MODULE_LICENSE("GPL");
135 MODULE_DESCRIPTION("Blowfish Cipher Algorithm");
136 MODULE_ALIAS_CRYPTO("blowfish");
137 MODULE_ALIAS_CRYPTO("blowfish-generic");