2 * ChaCha20 256-bit cipher algorithm, RFC7539
4 * Copyright (C) 2015 Martin Willi
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
12 #include <linux/byteorder.h>
13 #include <linux/errno.h>
14 #include <linux/kernel.h>
15 #include <linux/scatterlist.h>
16 #include <asm/unaligned.h>
18 #include <linux/crypto.h>
19 #include <crypto/algapi.h>
20 #include <crypto/chacha.h>
21 #include <crypto/skcipher.h>
23 #include <sodium/crypto_stream_chacha20.h>
25 static struct skcipher_alg alg;
28 struct crypto_skcipher tfm;
32 static int crypto_chacha20_setkey(struct crypto_skcipher *tfm, const u8 *key,
35 struct chacha20_tfm *ctx =
36 container_of(tfm, struct chacha20_tfm, tfm);
39 if (keysize != CHACHA_KEY_SIZE)
42 for (i = 0; i < ARRAY_SIZE(ctx->key); i++)
43 ctx->key[i] = get_unaligned_le32(key + i * sizeof(u32));
48 static int crypto_chacha20_crypt(struct skcipher_request *req)
50 struct chacha20_tfm *ctx =
51 container_of(req->tfm, struct chacha20_tfm, tfm.base);
52 struct scatterlist *sg = req->src;
53 unsigned nbytes = req->cryptlen;
57 BUG_ON(req->src != req->dst);
59 memcpy(iv, req->iv, sizeof(iv));
62 ret = crypto_stream_chacha20_xor_ic(sg_virt(sg),
66 iv[0] | ((u64) iv[1] << 32),
75 BUG_ON(sg->length % CHACHA_BLOCK_SIZE);
76 iv[0] += sg->length / CHACHA_BLOCK_SIZE;
85 static void *crypto_chacha20_alloc_tfm(void)
87 struct chacha20_tfm *tfm = kzalloc(sizeof(*tfm), GFP_KERNEL);
92 tfm->tfm.base.alg = &alg.base;
93 tfm->tfm.setkey = crypto_chacha20_setkey;
94 tfm->tfm.encrypt = crypto_chacha20_crypt;
95 tfm->tfm.decrypt = crypto_chacha20_crypt;
96 tfm->tfm.ivsize = CHACHA_IV_SIZE;
97 tfm->tfm.keysize = CHACHA_KEY_SIZE;
102 static struct skcipher_alg alg = {
103 .base.cra_name = "chacha20",
104 .base.alloc_tfm = crypto_chacha20_alloc_tfm,
107 __attribute__((constructor(110)))
108 static int chacha20_generic_mod_init(void)
110 return crypto_register_skcipher(&alg);