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>
15 #include <crypto/algapi.h>
16 #include <linux/init.h>
17 #include <linux/module.h>
19 #include <asm/unaligned.h>
20 #include <linux/types.h>
21 #include <crypto/blowfish.h>
24 * Round loop unrolling macros, S is a pointer to a S-Box array
25 * organized in 4 unsigned longs at a row.
27 #define GET32_3(x) (((x) & 0xff))
28 #define GET32_2(x) (((x) >> (8)) & (0xff))
29 #define GET32_1(x) (((x) >> (16)) & (0xff))
30 #define GET32_0(x) (((x) >> (24)) & (0xff))
32 #define bf_F(x) (((S[GET32_0(x)] + S[256 + GET32_1(x)]) ^ \
33 S[512 + GET32_2(x)]) + S[768 + GET32_3(x)])
35 #define ROUND(a, b, n) ({ b ^= P[n]; a ^= bf_F(b); })
37 static void bf_encrypt(struct crypto_tfm *tfm, u8 *dst, const u8 *src)
39 struct bf_ctx *ctx = crypto_tfm_ctx(tfm);
40 const u32 *P = ctx->p;
41 const u32 *S = ctx->s;
42 u32 yl = get_unaligned_be32(src);
43 u32 yr = get_unaligned_be32(src + 4);
65 put_unaligned_be32(yr, dst);
66 put_unaligned_be32(yl, dst + 4);
69 static void bf_decrypt(struct crypto_tfm *tfm, u8 *dst, const u8 *src)
71 struct bf_ctx *ctx = crypto_tfm_ctx(tfm);
72 const u32 *P = ctx->p;
73 const u32 *S = ctx->s;
74 u32 yl = get_unaligned_be32(src);
75 u32 yr = get_unaligned_be32(src + 4);
97 put_unaligned_be32(yr, dst);
98 put_unaligned_be32(yl, dst + 4);
101 static struct crypto_alg alg = {
102 .cra_name = "blowfish",
103 .cra_driver_name = "blowfish-generic",
105 .cra_flags = CRYPTO_ALG_TYPE_CIPHER,
106 .cra_blocksize = BF_BLOCK_SIZE,
107 .cra_ctxsize = sizeof(struct bf_ctx),
108 .cra_module = THIS_MODULE,
109 .cra_u = { .cipher = {
110 .cia_min_keysize = BF_MIN_KEY_SIZE,
111 .cia_max_keysize = BF_MAX_KEY_SIZE,
112 .cia_setkey = blowfish_setkey,
113 .cia_encrypt = bf_encrypt,
114 .cia_decrypt = bf_decrypt } }
117 static int __init blowfish_mod_init(void)
119 return crypto_register_alg(&alg);
122 static void __exit blowfish_mod_fini(void)
124 crypto_unregister_alg(&alg);
127 subsys_initcall(blowfish_mod_init);
128 module_exit(blowfish_mod_fini);
130 MODULE_LICENSE("GPL");
131 MODULE_DESCRIPTION("Blowfish Cipher Algorithm");
132 MODULE_ALIAS_CRYPTO("blowfish");
133 MODULE_ALIAS_CRYPTO("blowfish-generic");