1 // SPDX-License-Identifier: GPL-2.0
4 * OFB: Output FeedBack mode
6 * Copyright (C) 2018 ARM Limited or its affiliates.
10 #include <crypto/algapi.h>
11 #include <crypto/internal/skcipher.h>
12 #include <linux/err.h>
13 #include <linux/init.h>
14 #include <linux/kernel.h>
15 #include <linux/module.h>
17 static int crypto_ofb_crypt(struct skcipher_request *req)
19 struct crypto_skcipher *tfm = crypto_skcipher_reqtfm(req);
20 struct crypto_cipher *cipher = skcipher_cipher_simple(tfm);
21 const unsigned int bsize = crypto_cipher_blocksize(cipher);
22 struct skcipher_walk walk;
25 err = skcipher_walk_virt(&walk, req, false);
27 while (walk.nbytes >= bsize) {
28 const u8 *src = walk.src.virt.addr;
29 u8 *dst = walk.dst.virt.addr;
30 u8 * const iv = walk.iv;
31 unsigned int nbytes = walk.nbytes;
34 crypto_cipher_encrypt_one(cipher, iv, iv);
35 crypto_xor_cpy(dst, src, iv, bsize);
38 } while ((nbytes -= bsize) >= bsize);
40 err = skcipher_walk_done(&walk, nbytes);
44 crypto_cipher_encrypt_one(cipher, walk.iv, walk.iv);
45 crypto_xor_cpy(walk.dst.virt.addr, walk.src.virt.addr, walk.iv,
47 err = skcipher_walk_done(&walk, 0);
52 static int crypto_ofb_create(struct crypto_template *tmpl, struct rtattr **tb)
54 struct skcipher_instance *inst;
55 struct crypto_alg *alg;
58 inst = skcipher_alloc_instance_simple(tmpl, tb);
62 alg = skcipher_ialg_simple(inst);
64 /* OFB mode is a stream cipher. */
65 inst->alg.base.cra_blocksize = 1;
68 * To simplify the implementation, configure the skcipher walk to only
69 * give a partial block at the very end, never earlier.
71 inst->alg.chunksize = alg->cra_blocksize;
73 inst->alg.encrypt = crypto_ofb_crypt;
74 inst->alg.decrypt = crypto_ofb_crypt;
76 err = skcipher_register_instance(tmpl, inst);
83 static struct crypto_template crypto_ofb_tmpl = {
85 .create = crypto_ofb_create,
86 .module = THIS_MODULE,
89 static int __init crypto_ofb_module_init(void)
91 return crypto_register_template(&crypto_ofb_tmpl);
94 static void __exit crypto_ofb_module_exit(void)
96 crypto_unregister_template(&crypto_ofb_tmpl);
99 subsys_initcall(crypto_ofb_module_init);
100 module_exit(crypto_ofb_module_exit);
102 MODULE_LICENSE("GPL");
103 MODULE_DESCRIPTION("OFB block cipher mode of operation");
104 MODULE_ALIAS_CRYPTO("ofb");