1 // SPDX-License-Identifier: GPL-2.0-only
3 * GHASH: digest algorithm for GCM (Galois/Counter Mode).
6 * Copyright (c) 2009 Intel Corp.
9 * The algorithm implementation is copied from gcm.c.
12 #include <crypto/algapi.h>
13 #include <crypto/gf128mul.h>
14 #include <crypto/ghash.h>
15 #include <crypto/internal/hash.h>
16 #include <linux/crypto.h>
17 #include <linux/init.h>
18 #include <linux/kernel.h>
19 #include <linux/module.h>
21 static int ghash_init(struct shash_desc *desc)
23 struct ghash_desc_ctx *dctx = shash_desc_ctx(desc);
25 memset(dctx, 0, sizeof(*dctx));
30 static int ghash_setkey(struct crypto_shash *tfm,
31 const u8 *key, unsigned int keylen)
33 struct ghash_ctx *ctx = crypto_shash_ctx(tfm);
35 if (keylen != GHASH_BLOCK_SIZE) {
36 crypto_shash_set_flags(tfm, CRYPTO_TFM_RES_BAD_KEY_LEN);
41 gf128mul_free_4k(ctx->gf128);
42 ctx->gf128 = gf128mul_init_4k_lle((be128 *)key);
49 static int ghash_update(struct shash_desc *desc,
50 const u8 *src, unsigned int srclen)
52 struct ghash_desc_ctx *dctx = shash_desc_ctx(desc);
53 struct ghash_ctx *ctx = crypto_shash_ctx(desc->tfm);
54 u8 *dst = dctx->buffer;
57 int n = min(srclen, dctx->bytes);
58 u8 *pos = dst + (GHASH_BLOCK_SIZE - dctx->bytes);
67 gf128mul_4k_lle((be128 *)dst, ctx->gf128);
70 while (srclen >= GHASH_BLOCK_SIZE) {
71 crypto_xor(dst, src, GHASH_BLOCK_SIZE);
72 gf128mul_4k_lle((be128 *)dst, ctx->gf128);
73 src += GHASH_BLOCK_SIZE;
74 srclen -= GHASH_BLOCK_SIZE;
78 dctx->bytes = GHASH_BLOCK_SIZE - srclen;
86 static void ghash_flush(struct ghash_ctx *ctx, struct ghash_desc_ctx *dctx)
88 u8 *dst = dctx->buffer;
91 u8 *tmp = dst + (GHASH_BLOCK_SIZE - dctx->bytes);
96 gf128mul_4k_lle((be128 *)dst, ctx->gf128);
102 static int ghash_final(struct shash_desc *desc, u8 *dst)
104 struct ghash_desc_ctx *dctx = shash_desc_ctx(desc);
105 struct ghash_ctx *ctx = crypto_shash_ctx(desc->tfm);
106 u8 *buf = dctx->buffer;
108 ghash_flush(ctx, dctx);
109 memcpy(dst, buf, GHASH_BLOCK_SIZE);
114 static void ghash_exit_tfm(struct crypto_tfm *tfm)
116 struct ghash_ctx *ctx = crypto_tfm_ctx(tfm);
118 gf128mul_free_4k(ctx->gf128);
121 static struct shash_alg ghash_alg = {
122 .digestsize = GHASH_DIGEST_SIZE,
124 .update = ghash_update,
125 .final = ghash_final,
126 .setkey = ghash_setkey,
127 .descsize = sizeof(struct ghash_desc_ctx),
130 .cra_driver_name = "ghash-generic",
132 .cra_blocksize = GHASH_BLOCK_SIZE,
133 .cra_ctxsize = sizeof(struct ghash_ctx),
134 .cra_module = THIS_MODULE,
135 .cra_exit = ghash_exit_tfm,
139 static int __init ghash_mod_init(void)
141 return crypto_register_shash(&ghash_alg);
144 static void __exit ghash_mod_exit(void)
146 crypto_unregister_shash(&ghash_alg);
149 subsys_initcall(ghash_mod_init);
150 module_exit(ghash_mod_exit);
152 MODULE_LICENSE("GPL");
153 MODULE_DESCRIPTION("GHASH Message Digest Algorithm");
154 MODULE_ALIAS_CRYPTO("ghash");
155 MODULE_ALIAS_CRYPTO("ghash-generic");