summaryrefslogtreecommitdiffstats
path: root/freebsd/sys/crypto/chacha20/chacha-sw.c
blob: f610dac0a182b53fbb97e2aa9cd6eefc46e69b1e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <machine/rtems-bsd-kernel-space.h>

/* This file is in the public domain. */

#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");

#include <crypto/chacha20/chacha.h>
#include <opencrypto/xform_enc.h>

static int
chacha20_xform_setkey(u_int8_t **sched, const u_int8_t *key, int len)
{
	struct chacha_ctx *ctx;

	if (len != CHACHA_MINKEYLEN && len != 32)
		return (EINVAL);

	ctx = malloc(sizeof(*ctx), M_CRYPTO_DATA, M_NOWAIT | M_ZERO);
	*sched = (void *)ctx;
	if (ctx == NULL)
		return (ENOMEM);

	chacha_keysetup(ctx, key, len * 8);
	return (0);
}

static void
chacha20_xform_reinit(caddr_t key, const u_int8_t *iv)
{
	struct chacha_ctx *ctx;

	ctx = (void *)key;
	chacha_ivsetup(ctx, iv + 8, iv);
}

static void
chacha20_xform_zerokey(u_int8_t **sched)
{
	struct chacha_ctx *ctx;

	ctx = (void *)*sched;
	explicit_bzero(ctx, sizeof(*ctx));
	free(ctx, M_CRYPTO_DATA);
	*sched = NULL;
}

static void
chacha20_xform_crypt(caddr_t cctx, u_int8_t *bytes)
{
	struct chacha_ctx *ctx;

	ctx = (void *)cctx;
	chacha_encrypt_bytes(ctx, bytes, bytes, 1);
}

static void
chacha20_xform_crypt_multi(void *vctx, uint8_t *bytes, size_t len)
{
	struct chacha_ctx *ctx;

	ctx = vctx;
	chacha_encrypt_bytes(ctx, bytes, bytes, len);
}

struct enc_xform enc_xform_chacha20 = {
	.type = CRYPTO_CHACHA20,
	.name = "chacha20",
	.blocksize = 1,
	.ivsize = CHACHA_NONCELEN + CHACHA_CTRLEN,
	.minkey = CHACHA_MINKEYLEN,
	.maxkey = 32,
	.encrypt = chacha20_xform_crypt,
	.decrypt = chacha20_xform_crypt,
	.setkey = chacha20_xform_setkey,
	.zerokey = chacha20_xform_zerokey,
	.reinit = chacha20_xform_reinit,
	.encrypt_multi = chacha20_xform_crypt_multi,
	.decrypt_multi = chacha20_xform_crypt_multi,
};