1 /* Software-based Trusted Platform Module (TPM) Emulator
2 * Copyright (C) 2004-2010 Mario Strasser <mast@gmx.net>
3 *
4 * This module is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published
6 * by the Free Software Foundation; either version 2 of the License,
7 * or (at your option) any later version.
8 *
9 * This module is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * $Id: rc4.c 364 2010-02-11 10:24:45Z mast $
15 */
16
17 #include "rc4.h"
18
tpm_rc4_init(tpm_rc4_ctx_t * ctx,uint8_t * key,size_t key_len)19 void tpm_rc4_init(tpm_rc4_ctx_t *ctx, uint8_t *key, size_t key_len)
20 {
21 int i;
22 uint8_t a, j, k;
23
24 ctx->x = ctx->y = 0;
25 for (i = 0; i < 256; i++) {
26 ctx->state[i] = i;
27 }
28 for (i = j = k = 0; i < 256; i++) {
29 a = ctx->state[i];
30 j += a + key[k++];
31 ctx->state[i] = ctx->state[j];
32 ctx->state[j] = a;
33 if (k >= key_len) k = 0;
34 }
35 /* to strengthen the algorithm it is recommended to
36 discard the first few (say 256) octets */
37 for (i = 0; i < 16; i++) {
38 uint8_t buf[16];
39 tpm_rc4_crypt(ctx, buf, buf, sizeof(buf));
40 }
41 }
42
tpm_rc4_crypt(tpm_rc4_ctx_t * ctx,uint8_t * in,uint8_t * out,size_t length)43 void tpm_rc4_crypt(tpm_rc4_ctx_t *ctx, uint8_t *in, uint8_t *out, size_t length)
44 {
45 uint8_t a, x, y, *state;
46
47 x = ctx->x;
48 y = ctx->y;
49 state = ctx->state;
50 while (length--) {
51 x++;
52 y += state[x];
53 a = state[x];
54 state[x] = state[y];
55 state[y] = a;
56 a += state[x];
57 *out++ = *in++ ^ state[a];
58 }
59 ctx->x = x;
60 ctx->y = y;
61 }
62
63