summaryrefslogtreecommitdiffstats
path: root/grub-core/lib/adler32.c
blob: 43b68af62c140a1f3c66cf647a5b527a1f7b7389 (plain)
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/*
 *  GRUB  --  GRand Unified Bootloader
 *  Copyright (C) 2012  Free Software Foundation, Inc.
 *
 *  GRUB is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  GRUB is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with GRUB.  If not, see <http://www.gnu.org/licenses/>.
 */


#include <grub/dl.h>
#include <grub/crypto.h>

GRUB_MOD_LICENSE ("GPLv3+");

struct adler32_context
{
  grub_uint16_t a, b;
  grub_uint32_t c;
};

static void
adler32_init (void *context)
{
  struct adler32_context *ctx = context;

  ctx->a = 1;
  ctx->b = 0;
}

#define MOD 65521

static grub_uint16_t
mod_add (grub_uint16_t a, grub_uint16_t b)
{
  if ((grub_uint32_t) a + (grub_uint32_t) b >= MOD)
    return a + b - MOD;
  return a + b;
}

static void
adler32_write (void *context, const void *inbuf, grub_size_t inlen)
{
  struct adler32_context *ctx = context;
  const grub_uint8_t *ptr = inbuf;

  while (inlen)
    {
      ctx->a = mod_add (ctx->a, *ptr);
      ctx->b = mod_add (ctx->a, ctx->b);
      inlen--;
      ptr++;
    }
}

static void
adler32_final (void *context __attribute__ ((unused)))
{
}

static grub_uint8_t *
adler32_read (void *context)
{
  struct adler32_context *ctx = context;
  if (ctx->a > MOD)
    ctx->a -= MOD;
  if (ctx->b > MOD)
    ctx->b -= MOD;
  ctx->c = grub_cpu_to_be32 (ctx->a | (ctx->b << 16));
  return (grub_uint8_t *) &ctx->c;
}

static gcry_md_spec_t spec_adler32 =
  {
    "ADLER32", 0, 0, 0, 4,
    adler32_init, adler32_write, adler32_final, adler32_read,
    sizeof (struct adler32_context),
#ifdef GRUB_UTIL
    .modname = "adler32",
#endif
    .blocksize = 64
  };


GRUB_MOD_INIT(adler32)
{
  grub_md_register (&spec_adler32);
}

GRUB_MOD_FINI(adler32)
{
  grub_md_unregister (&spec_adler32);
}